Всё проще чем я думал.

ЛАБА 7 СДАНА!!!!!!!!!
This commit is contained in:
Stepan 2024-12-12 16:20:42 +04:00
parent a5e7f52516
commit 17d74c828b
27 changed files with 627 additions and 72 deletions

6
l10n.yaml Normal file
View 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
View File

@ -0,0 +1,9 @@
{
"@@locale": "en",
"search": "Search",
"liked": "liked!",
"disliked": "disliked",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
}

9
l10n/app_ru.arb Normal file
View File

@ -0,0 +1,9 @@
{
"@@locale": "ru",
"search": "Поиск",
"liked": "понравился!",
"disliked": "разонравился",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
}

View 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)!; //делает удобное обращение к локале
}

View 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, youll need to edit this
/// file.
///
/// First, open your projects ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// projects 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.'
);
}

View 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 => 'Чтобы не забыть про отсутствие запятой :)';
}

View 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 => 'Чтобы не забыть про отсутствие запятой :)';
}

View 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';
}

View File

@ -12,12 +12,13 @@ class CharactersDto {
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class CharacterDto { class CharacterDto {
final String? uuid;
final String? displayName; final String? displayName;
final String? displayIcon; final String? displayIcon;
final String? description; final String? description;
final String? developerName; 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); factory CharacterDto.fromJson(Map<String, dynamic> json) => _$CharacterDtoFromJson(json);
} }

View File

@ -6,14 +6,14 @@ part of 'characters_dto.dart';
// JsonSerializableGenerator // JsonSerializableGenerator
// ************************************************************************** // **************************************************************************
CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) => CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) => CharactersDto(
CharactersDto(
data: (json['data'] as List<dynamic>?) data: (json['data'] as List<dynamic>?)
?.map((e) => CharacterDto.fromJson(e as Map<String, dynamic>)) ?.map((e) => CharacterDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
); );
CharacterDto _$CharacterDtoFromJson(Map<String, dynamic> json) => CharacterDto( CharacterDto _$CharacterDtoFromJson(Map<String, dynamic> json) => CharacterDto(
uuid: json['uuid'] as String?,
displayName: json['displayName'] as String?, displayName: json['displayName'] as String?,
displayIcon: json['displayIcon'] as String?, displayIcon: json['displayIcon'] as String?,
description: json['description'] as String?, description: json['description'] as String?,

View File

@ -4,6 +4,7 @@ import '../dtos/characters_dto.dart';
extension CharacterDtoToModel on CharacterDto { extension CharacterDtoToModel on CharacterDto {
CardData toDomain() => CardData( CardData toDomain() => CardData(
displayName ?? 'UNKNOWN', displayName ?? 'UNKNOWN',
uuid: uuid ?? 'UNKNOWN',
descriptionText: developerName ?? 'Описание отсутствует', descriptionText: developerName ?? 'Описание отсутствует',
gameDesc: description, gameDesc: description,
imageUrl: displayIcon, imageUrl: displayIcon,

View File

@ -13,7 +13,7 @@ class AgentsRepository extends ApiInterface {
requestBody: true, requestBody: true,
)); ));
static const String _baseUrl = 'https://valorant-api.com/v1/ agents'; static const String _baseUrl = 'https://valorant-api.com/v1/agents';
@override @override
Future<List<CardData>?> loadData({ Future<List<CardData>?> loadData({

View File

@ -6,6 +6,7 @@ class MockRepository extends ApiInterface {
Future<List<CardData>?> loadData() async { Future<List<CardData>?> loadData() async {
return [ return [
CardData('Far Cry 1', CardData('Far Cry 1',
uuid: '1',
descriptionText: 'Так себе', descriptionText: 'Так себе',
imageUrl: imageUrl:
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg', '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', CardData('Far Cry 2',
descriptionText: 'Лучше', descriptionText: 'Лучше',
uuid: '2',
imageUrl: imageUrl:
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg', 'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg',
gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' + gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' +
@ -25,6 +27,7 @@ class MockRepository extends ApiInterface {
'ужасам Галактики в эпических боях сразу на нескольких планетах. Раскройте мрачные секреты и отбросьте тень вечной ночи.'), 'ужасам Галактики в эпических боях сразу на нескольких планетах. Раскройте мрачные секреты и отбросьте тень вечной ночи.'),
CardData('Far Cry 3', CardData('Far Cry 3',
descriptionText: 'Красавцы', descriptionText: 'Красавцы',
uuid: '3',
imageUrl: imageUrl:
'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg', 'https://images.stopgame.ru/games/logos/8351/c1536x856/VdQJNv5ECykaiteg212k5g/far_cry_2-square_1.jpg',
gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' + gameDesc: 'Обретите сверхчеловеческую мощь космодесантника. Пустите в ход смертоносные навыки и разрушительное оружие, чтобы ' +

View File

@ -6,12 +6,13 @@ class CardData {
//final IconData icon; //final IconData icon;
final String? imageUrl; final String? imageUrl;
final String? gameDesc; final String? gameDesc;
late final String uuid;
CardData( CardData(
this.text, { this.text, {
required this.descriptionText, required this.descriptionText,
//this.icon = Icons.ac_unit_outlined,
this.imageUrl, this.imageUrl,
required this.gameDesc, required this.gameDesc,
required this.uuid,
}); });
} }

View File

@ -1,6 +1,11 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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/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 'data/repositories/characters_repository.dart';
import 'presentation/home_page/home_page.dart'; import 'presentation/home_page/home_page.dart';
@ -13,25 +18,37 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return BlocProvider<LocaleBloc>(
title: 'Flutter Demo', lazy: false,
debugShowCheckedModeBanner: false, create: (context) => LocaleBloc(Locale(Platform.localeName)),
theme: ThemeData( child: BlocBuilder<LocaleBloc, LocaleState>( //Передаём текущую локаль
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange), builder: (context, state) {
useMaterial3: true, return MaterialApp(
), title: 'Flutter Demo',
home: RepositoryProvider<AgentsRepository>( locale: state.currentLocale,
//даём нашему репозиторию доступ localizationsDelegates: AppLocale.localizationsDelegates,
lazy: true, //ленивое создание объекта supportedLocales: AppLocale.supportedLocales,// подключаем список доступных локалей
create: (_) => AgentsRepository(), debugShowCheckedModeBanner: false,
child: BlocProvider<HomeBloc>( theme: ThemeData(
//даём доступ Bloc для нашей страницы colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurpleAccent),
lazy: false, useMaterial3: true,
create: (context) => HomeBloc(context.read< ),
AgentsRepository>()), //в конструктор нашего Блока передаём репозиторий с нашей апи, то есть у нас появляется доступ по дереву к апи home: RepositoryProvider<AgentsRepository>(
child: const MyHomePage(title: 'Агенты Valorant'), 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'),
),
),
),
);
}
), ),
),
); );
} }
} }

View 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);
}
}

View File

@ -1,14 +1,16 @@
part of 'home_page.dart'; 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 text;
final String descriptionText; final String descriptionText;
//final IconData icon; //final IconData icon;
final String? imageUrl; final String? imageUrl;
final OnLikeCallback? onLike; final OnLikeCallback? onLike;
final VoidCallback? onTap; final VoidCallback? onTap;
final String uuid;
final bool isLiked;
const _Card( const _Card(
this.text, { this.text, {
@ -17,31 +19,30 @@ class _Card extends StatefulWidget {
this.imageUrl, this.imageUrl,
this.onLike, this.onLike,
this.onTap, this.onTap,
required this.uuid,
this.isLiked = false,
}); });
factory _Card.fromData( factory _Card.fromData(
CardData data, { CardData data, {
OnLikeCallback? onLike, OnLikeCallback? onLike,
VoidCallback? onTap, VoidCallback? onTap,
bool isLiked = false,
}) => }) =>
_Card( _Card(
uuid: data.uuid,
data.text!, data.text!,
descriptionText: data.descriptionText!, descriptionText: data.descriptionText!,
imageUrl: data.imageUrl, imageUrl: data.imageUrl,
onLike: onLike, onLike: onLike,
onTap: onTap, onTap: onTap,
isLiked: isLiked,
); );
@override
State<_Card> createState() => _CardState();
}
class _CardState extends State<_Card> {
bool isLiked = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return GestureDetector(
onTap: widget.onTap, onTap: onTap,
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0), padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Container( child: Container(
@ -72,7 +73,7 @@ class _CardState extends State<_Card> {
children: [ children: [
Positioned.fill( Positioned.fill(
child: Image.network( child: Image.network(
widget.imageUrl ?? '', imageUrl ?? '',
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const Placeholder(), errorBuilder: (_, __, ___) => const Placeholder(),
), ),
@ -107,12 +108,18 @@ class _CardState extends State<_Card> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
widget.text, text,
style: Theme.of(context).textTheme.headlineLarge, style: Theme
.of(context)
.textTheme
.titleLarge,
), ),
Text( Text(
widget.descriptionText, descriptionText,
style: Theme.of(context).textTheme.bodyLarge, style: Theme
.of(context)
.textTheme
.bodyLarge,
), ),
], ],
), ),
@ -127,25 +134,20 @@ class _CardState extends State<_Card> {
bottom: 16, bottom: 16,
), ),
child: GestureDetector( child: GestureDetector(
onTap: () { onTap: () => onLike?.call(uuid, text, isLiked),
setState(() {
isLiked = !isLiked; // установка лайков
});
widget.onLike?.call(widget.text, isLiked);
},
child: AnimatedSwitcher( child: AnimatedSwitcher(
// Анимация для наших лайков // Анимация для наших лайков
duration: const Duration(milliseconds: 300), duration: const Duration(milliseconds: 300),
child: isLiked child: isLiked
? const Icon( ? const Icon(
Icons.favorite, Icons.favorite,
color: Colors.redAccent, color: Colors.purpleAccent,
key: ValueKey<int>(0), // ключи для перерисовки key: ValueKey<int>(0),
) )
: const Icon( : const Icon(
Icons.favorite_border, Icons.favorite_border,
key: ValueKey<int>(1), // ключи для перерисовки key: ValueKey<int>(1),
), ),
), ),
), ),
), ),

View File

@ -1,10 +1,18 @@
import 'package:flutter_bloc/flutter_bloc.dart'; 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/data/repositories/mock_repository.dart';
import 'package:flutter_test_app/main.dart'; import 'package:flutter_test_app/main.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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 '../../data/repositories/characters_repository.dart';
import '../../domain/models/card.dart'; import '../../domain/models/card.dart';
import '../common/svg_objects.dart';
import '../details_page/details_page.dart'; import '../details_page/details_page.dart';
import 'bloc/bloc.dart'; import 'bloc/bloc.dart';
import 'bloc/events.dart'; import 'bloc/events.dart';
@ -49,9 +57,11 @@ class _BodyState extends State<Body> {
@override @override
void initState() { void initState() {
SvgObjects.init();
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
// привязываем логику к кадру // привязываем логику к кадру
context.read<HomeBloc>().add(const HomeLoadDataEvent()); // добавляем данные после считывания context.read<HomeBloc>().add(const HomeLoadDataEvent()); // добавляем данные после считывания
context.read<LikeBloc>().add(const LoadLikesEvent()); // загрузка лайков которые ставили в прошлый раз
}); });
super.initState(); 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( return Column(
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField( child: Row( // наше поле для поиска
controller: searchController, children: [
onChanged: (search) { Expanded(
//вызов задержки пока пользователь не перестанет печатать в поисковой строке child: CupertinoSearchTextField( // переписали под наши локали
Debounce.run(() => context.read<HomeBloc>().add(HomeLoadDataEvent(search: search))); 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>( BlocBuilder<HomeBloc, HomeState>(
@ -107,23 +149,25 @@ class _BodyState extends State<Body> {
) )
: state.isLoading : state.isLoading
? const CircularProgressIndicator() ? const CircularProgressIndicator()
: Expanded( : BlocBuilder<LikeBloc, LikeState>( // проверяем в зависимости от стейта, лайкнута ли карточка
child: RefreshIndicator( builder: (context, likeState) => Expanded(
onRefresh: _onRefresh, child: RefreshIndicator(
child: ListView.builder( onRefresh: _onRefresh,
padding: EdgeInsets.zero, child: ListView.builder(
itemCount: state.data?.length ?? 0, padding: EdgeInsets.zero,
itemBuilder: (context, index) { itemCount: state.data?.length ?? 0,
final data = state.data?[index]; itemBuilder: (context, index) {
return data != null final data = state.data?[index];
? _Card.fromData( return data != null
data, ? _Card.fromData(
onLike: (String title, bool isLiked) => data,
_showSnackBar(context, title, isLiked), onLike: _onLike,
onTap: () => _navToDetails(context, data), isLiked: likeState.likedIds?.contains(data.uuid) == true,
) onTap: () => _navToDetails(context, data),
: const SizedBox.shrink(); )
}, : const SizedBox.shrink();
},
),
), ),
), ),
), ),
@ -143,7 +187,7 @@ class _BodyState extends State<Body> {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar( ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text( content: Text(
'News $title ${isLiked ? 'liked' : 'disliked '}', '$title ${isLiked ? context.locale.liked : context.locale.disliked}', // переписали под наши локали
style: Theme.of(context).textTheme.bodyLarge, style: Theme.of(context).textTheme.bodyLarge,
), ),
backgroundColor: Colors.deepPurpleAccent, backgroundColor: Colors.deepPurpleAccent,

View 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));
}
}

View 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);
}

View 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];
}

View 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);
}

View 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));
}
}

View File

@ -0,0 +1,7 @@
abstract class LocaleEvent{
const LocaleEvent();
}
class ChangeLocaleEvent extends LocaleEvent{
const ChangeLocaleEvent();
}

View 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];
}

View 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);
}

View File

@ -9,3 +9,6 @@ format:
res: res:
fgen --output lib/components/resources.g.dart --no-watch --no-preview; \ fgen --output lib/components/resources.g.dart --no-watch --no-preview; \
mingw32-make format mingw32-make format
loc:
flutter gen-l10n
mingw32-make format