From 17d74c828bb0c3b55cabd0c1260fc21d74bca0bf Mon Sep 17 00:00:00 2001 From: Stepan Date: Thu, 12 Dec 2024 16:20:42 +0400 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=81=D1=91=20=D0=BF=D1=80=D0=BE=D1=89?= =?UTF-8?q?=D0=B5=20=D1=87=D0=B5=D0=BC=20=D1=8F=20=D0=B4=D1=83=D0=BC=D0=B0?= =?UTF-8?q?=D0=BB.=20=D0=9B=D0=90=D0=91=D0=90=207=20=D0=A1=D0=94=D0=90?= =?UTF-8?q?=D0=9D=D0=90!!!!!!!!!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- l10n.yaml | 6 + l10n/app_en.arb | 9 ++ l10n/app_ru.arb | 9 ++ lib/components/extensions/context_x.dart | 7 + lib/components/locale/l10n/app_locale.dart | 153 ++++++++++++++++++ lib/components/locale/l10n/app_locale_en.dart | 20 +++ lib/components/locale/l10n/app_locale_ru.dart | 20 +++ lib/components/resources.g.dart | 12 ++ lib/data/dtos/characters_dto.dart | 3 +- lib/data/dtos/characters_dto.g.dart | 4 +- lib/data/mappers/characters_mapper.dart | 1 + .../repositories/characters_repository.dart | 2 +- lib/data/repositories/mock_repository.dart | 3 + lib/domain/models/card.dart | 3 +- lib/main.dart | 53 +++--- lib/presentation/common/svg_objects.dart | 34 ++++ lib/presentation/home_page/card.dart | 52 +++--- lib/presentation/home_page/home_page.dart | 92 ++++++++--- lib/presentation/like_bloc/like_bloc.dart | 34 ++++ lib/presentation/like_bloc/like_event.dart | 13 ++ lib/presentation/like_bloc/like_state.dart | 14 ++ lib/presentation/like_bloc/like_state.g.dart | 56 +++++++ lib/presentation/locale_bloc/locale_bloc.dart | 16 ++ .../locale_bloc/locale_events.dart | 7 + .../locale_bloc/locale_state.dart | 15 ++ .../locale_bloc/locale_state.g.dart | 58 +++++++ makefile | 3 + 27 files changed, 627 insertions(+), 72 deletions(-) create mode 100644 l10n.yaml create mode 100644 l10n/app_en.arb create mode 100644 l10n/app_ru.arb create mode 100644 lib/components/extensions/context_x.dart create mode 100644 lib/components/locale/l10n/app_locale.dart create mode 100644 lib/components/locale/l10n/app_locale_en.dart create mode 100644 lib/components/locale/l10n/app_locale_ru.dart create mode 100644 lib/components/resources.g.dart create mode 100644 lib/presentation/common/svg_objects.dart create mode 100644 lib/presentation/like_bloc/like_bloc.dart create mode 100644 lib/presentation/like_bloc/like_event.dart create mode 100644 lib/presentation/like_bloc/like_state.dart create mode 100644 lib/presentation/like_bloc/like_state.g.dart create mode 100644 lib/presentation/locale_bloc/locale_bloc.dart create mode 100644 lib/presentation/locale_bloc/locale_events.dart create mode 100644 lib/presentation/locale_bloc/locale_state.dart create mode 100644 lib/presentation/locale_bloc/locale_state.g.dart diff --git a/l10n.yaml b/l10n.yaml new file mode 100644 index 0000000..d26d702 --- /dev/null +++ b/l10n.yaml @@ -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 \ No newline at end of file diff --git a/l10n/app_en.arb b/l10n/app_en.arb new file mode 100644 index 0000000..3059e44 --- /dev/null +++ b/l10n/app_en.arb @@ -0,0 +1,9 @@ + { + "@@locale": "en", + + "search": "Search", + "liked": "liked!", + "disliked": "disliked", + + "arbEnding": "Чтобы не забыть про отсутствие запятой :)" +} \ No newline at end of file diff --git a/l10n/app_ru.arb b/l10n/app_ru.arb new file mode 100644 index 0000000..b823375 --- /dev/null +++ b/l10n/app_ru.arb @@ -0,0 +1,9 @@ +{ + "@@locale": "ru", + + "search": "Поиск", + "liked": "понравился!", + "disliked": "разонравился", + + "arbEnding": "Чтобы не забыть про отсутствие запятой :)" +} \ No newline at end of file diff --git a/lib/components/extensions/context_x.dart b/lib/components/extensions/context_x.dart new file mode 100644 index 0000000..08f4994 --- /dev/null +++ b/lib/components/extensions/context_x.dart @@ -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)!; //делает удобное обращение к локале +} \ No newline at end of file diff --git a/lib/components/locale/l10n/app_locale.dart b/lib/components/locale/l10n/app_locale.dart new file mode 100644 index 0000000..1a23eb7 --- /dev/null +++ b/lib/components/locale/l10n/app_locale.dart @@ -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(context, AppLocale); + } + + static const LocalizationsDelegate 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> localizationsDelegates = >[ + delegate, + GlobalMaterialLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ]; + + /// A list of this localizations delegate's supported locales. + static const List supportedLocales = [ + 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 { + const _AppLocaleDelegate(); + + @override + Future load(Locale locale) { + return SynchronousFuture(lookupAppLocale(locale)); + } + + @override + bool isSupported(Locale locale) => ['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.' + ); +} diff --git a/lib/components/locale/l10n/app_locale_en.dart b/lib/components/locale/l10n/app_locale_en.dart new file mode 100644 index 0000000..8f9dc19 --- /dev/null +++ b/lib/components/locale/l10n/app_locale_en.dart @@ -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 => 'Чтобы не забыть про отсутствие запятой :)'; +} diff --git a/lib/components/locale/l10n/app_locale_ru.dart b/lib/components/locale/l10n/app_locale_ru.dart new file mode 100644 index 0000000..4685a92 --- /dev/null +++ b/lib/components/locale/l10n/app_locale_ru.dart @@ -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 => 'Чтобы не забыть про отсутствие запятой :)'; +} diff --git a/lib/components/resources.g.dart b/lib/components/resources.g.dart new file mode 100644 index 0000000..cd54bcb --- /dev/null +++ b/lib/components/resources.g.dart @@ -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'; +} diff --git a/lib/data/dtos/characters_dto.dart b/lib/data/dtos/characters_dto.dart index 14c929e..17fc33a 100644 --- a/lib/data/dtos/characters_dto.dart +++ b/lib/data/dtos/characters_dto.dart @@ -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 json) => _$CharacterDtoFromJson(json); } diff --git a/lib/data/dtos/characters_dto.g.dart b/lib/data/dtos/characters_dto.g.dart index f59b735..4171075 100644 --- a/lib/data/dtos/characters_dto.g.dart +++ b/lib/data/dtos/characters_dto.g.dart @@ -6,14 +6,14 @@ part of 'characters_dto.dart'; // JsonSerializableGenerator // ************************************************************************** -CharactersDto _$CharactersDtoFromJson(Map json) => - CharactersDto( +CharactersDto _$CharactersDtoFromJson(Map json) => CharactersDto( data: (json['data'] as List?) ?.map((e) => CharacterDto.fromJson(e as Map)) .toList(), ); CharacterDto _$CharacterDtoFromJson(Map json) => CharacterDto( + uuid: json['uuid'] as String?, displayName: json['displayName'] as String?, displayIcon: json['displayIcon'] as String?, description: json['description'] as String?, diff --git a/lib/data/mappers/characters_mapper.dart b/lib/data/mappers/characters_mapper.dart index 6e10678..8ce0ce9 100644 --- a/lib/data/mappers/characters_mapper.dart +++ b/lib/data/mappers/characters_mapper.dart @@ -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, diff --git a/lib/data/repositories/characters_repository.dart b/lib/data/repositories/characters_repository.dart index b400691..ec2e53d 100644 --- a/lib/data/repositories/characters_repository.dart +++ b/lib/data/repositories/characters_repository.dart @@ -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?> loadData({ diff --git a/lib/data/repositories/mock_repository.dart b/lib/data/repositories/mock_repository.dart index 85dc4a4..8efae74 100644 --- a/lib/data/repositories/mock_repository.dart +++ b/lib/data/repositories/mock_repository.dart @@ -6,6 +6,7 @@ class MockRepository extends ApiInterface { Future?> 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: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' + diff --git a/lib/domain/models/card.dart b/lib/domain/models/card.dart index fcdc380..27c9721 100644 --- a/lib/domain/models/card.dart +++ b/lib/domain/models/card.dart @@ -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, }); } diff --git a/lib/main.dart b/lib/main.dart index 270757f..604d47d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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( - //даём нашему репозиторию доступ - lazy: true, //ленивое создание объекта - create: (_) => AgentsRepository(), - child: BlocProvider( - //даём доступ Bloc для нашей страницы - lazy: false, - create: (context) => HomeBloc(context.read< - AgentsRepository>()), //в конструктор нашего Блока передаём репозиторий с нашей апи, то есть у нас появляется доступ по дереву к апи - child: const MyHomePage(title: 'Агенты Valorant'), + return BlocProvider( + lazy: false, + create: (context) => LocaleBloc(Locale(Platform.localeName)), + child: BlocBuilder( //Передаём текущую локаль + 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( + lazy: true, + create: (_) => AgentsRepository(), + child: BlocProvider( + lazy: false, + create: (context) => LikeBloc(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const MyHomePage(title: 'Агенты Valorant'), + ), + ), + ), + ); + } ), - ), ); } } diff --git a/lib/presentation/common/svg_objects.dart b/lib/presentation/common/svg_objects.dart new file mode 100644 index 0000000..96e391a --- /dev/null +++ b/lib/presentation/common/svg_objects.dart @@ -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 = [ + 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); + } +} diff --git a/lib/presentation/home_page/card.dart b/lib/presentation/home_page/card.dart index 9d04111..02a1768 100644 --- a/lib/presentation/home_page/card.dart +++ b/lib/presentation/home_page/card.dart @@ -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(0), // ключи для перерисовки + color: Colors.purpleAccent, + key: ValueKey(0), ) : const Icon( - Icons.favorite_border, - key: ValueKey(1), // ключи для перерисовки - ), + Icons.favorite_border, + key: ValueKey(1), + ), ), ), ), diff --git a/lib/presentation/home_page/home_page.dart b/lib/presentation/home_page/home_page.dart index d624677..811fc94 100644 --- a/lib/presentation/home_page/home_page.dart +++ b/lib/presentation/home_page/home_page.dart @@ -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 { @override void initState() { + SvgObjects.init(); WidgetsBinding.instance.addPostFrameCallback((_) { // привязываем логику к кадру context.read().add(const HomeLoadDataEvent()); // добавляем данные после считывания + context.read().add(const LoadLikesEvent()); // загрузка лайков которые ставили в прошлый раз }); super.initState(); } @@ -84,18 +94,50 @@ class _BodyState extends State { } } + void _onLike(String? id, String title, bool isLiked) { + if (id != null) { + context.read().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().add(HomeLoadDataEvent(search: search))); - }, + child: Row( // наше поле для поиска + children: [ + Expanded( + child: CupertinoSearchTextField( // переписали под наши локали + controller: searchController, + placeholder: context.locale.search, + onChanged: (search) { + Debounce.run(() => context + .read() + .add(HomeLoadDataEvent(search: search))); + }, + ), + ), + GestureDetector( // иконки для смены локали + onTap: () => + context.read().add(const ChangeLocaleEvent()), //меняет в зависимости от текущей локализации + child: SizedBox.square( + dimension: 50, + child: Padding( + padding: const EdgeInsets.only(left: 12), + child: BlocBuilder( + builder: (context, state) { + return state.currentLocale.languageCode == 'ru' + ? const SvgRu() + : const SvgUk(); // иконки из ассетов + }, + ), + ), + ), + ), + ], ), ), BlocBuilder( @@ -107,23 +149,25 @@ class _BodyState extends State { ) : 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( // проверяем в зависимости от стейта, лайкнута ли карточка + 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 { 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, diff --git a/lib/presentation/like_bloc/like_bloc.dart b/lib/presentation/like_bloc/like_bloc.dart new file mode 100644 index 0000000..5fefc3d --- /dev/null +++ b/lib/presentation/like_bloc/like_bloc.dart @@ -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{ + LikeBloc() : super(const LikeState(likedIds: [])){ + on(_onChangeLike); + on(_onLoadLikes); + } + + Future _onLoadLikes(LoadLikesEvent event, Emitter emit) async{ + final prefs = await SharedPreferences.getInstance(); + final data = prefs.getStringList(_likedPrefsKey); + + emit(state.copyWith(likedIds: data)); + } + + Future _onChangeLike(ChangeLikeEvent event, Emitter emit) async{ + final updatedList = List.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)); + } +} \ No newline at end of file diff --git a/lib/presentation/like_bloc/like_event.dart b/lib/presentation/like_bloc/like_event.dart new file mode 100644 index 0000000..11ea044 --- /dev/null +++ b/lib/presentation/like_bloc/like_event.dart @@ -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); +} \ No newline at end of file diff --git a/lib/presentation/like_bloc/like_state.dart b/lib/presentation/like_bloc/like_state.dart new file mode 100644 index 0000000..35f2475 --- /dev/null +++ b/lib/presentation/like_bloc/like_state.dart @@ -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? likedIds; + + const LikeState({required this.likedIds}); + + @override + List get props => [likedIds]; +} \ No newline at end of file diff --git a/lib/presentation/like_bloc/like_state.g.dart b/lib/presentation/like_bloc/like_state.g.dart new file mode 100644 index 0000000..0888cf2 --- /dev/null +++ b/lib/presentation/like_bloc/like_state.g.dart @@ -0,0 +1,56 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'like_state.dart'; + +// ************************************************************************** +// CopyWithGenerator +// ************************************************************************** + +abstract class _$LikeStateCWProxy { + LikeState likedIds(List? 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? 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? 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?, + ); + } +} + +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); +} diff --git a/lib/presentation/locale_bloc/locale_bloc.dart b/lib/presentation/locale_bloc/locale_bloc.dart new file mode 100644 index 0000000..10dee1b --- /dev/null +++ b/lib/presentation/locale_bloc/locale_bloc.dart @@ -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{ + LocaleBloc(Locale defaultLocale) : super(LocaleState(currentLocale: defaultLocale)){ + on(_onChangeLocale); + } + + Future _onChangeLocale(ChangeLocaleEvent event, Emitter emit) async { + final toChange = AppLocale.supportedLocales.firstWhere((e) => e.languageCode != state.currentLocale.languageCode); + emit(state.copyWith(currentLocale: toChange)); + } +} \ No newline at end of file diff --git a/lib/presentation/locale_bloc/locale_events.dart b/lib/presentation/locale_bloc/locale_events.dart new file mode 100644 index 0000000..3d09e52 --- /dev/null +++ b/lib/presentation/locale_bloc/locale_events.dart @@ -0,0 +1,7 @@ +abstract class LocaleEvent{ + const LocaleEvent(); +} + +class ChangeLocaleEvent extends LocaleEvent{ + const ChangeLocaleEvent(); +} \ No newline at end of file diff --git a/lib/presentation/locale_bloc/locale_state.dart b/lib/presentation/locale_bloc/locale_state.dart new file mode 100644 index 0000000..8539fbf --- /dev/null +++ b/lib/presentation/locale_bloc/locale_state.dart @@ -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 get props => [currentLocale]; +} \ No newline at end of file diff --git a/lib/presentation/locale_bloc/locale_state.g.dart b/lib/presentation/locale_bloc/locale_state.g.dart new file mode 100644 index 0000000..e374db6 --- /dev/null +++ b/lib/presentation/locale_bloc/locale_state.g.dart @@ -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); +} diff --git a/makefile b/makefile index fde0a1b..d8ca212 100644 --- a/makefile +++ b/makefile @@ -8,4 +8,7 @@ format: dart format . --line-length 100 res: fgen --output lib/components/resources.g.dart --no-watch --no-preview; \ + mingw32-make format +loc: + flutter gen-l10n mingw32-make format \ No newline at end of file