Всё проще чем я думал.
ЛАБА 7 СДАНА!!!!!!!!!
This commit is contained in:
parent
a5e7f52516
commit
17d74c828b
6
l10n.yaml
Normal file
6
l10n.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
arb-dir: l10n
|
||||
template-arb-file: app_ru.arb
|
||||
output-localization-file: app_locale.dart
|
||||
output-dir: lib/components/locale/l10n
|
||||
output-class: AppLocale
|
||||
synthetic-package: false
|
9
l10n/app_en.arb
Normal file
9
l10n/app_en.arb
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"@@locale": "en",
|
||||
|
||||
"search": "Search",
|
||||
"liked": "liked!",
|
||||
"disliked": "disliked",
|
||||
|
||||
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
|
||||
}
|
9
l10n/app_ru.arb
Normal file
9
l10n/app_ru.arb
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"@@locale": "ru",
|
||||
|
||||
"search": "Поиск",
|
||||
"liked": "понравился!",
|
||||
"disliked": "разонравился",
|
||||
|
||||
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
|
||||
}
|
7
lib/components/extensions/context_x.dart
Normal file
7
lib/components/extensions/context_x.dart
Normal file
@ -0,0 +1,7 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../locale/l10n/app_locale.dart';
|
||||
|
||||
extension LocalContextX on BuildContext{
|
||||
AppLocale get locale => AppLocale.of(this)!; //делает удобное обращение к локале
|
||||
}
|
153
lib/components/locale/l10n/app_locale.dart
Normal file
153
lib/components/locale/l10n/app_locale.dart
Normal file
@ -0,0 +1,153 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
|
||||
import 'app_locale_en.dart';
|
||||
import 'app_locale_ru.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// Callers can lookup localized strings with an instance of AppLocale
|
||||
/// returned by `AppLocale.of(context)`.
|
||||
///
|
||||
/// Applications need to include `AppLocale.delegate()` in their app's
|
||||
/// `localizationDelegates` list, and the locales they support in the app's
|
||||
/// `supportedLocales` list. For example:
|
||||
///
|
||||
/// ```dart
|
||||
/// import 'l10n/app_locale.dart';
|
||||
///
|
||||
/// return MaterialApp(
|
||||
/// localizationsDelegates: AppLocale.localizationsDelegates,
|
||||
/// supportedLocales: AppLocale.supportedLocales,
|
||||
/// home: MyApplicationHome(),
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// ## Update pubspec.yaml
|
||||
///
|
||||
/// Please make sure to update your pubspec.yaml to include the following
|
||||
/// packages:
|
||||
///
|
||||
/// ```yaml
|
||||
/// dependencies:
|
||||
/// # Internationalization support.
|
||||
/// flutter_localizations:
|
||||
/// sdk: flutter
|
||||
/// intl: any # Use the pinned version from flutter_localizations
|
||||
///
|
||||
/// # Rest of dependencies
|
||||
/// ```
|
||||
///
|
||||
/// ## iOS Applications
|
||||
///
|
||||
/// iOS applications define key application metadata, including supported
|
||||
/// locales, in an Info.plist file that is built into the application bundle.
|
||||
/// To configure the locales supported by your app, you’ll need to edit this
|
||||
/// file.
|
||||
///
|
||||
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
|
||||
/// Then, in the Project Navigator, open the Info.plist file under the Runner
|
||||
/// project’s Runner folder.
|
||||
///
|
||||
/// Next, select the Information Property List item, select Add Item from the
|
||||
/// Editor menu, then select Localizations from the pop-up menu.
|
||||
///
|
||||
/// Select and expand the newly-created Localizations item then, for each
|
||||
/// locale your application supports, add a new item and select the locale
|
||||
/// you wish to add from the pop-up menu in the Value field. This list should
|
||||
/// be consistent with the languages listed in the AppLocale.supportedLocales
|
||||
/// property.
|
||||
abstract class AppLocale {
|
||||
AppLocale(String locale) : localeName = intl.Intl.canonicalizedLocale(locale.toString());
|
||||
|
||||
final String localeName;
|
||||
|
||||
static AppLocale? of(BuildContext context) {
|
||||
return Localizations.of<AppLocale>(context, AppLocale);
|
||||
}
|
||||
|
||||
static const LocalizationsDelegate<AppLocale> delegate = _AppLocaleDelegate();
|
||||
|
||||
/// A list of this localizations delegate along with the default localizations
|
||||
/// delegates.
|
||||
///
|
||||
/// Returns a list of localizations delegates containing this delegate along with
|
||||
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
|
||||
/// and GlobalWidgetsLocalizations.delegate.
|
||||
///
|
||||
/// Additional delegates can be added by appending to this list in
|
||||
/// MaterialApp. This list does not have to be used at all if a custom list
|
||||
/// of delegates is preferred or required.
|
||||
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
|
||||
delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
];
|
||||
|
||||
/// A list of this localizations delegate's supported locales.
|
||||
static const List<Locale> supportedLocales = <Locale>[
|
||||
Locale('en'),
|
||||
Locale('ru')
|
||||
];
|
||||
|
||||
/// No description provided for @search.
|
||||
///
|
||||
/// In ru, this message translates to:
|
||||
/// **'Поиск'**
|
||||
String get search;
|
||||
|
||||
/// No description provided for @liked.
|
||||
///
|
||||
/// In ru, this message translates to:
|
||||
/// **'понравился!'**
|
||||
String get liked;
|
||||
|
||||
/// No description provided for @disliked.
|
||||
///
|
||||
/// In ru, this message translates to:
|
||||
/// **'разонравился'**
|
||||
String get disliked;
|
||||
|
||||
/// No description provided for @arbEnding.
|
||||
///
|
||||
/// In ru, this message translates to:
|
||||
/// **'Чтобы не забыть про отсутствие запятой :)'**
|
||||
String get arbEnding;
|
||||
}
|
||||
|
||||
class _AppLocaleDelegate extends LocalizationsDelegate<AppLocale> {
|
||||
const _AppLocaleDelegate();
|
||||
|
||||
@override
|
||||
Future<AppLocale> load(Locale locale) {
|
||||
return SynchronousFuture<AppLocale>(lookupAppLocale(locale));
|
||||
}
|
||||
|
||||
@override
|
||||
bool isSupported(Locale locale) => <String>['en', 'ru'].contains(locale.languageCode);
|
||||
|
||||
@override
|
||||
bool shouldReload(_AppLocaleDelegate old) => false;
|
||||
}
|
||||
|
||||
AppLocale lookupAppLocale(Locale locale) {
|
||||
|
||||
|
||||
// Lookup logic when only language code is specified.
|
||||
switch (locale.languageCode) {
|
||||
case 'en': return AppLocaleEn();
|
||||
case 'ru': return AppLocaleRu();
|
||||
}
|
||||
|
||||
throw FlutterError(
|
||||
'AppLocale.delegate failed to load unsupported locale "$locale". This is likely '
|
||||
'an issue with the localizations generation tool. Please file an issue '
|
||||
'on GitHub with a reproducible sample app and the gen-l10n configuration '
|
||||
'that was used.'
|
||||
);
|
||||
}
|
20
lib/components/locale/l10n/app_locale_en.dart
Normal file
20
lib/components/locale/l10n/app_locale_en.dart
Normal file
@ -0,0 +1,20 @@
|
||||
import 'app_locale.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// The translations for English (`en`).
|
||||
class AppLocaleEn extends AppLocale {
|
||||
AppLocaleEn([String locale = 'en']) : super(locale);
|
||||
|
||||
@override
|
||||
String get search => 'Search';
|
||||
|
||||
@override
|
||||
String get liked => 'liked!';
|
||||
|
||||
@override
|
||||
String get disliked => 'disliked';
|
||||
|
||||
@override
|
||||
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
|
||||
}
|
20
lib/components/locale/l10n/app_locale_ru.dart
Normal file
20
lib/components/locale/l10n/app_locale_ru.dart
Normal file
@ -0,0 +1,20 @@
|
||||
import 'app_locale.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// The translations for Russian (`ru`).
|
||||
class AppLocaleRu extends AppLocale {
|
||||
AppLocaleRu([String locale = 'ru']) : super(locale);
|
||||
|
||||
@override
|
||||
String get search => 'Поиск';
|
||||
|
||||
@override
|
||||
String get liked => 'понравился!';
|
||||
|
||||
@override
|
||||
String get disliked => 'разонравился';
|
||||
|
||||
@override
|
||||
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
|
||||
}
|
12
lib/components/resources.g.dart
Normal file
12
lib/components/resources.g.dart
Normal file
@ -0,0 +1,12 @@
|
||||
/// Generate by [flutter_assets_generator](https://github.com/goodswifter/flutter_assets_generator) library.
|
||||
///
|
||||
/// PLEASE DO NOT EDIT MANUALLY.
|
||||
class R { // сгенерировали пути до наших ресурсов
|
||||
const R._();
|
||||
|
||||
/// ![preview](file://C:\Users\shotb\StudioProjects\pmu_labs\assets\svg\ru.svg)
|
||||
static const String assetsSvgRuSvg = 'assets/svg/ru.svg';
|
||||
|
||||
/// ![preview](file://C:\Users\shotb\StudioProjects\pmu_labs\assets\svg\uk.svg)
|
||||
static const String assetsSvgUkSvg = 'assets/svg/uk.svg';
|
||||
}
|
@ -12,12 +12,13 @@ class CharactersDto {
|
||||
|
||||
@JsonSerializable(createToJson: false)
|
||||
class CharacterDto {
|
||||
final String? uuid;
|
||||
final String? displayName;
|
||||
final String? displayIcon;
|
||||
final String? description;
|
||||
final String? developerName;
|
||||
|
||||
const CharacterDto({this.displayName, this.displayIcon, this.description, this.developerName});
|
||||
const CharacterDto({this.uuid, this.displayName, this.displayIcon, this.description, this.developerName});
|
||||
|
||||
factory CharacterDto.fromJson(Map<String, dynamic> json) => _$CharacterDtoFromJson(json);
|
||||
}
|
||||
|
@ -6,14 +6,14 @@ part of 'characters_dto.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) =>
|
||||
CharactersDto(
|
||||
CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) => CharactersDto(
|
||||
data: (json['data'] as List<dynamic>?)
|
||||
?.map((e) => CharacterDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
CharacterDto _$CharacterDtoFromJson(Map<String, dynamic> json) => CharacterDto(
|
||||
uuid: json['uuid'] as String?,
|
||||
displayName: json['displayName'] as String?,
|
||||
displayIcon: json['displayIcon'] as String?,
|
||||
description: json['description'] as String?,
|
||||
|
@ -4,6 +4,7 @@ import '../dtos/characters_dto.dart';
|
||||
extension CharacterDtoToModel on CharacterDto {
|
||||
CardData toDomain() => CardData(
|
||||
displayName ?? 'UNKNOWN',
|
||||
uuid: uuid ?? 'UNKNOWN',
|
||||
descriptionText: developerName ?? 'Описание отсутствует',
|
||||
gameDesc: description,
|
||||
imageUrl: displayIcon,
|
||||
|
@ -13,7 +13,7 @@ class AgentsRepository extends ApiInterface {
|
||||
requestBody: true,
|
||||
));
|
||||
|
||||
static const String _baseUrl = 'https://valorant-api.com/v1/ agents';
|
||||
static const String _baseUrl = 'https://valorant-api.com/v1/agents';
|
||||
|
||||
@override
|
||||
Future<List<CardData>?> loadData({
|
||||
|
@ -6,6 +6,7 @@ class MockRepository extends ApiInterface {
|
||||
Future<List<CardData>?> loadData() async {
|
||||
return [
|
||||
CardData('Far Cry 1',
|
||||
uuid: '1',
|
||||
descriptionText: 'Так себе',
|
||||
imageUrl:
|
||||
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg',
|
||||
@ -16,6 +17,7 @@ class MockRepository extends ApiInterface {
|
||||
'ужасам Галактики в эпических боях сразу на нескольких планетах. Раскройте мрачные секреты и отбросьте тень вечной ночи.'), // создаётся объект ранее созданного контейнера
|
||||
CardData('Far Cry 2',
|
||||
descriptionText: 'Лучше',
|
||||
uuid: '2',
|
||||
imageUrl:
|
||||
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg',
|
||||
gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' +
|
||||
@ -25,6 +27,7 @@ class MockRepository extends ApiInterface {
|
||||
'ужасам Галактики в эпических боях сразу на нескольких планетах. Раскройте мрачные секреты и отбросьте тень вечной ночи.'),
|
||||
CardData('Far Cry 3',
|
||||
descriptionText: 'Красавцы',
|
||||
uuid: '3',
|
||||
imageUrl:
|
||||
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg',
|
||||
gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' +
|
||||
|
@ -6,12 +6,13 @@ class CardData {
|
||||
//final IconData icon;
|
||||
final String? imageUrl;
|
||||
final String? gameDesc;
|
||||
late final String uuid;
|
||||
|
||||
CardData(
|
||||
this.text, {
|
||||
required this.descriptionText,
|
||||
//this.icon = Icons.ac_unit_outlined,
|
||||
this.imageUrl,
|
||||
required this.gameDesc,
|
||||
required this.uuid,
|
||||
});
|
||||
}
|
||||
|
@ -1,6 +1,11 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/home_page/bloc/bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_state.dart';
|
||||
import 'components/locale/l10n/app_locale.dart';
|
||||
import 'data/repositories/characters_repository.dart';
|
||||
import 'presentation/home_page/home_page.dart';
|
||||
|
||||
@ -13,25 +18,37 @@ class MyApp extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Flutter Demo',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: RepositoryProvider<AgentsRepository>(
|
||||
//даём нашему репозиторию доступ
|
||||
lazy: true, //ленивое создание объекта
|
||||
create: (_) => AgentsRepository(),
|
||||
child: BlocProvider<HomeBloc>(
|
||||
//даём доступ Bloc для нашей страницы
|
||||
lazy: false,
|
||||
create: (context) => HomeBloc(context.read<
|
||||
AgentsRepository>()), //в конструктор нашего Блока передаём репозиторий с нашей апи, то есть у нас появляется доступ по дереву к апи
|
||||
child: const MyHomePage(title: 'Агенты Valorant'),
|
||||
return BlocProvider<LocaleBloc>(
|
||||
lazy: false,
|
||||
create: (context) => LocaleBloc(Locale(Platform.localeName)),
|
||||
child: BlocBuilder<LocaleBloc, LocaleState>( //Передаём текущую локаль
|
||||
builder: (context, state) {
|
||||
return MaterialApp(
|
||||
title: 'Flutter Demo',
|
||||
locale: state.currentLocale,
|
||||
localizationsDelegates: AppLocale.localizationsDelegates,
|
||||
supportedLocales: AppLocale.supportedLocales,// подключаем список доступных локалей
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurpleAccent),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: RepositoryProvider<AgentsRepository>(
|
||||
lazy: true,
|
||||
create: (_) => AgentsRepository(),
|
||||
child: BlocProvider<LikeBloc>(
|
||||
lazy: false,
|
||||
create: (context) => LikeBloc(),
|
||||
child: BlocProvider<HomeBloc>(
|
||||
lazy: false,
|
||||
create: (context) => HomeBloc(context.read<AgentsRepository>()),
|
||||
child: const MyHomePage(title: 'Агенты Valorant'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
34
lib/presentation/common/svg_objects.dart
Normal file
34
lib/presentation/common/svg_objects.dart
Normal file
@ -0,0 +1,34 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
import '../../components/resources.g.dart';
|
||||
|
||||
abstract class SvgObjects {
|
||||
static void init() { // подгрузка иконок в кеш перед их использованием
|
||||
final pics = <String>[
|
||||
R.assetsSvgRuSvg,
|
||||
R.assetsSvgUkSvg,
|
||||
];
|
||||
for (final String p in pics) {
|
||||
final loader = SvgAssetLoader(p);
|
||||
svg.cache.putIfAbsent(loader.cacheKey(null), () => loader.loadBytes(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SvgRu extends StatelessWidget {
|
||||
const SvgRu({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SvgPicture.asset(R.assetsSvgRuSvg);
|
||||
}
|
||||
}
|
||||
|
||||
class SvgUk extends StatelessWidget {
|
||||
const SvgUk({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SvgPicture.asset(R.assetsSvgUkSvg);
|
||||
}
|
||||
}
|
@ -1,14 +1,16 @@
|
||||
part of 'home_page.dart';
|
||||
|
||||
typedef OnLikeCallback = void Function(String title, bool isLiked); //сделано от дублирования кода
|
||||
typedef OnLikeCallback = void Function(String? id, String title, bool isLiked); //сделано от дублирования кода
|
||||
|
||||
class _Card extends StatefulWidget {
|
||||
class _Card extends StatelessWidget {
|
||||
final String text;
|
||||
final String descriptionText;
|
||||
//final IconData icon;
|
||||
final String? imageUrl;
|
||||
final OnLikeCallback? onLike;
|
||||
final VoidCallback? onTap;
|
||||
final String uuid;
|
||||
final bool isLiked;
|
||||
|
||||
const _Card(
|
||||
this.text, {
|
||||
@ -17,31 +19,30 @@ class _Card extends StatefulWidget {
|
||||
this.imageUrl,
|
||||
this.onLike,
|
||||
this.onTap,
|
||||
required this.uuid,
|
||||
this.isLiked = false,
|
||||
});
|
||||
|
||||
factory _Card.fromData(
|
||||
CardData data, {
|
||||
OnLikeCallback? onLike,
|
||||
VoidCallback? onTap,
|
||||
bool isLiked = false,
|
||||
}) =>
|
||||
_Card(
|
||||
uuid: data.uuid,
|
||||
data.text!,
|
||||
descriptionText: data.descriptionText!,
|
||||
imageUrl: data.imageUrl,
|
||||
onLike: onLike,
|
||||
onTap: onTap,
|
||||
isLiked: isLiked,
|
||||
);
|
||||
|
||||
@override
|
||||
State<_Card> createState() => _CardState();
|
||||
}
|
||||
|
||||
class _CardState extends State<_Card> {
|
||||
bool isLiked = false;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Container(
|
||||
@ -72,7 +73,7 @@ class _CardState extends State<_Card> {
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: Image.network(
|
||||
widget.imageUrl ?? '',
|
||||
imageUrl ?? '',
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => const Placeholder(),
|
||||
),
|
||||
@ -107,12 +108,18 @@ class _CardState extends State<_Card> {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
widget.text,
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
text,
|
||||
style: Theme
|
||||
.of(context)
|
||||
.textTheme
|
||||
.titleLarge,
|
||||
),
|
||||
Text(
|
||||
widget.descriptionText,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
descriptionText,
|
||||
style: Theme
|
||||
.of(context)
|
||||
.textTheme
|
||||
.bodyLarge,
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -127,25 +134,20 @@ class _CardState extends State<_Card> {
|
||||
bottom: 16,
|
||||
),
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
isLiked = !isLiked; // установка лайков
|
||||
});
|
||||
widget.onLike?.call(widget.text, isLiked);
|
||||
},
|
||||
onTap: () => onLike?.call(uuid, text, isLiked),
|
||||
child: AnimatedSwitcher(
|
||||
// Анимация для наших лайков
|
||||
duration: const Duration(milliseconds: 300),
|
||||
child: isLiked
|
||||
? const Icon(
|
||||
Icons.favorite,
|
||||
color: Colors.redAccent,
|
||||
key: ValueKey<int>(0), // ключи для перерисовки
|
||||
color: Colors.purpleAccent,
|
||||
key: ValueKey<int>(0),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.favorite_border,
|
||||
key: ValueKey<int>(1), // ключи для перерисовки
|
||||
),
|
||||
Icons.favorite_border,
|
||||
key: ValueKey<int>(1),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
@ -1,10 +1,18 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_test_app/components/extensions/context_x.dart';
|
||||
import 'package:flutter_test_app/data/repositories/mock_repository.dart';
|
||||
import 'package:flutter_test_app/main.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_event.dart';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_state.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_events.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_state.dart';
|
||||
import '../../data/repositories/characters_repository.dart';
|
||||
import '../../domain/models/card.dart';
|
||||
import '../common/svg_objects.dart';
|
||||
import '../details_page/details_page.dart';
|
||||
import 'bloc/bloc.dart';
|
||||
import 'bloc/events.dart';
|
||||
@ -49,9 +57,11 @@ class _BodyState extends State<Body> {
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
SvgObjects.init();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
// привязываем логику к кадру
|
||||
context.read<HomeBloc>().add(const HomeLoadDataEvent()); // добавляем данные после считывания
|
||||
context.read<LikeBloc>().add(const LoadLikesEvent()); // загрузка лайков которые ставили в прошлый раз
|
||||
});
|
||||
super.initState();
|
||||
}
|
||||
@ -84,18 +94,50 @@ class _BodyState extends State<Body> {
|
||||
}
|
||||
}
|
||||
|
||||
void _onLike(String? id, String title, bool isLiked) {
|
||||
if (id != null) {
|
||||
context.read<LikeBloc>().add(ChangeLikeEvent(id));
|
||||
_showSnackBar(context, title , !isLiked);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: CupertinoSearchTextField(
|
||||
controller: searchController,
|
||||
onChanged: (search) {
|
||||
//вызов задержки пока пользователь не перестанет печатать в поисковой строке
|
||||
Debounce.run(() => context.read<HomeBloc>().add(HomeLoadDataEvent(search: search)));
|
||||
},
|
||||
child: Row( // наше поле для поиска
|
||||
children: [
|
||||
Expanded(
|
||||
child: CupertinoSearchTextField( // переписали под наши локали
|
||||
controller: searchController,
|
||||
placeholder: context.locale.search,
|
||||
onChanged: (search) {
|
||||
Debounce.run(() => context
|
||||
.read<HomeBloc>()
|
||||
.add(HomeLoadDataEvent(search: search)));
|
||||
},
|
||||
),
|
||||
),
|
||||
GestureDetector( // иконки для смены локали
|
||||
onTap: () =>
|
||||
context.read<LocaleBloc>().add(const ChangeLocaleEvent()), //меняет в зависимости от текущей локализации
|
||||
child: SizedBox.square(
|
||||
dimension: 50,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 12),
|
||||
child: BlocBuilder<LocaleBloc, LocaleState>(
|
||||
builder: (context, state) {
|
||||
return state.currentLocale.languageCode == 'ru'
|
||||
? const SvgRu()
|
||||
: const SvgUk(); // иконки из ассетов
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
BlocBuilder<HomeBloc, HomeState>(
|
||||
@ -107,23 +149,25 @@ class _BodyState extends State<Body> {
|
||||
)
|
||||
: state.isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: _onRefresh,
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: state.data?.length ?? 0,
|
||||
itemBuilder: (context, index) {
|
||||
final data = state.data?[index];
|
||||
return data != null
|
||||
? _Card.fromData(
|
||||
data,
|
||||
onLike: (String title, bool isLiked) =>
|
||||
_showSnackBar(context, title, isLiked),
|
||||
onTap: () => _navToDetails(context, data),
|
||||
)
|
||||
: const SizedBox.shrink();
|
||||
},
|
||||
: BlocBuilder<LikeBloc, LikeState>( // проверяем в зависимости от стейта, лайкнута ли карточка
|
||||
builder: (context, likeState) => Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: _onRefresh,
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: state.data?.length ?? 0,
|
||||
itemBuilder: (context, index) {
|
||||
final data = state.data?[index];
|
||||
return data != null
|
||||
? _Card.fromData(
|
||||
data,
|
||||
onLike: _onLike,
|
||||
isLiked: likeState.likedIds?.contains(data.uuid) == true,
|
||||
onTap: () => _navToDetails(context, data),
|
||||
)
|
||||
: const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@ -143,7 +187,7 @@ class _BodyState extends State<Body> {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(
|
||||
'News $title ${isLiked ? 'liked' : 'disliked '}',
|
||||
'$title ${isLiked ? context.locale.liked : context.locale.disliked}', // переписали под наши локали
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
backgroundColor: Colors.deepPurpleAccent,
|
||||
|
34
lib/presentation/like_bloc/like_bloc.dart
Normal file
34
lib/presentation/like_bloc/like_bloc.dart
Normal file
@ -0,0 +1,34 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart%20%20';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_event.dart';
|
||||
import 'package:flutter_test_app/presentation/like_bloc/like_state.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const String _likedPrefsKey = 'liked';
|
||||
|
||||
class LikeBloc extends Bloc<LikeEvent, LikeState>{
|
||||
LikeBloc() : super(const LikeState(likedIds: [])){
|
||||
on<ChangeLikeEvent>(_onChangeLike);
|
||||
on<LoadLikesEvent>(_onLoadLikes);
|
||||
}
|
||||
|
||||
Future<void> _onLoadLikes(LoadLikesEvent event, Emitter<LikeState> emit) async{
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final data = prefs.getStringList(_likedPrefsKey);
|
||||
|
||||
emit(state.copyWith(likedIds: data));
|
||||
}
|
||||
|
||||
Future<void> _onChangeLike(ChangeLikeEvent event, Emitter<LikeState> emit) async{
|
||||
final updatedList = List<String>.from(state.likedIds ?? []);
|
||||
|
||||
if(updatedList.contains(event.id)){ // проверка установлен ли лайк
|
||||
updatedList.remove(event.id);
|
||||
} else{
|
||||
updatedList.add(event.id);
|
||||
}
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
prefs.setStringList(_likedPrefsKey, updatedList);
|
||||
emit(state.copyWith(likedIds: updatedList));
|
||||
}
|
||||
}
|
13
lib/presentation/like_bloc/like_event.dart
Normal file
13
lib/presentation/like_bloc/like_event.dart
Normal file
@ -0,0 +1,13 @@
|
||||
abstract class LikeEvent{
|
||||
const LikeEvent();
|
||||
}
|
||||
|
||||
class LoadLikesEvent extends LikeEvent{
|
||||
const LoadLikesEvent();
|
||||
}
|
||||
|
||||
class ChangeLikeEvent extends LikeEvent{
|
||||
final String id;
|
||||
|
||||
const ChangeLikeEvent(this.id);
|
||||
}
|
14
lib/presentation/like_bloc/like_state.dart
Normal file
14
lib/presentation/like_bloc/like_state.dart
Normal file
@ -0,0 +1,14 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
part 'like_state.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class LikeState extends Equatable{
|
||||
final List<String>? likedIds;
|
||||
|
||||
const LikeState({required this.likedIds});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [likedIds];
|
||||
}
|
56
lib/presentation/like_bloc/like_state.g.dart
Normal file
56
lib/presentation/like_bloc/like_state.g.dart
Normal file
@ -0,0 +1,56 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'like_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$LikeStateCWProxy {
|
||||
LikeState likedIds(List<String>? likedIds);
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LikeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// LikeState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
LikeState call({
|
||||
List<String>? likedIds,
|
||||
});
|
||||
}
|
||||
|
||||
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfLikeState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfLikeState.copyWith.fieldName(...)`
|
||||
class _$LikeStateCWProxyImpl implements _$LikeStateCWProxy {
|
||||
const _$LikeStateCWProxyImpl(this._value);
|
||||
|
||||
final LikeState _value;
|
||||
|
||||
@override
|
||||
LikeState likedIds(List<String>? likedIds) => this(likedIds: likedIds);
|
||||
|
||||
@override
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LikeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// LikeState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
LikeState call({
|
||||
Object? likedIds = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return LikeState(
|
||||
likedIds: likedIds == const $CopyWithPlaceholder()
|
||||
? _value.likedIds
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: likedIds as List<String>?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $LikeStateCopyWith on LikeState {
|
||||
/// Returns a callable class that can be used as follows: `instanceOfLikeState.copyWith(...)` or like so:`instanceOfLikeState.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$LikeStateCWProxy get copyWith => _$LikeStateCWProxyImpl(this);
|
||||
}
|
16
lib/presentation/locale_bloc/locale_bloc.dart
Normal file
16
lib/presentation/locale_bloc/locale_bloc.dart
Normal file
@ -0,0 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_events.dart';
|
||||
import 'package:flutter_test_app/presentation/locale_bloc/locale_state.dart';
|
||||
import '../../components/locale/l10n/app_locale.dart';
|
||||
|
||||
class LocaleBloc extends Bloc<LocaleEvent, LocaleState>{
|
||||
LocaleBloc(Locale defaultLocale) : super(LocaleState(currentLocale: defaultLocale)){
|
||||
on<ChangeLocaleEvent>(_onChangeLocale);
|
||||
}
|
||||
|
||||
Future<void> _onChangeLocale(ChangeLocaleEvent event, Emitter<LocaleState> emit) async {
|
||||
final toChange = AppLocale.supportedLocales.firstWhere((e) => e.languageCode != state.currentLocale.languageCode);
|
||||
emit(state.copyWith(currentLocale: toChange));
|
||||
}
|
||||
}
|
7
lib/presentation/locale_bloc/locale_events.dart
Normal file
7
lib/presentation/locale_bloc/locale_events.dart
Normal file
@ -0,0 +1,7 @@
|
||||
abstract class LocaleEvent{
|
||||
const LocaleEvent();
|
||||
}
|
||||
|
||||
class ChangeLocaleEvent extends LocaleEvent{
|
||||
const ChangeLocaleEvent();
|
||||
}
|
15
lib/presentation/locale_bloc/locale_state.dart
Normal file
15
lib/presentation/locale_bloc/locale_state.dart
Normal file
@ -0,0 +1,15 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
part 'locale_state.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class LocaleState extends Equatable {
|
||||
final Locale currentLocale;
|
||||
|
||||
const LocaleState({required this.currentLocale});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [currentLocale];
|
||||
}
|
58
lib/presentation/locale_bloc/locale_state.g.dart
Normal file
58
lib/presentation/locale_bloc/locale_state.g.dart
Normal file
@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'locale_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$LocaleStateCWProxy {
|
||||
LocaleState currentLocale(Locale currentLocale);
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LocaleState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// LocaleState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
LocaleState call({
|
||||
Locale? currentLocale,
|
||||
});
|
||||
}
|
||||
|
||||
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfLocaleState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfLocaleState.copyWith.fieldName(...)`
|
||||
class _$LocaleStateCWProxyImpl implements _$LocaleStateCWProxy {
|
||||
const _$LocaleStateCWProxyImpl(this._value);
|
||||
|
||||
final LocaleState _value;
|
||||
|
||||
@override
|
||||
LocaleState currentLocale(Locale currentLocale) =>
|
||||
this(currentLocale: currentLocale);
|
||||
|
||||
@override
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LocaleState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// LocaleState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
LocaleState call({
|
||||
Object? currentLocale = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return LocaleState(
|
||||
currentLocale:
|
||||
currentLocale == const $CopyWithPlaceholder() || currentLocale == null
|
||||
? _value.currentLocale
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: currentLocale as Locale,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $LocaleStateCopyWith on LocaleState {
|
||||
/// Returns a callable class that can be used as follows: `instanceOfLocaleState.copyWith(...)` or like so:`instanceOfLocaleState.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$LocaleStateCWProxy get copyWith => _$LocaleStateCWProxyImpl(this);
|
||||
}
|
Loading…
Reference in New Issue
Block a user