This commit is contained in:
ValAn 2024-12-19 08:53:16 +04:00
parent 0375d06716
commit 9e76b66976
34 changed files with 1066 additions and 233 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

View File

@ -5,5 +5,10 @@
"liked": "liked",
"disliked": "disliked",
"start": "Now you",
"known": "know",
"unknown": "dont know",
"end": "word",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
}

View File

@ -5,5 +5,12 @@
"liked": "поставлен лайк",
"disliked": "убран лайк",
"start": "Теперь вы",
"known": "знаете",
"unknown": "не знаете",
"end": "слово",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)"
}

View File

@ -0,0 +1,6 @@
import 'package:flutter/widgets.dart';
import '../locale/l10n/app_locale.dart';
extension LocalContextX on BuildContext {
AppLocale get locale => AppLocale.of(this)!;
}

View File

@ -0,0 +1,177 @@
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 @start.
///
/// In ru, this message translates to:
/// **'Теперь вы'**
String get start;
/// No description provided for @known.
///
/// In ru, this message translates to:
/// **'знаете'**
String get known;
/// No description provided for @unknown.
///
/// In ru, this message translates to:
/// **'не знаете'**
String get unknown;
/// No description provided for @end.
///
/// In ru, this message translates to:
/// **'слово'**
String get end;
/// 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,32 @@
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 start => 'Now you';
@override
String get known => 'know';
@override
String get unknown => 'dont know';
@override
String get end => 'word';
@override
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
}

View File

@ -0,0 +1,32 @@
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 start => 'Теперь вы';
@override
String get known => 'знаете';
@override
String get unknown => 'не знаете';
@override
String get end => 'слово';
@override
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
}

View File

@ -0,0 +1,10 @@
/// Generate by [asset_generator](https://github.com/fluttercandies/flutter_asset_generator) library.
/// PLEASE DO NOT EDIT MANUALLY.
// ignore_for_file: constant_identifier_names
class R {
const R._();
static const String ASSETS_SVG_RU_SVG = 'assets/svg/ru.svg';
static const String ASSETS_SVG_UK_SVG = 'assets/svg/uk.svg';
}

View File

@ -1,4 +1,3 @@
import 'dart:ui';
import 'dart:async';
@ -13,7 +12,8 @@ class Debounce {
static Timer? _timer;
static void run(VoidCallback action, {
static void run(
VoidCallback action, {
Duration delay = const Duration(milliseconds: 500),
}) {
_timer?.cancel();

View File

@ -32,4 +32,4 @@ class SearchController with ChangeNotifier {
}
notifyListeners(); // Уведомляем слушателей об изменении данных
}
}
}

View File

@ -2,7 +2,7 @@ import 'package:json_annotation/json_annotation.dart';
part 'words_dto.g.dart';
@JsonSerializable(createToJson: false)
class WordsDto{
class WordsDto {
final List<WordDataDto>? data;
final MetaDto? meta;
@ -12,7 +12,7 @@ class WordsDto{
}
@JsonSerializable(createToJson: false)
class WordDataDto{
class WordDataDto {
final String? id;
final String? type;
final WordAttributesDataDto? attributes;
@ -23,14 +23,14 @@ class WordDataDto{
}
@JsonSerializable(createToJson: false)
class WordAttributesDataDto{
class WordAttributesDataDto {
final String? name;
final String? born;
final String? died;
final String? image;
factory WordAttributesDataDto.fromJson(Map<String, dynamic> json) => _$WordAttributesDataDtoFromJson(json);
factory WordAttributesDataDto.fromJson(Map<String, dynamic> json) =>
_$WordAttributesDataDtoFromJson(json);
WordAttributesDataDto(this.name, this.born, this.died, this.image);
}
@ -51,4 +51,3 @@ class PaginationDto {
const PaginationDto({this.current, this.next, this.last});
factory PaginationDto.fromJson(Map<String, dynamic> json) => _$PaginationDtoFromJson(json);
}

View File

@ -2,16 +2,21 @@ import 'package:card_app/data/dtos/words_dto.dart';
import 'package:card_app/domain/models/card.dart';
import 'package:card_app/domain/models/home.dart';
const _imagePlaceholder = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS69a8OWnRueQNykBpuyfbGxl3gt5ct46NOHg&s';
extension WordDataDtoToModel on WordDataDto{
const _imagePlaceholder =
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS69a8OWnRueQNykBpuyfbGxl3gt5ct46NOHg&s';
extension WordDataDtoToModel on WordDataDto {
CardData toDomain() => CardData(
word: attributes?.name ?? 'UNKNOWN',
image: attributes?.image ?? _imagePlaceholder,
translation: '${attributes?.born}',
);
word: attributes?.name ?? 'UNKNOWN',
image: attributes?.image ?? _imagePlaceholder,
translation: '${attributes?.born}',
id: id,
);
}
extension WordsDtoToModel on WordsDto{
extension WordsDtoToModel on WordsDto {
HomeData toDomain() => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: meta?.pagination?.next,);
}
data: data?.map((e) => e.toDomain()).toList(),
nextPage: meta?.pagination?.next,
);
}

View File

@ -1,14 +1,15 @@
class CardData {
final String word;
final String translation;
final String? image;
final int mark;
final String? id;
const CardData({
required this.word,
required this.translation,
required this.image,
this.mark = 0,
this.id
});
}
}

View File

@ -1,10 +1,8 @@
import 'card.dart';
class HomeData{
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.nextPage});
}
}

View File

@ -1,5 +1,11 @@
import 'dart:io';
import 'package:card_app/components/locale/l10n/app_locale.dart';
import 'package:card_app/presentation/home_page/bloc/bloc.dart';
import 'package:card_app/presentation/home_page/home_page.dart';
import 'package:card_app/presentation/like_bloc/know_bloc.dart';
import 'package:card_app/presentation/locale_bloc/locale_bloc.dart';
import 'package:card_app/presentation/locale_bloc/locale_state.dart';
import 'package:card_app/repositories/WordsRepository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@ -13,23 +19,43 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
// Настраиваем цветовую схему приложения
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigoAccent),
useMaterial3: true,
),
home: RepositoryProvider<WordsRepository>(
lazy: true,
create: (_) => WordsRepository(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<WordsRepository>()),
child: MyHomePage(title: 'FlashCardsApp'),
),
return BlocProvider<LocaleBloc>(
lazy: false,
create: (context) => LocaleBloc(Locale(Platform.localeName)),
child: BlocBuilder<LocaleBloc, LocaleState>(
builder: (context, state) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
locale: state.currentLocale,
localizationsDelegates: AppLocale.localizationsDelegates,
supportedLocales: AppLocale.supportedLocales,
theme: ThemeData(
// Настраиваем цветовую схему приложения
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigoAccent),
useMaterial3: true,
),
home: RepositoryProvider<WordsRepository>(
lazy: true,
create: (_) => WordsRepository(),
child: BlocProvider<KnowBloc>(
lazy: false,
create: (context) => KnowBloc(),
child:
BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<WordsRepository>()),
child: MyHomePage(title: 'FlashCardsApp'),
),
),
),
);
}
),
);
}
}
}

View File

@ -0,0 +1,34 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../components/resources.g.dart';
abstract class SvgObjects {
static void init() {
final pics = <String>[
R.ASSETS_SVG_RU_SVG,
R.ASSETS_SVG_UK_SVG,
];
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.ASSETS_SVG_RU_SVG);
}
}
class SvgUk extends StatelessWidget {
const SvgUk({super.key});
@override
Widget build(BuildContext context) {
return SvgPicture.asset(R.ASSETS_SVG_UK_SVG);
}
}

View File

@ -16,23 +16,21 @@ class DetailPage extends StatelessWidget {
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(padding: const EdgeInsets.only(bottom: 16.0),
child: Image.network(data.image ?? ''),),
Padding(padding: const EdgeInsets.only(bottom: 4.0),
child: Text(data.word,
style: Theme
.of(context)
.textTheme
.headlineLarge,)),
Text(data.translation,
style: Theme
.of(context)
.textTheme
.bodyLarge,)
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Image.network(data.image ?? ''),
),
Padding(
padding: const EdgeInsets.only(bottom: 4.0),
child: Text(
data.word,
style: Theme.of(context).textTheme.headlineLarge,
)),
Text(
data.translation,
style: Theme.of(context).textTheme.bodyLarge,
)
],
)
);
));
}
}

View File

@ -1,44 +1,36 @@
import 'package:card_app/presentation/home_page/bloc/events.dart';
import 'package:card_app/presentation/home_page/bloc/state.dart';
import 'package:card_app/repositories/WordsRepository.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState>{
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final WordsRepository repo;
HomeBloc(this.repo) : super(const HomeState()){
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async{
if (event.nextPage == null){
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
if (event.nextPage == null) {
emit(state.copyWith(isLoading: true));
} else{
} else {
emit(state.copyWith(isPaginationLoading: true));
}
String? error;
final data = await repo.loadData(
q: event.search,
page: event.nextPage ?? 1,
onError: (e) => error = e);
final data =
await repo.loadData(q: event.search, page: event.nextPage ?? 1, onError: (e) => error = e);
if (event.nextPage != null){
if (event.nextPage != null) {
data?.data?.insertAll(0, state.data?.data ?? []);
}
emit(state.copyWith(
isLoading: false,
isPaginationLoading: false,
data: data,
isPaginationLoading: false,
data: data,
error: error,
));
}
}
}

View File

@ -1,5 +1,4 @@
abstract class HomeEvent{
abstract class HomeEvent {
const HomeEvent();
}
@ -7,4 +6,4 @@ class HomeLoadDataEvent extends HomeEvent {
final String? search;
final int? nextPage;
const HomeLoadDataEvent({this.search, this.nextPage});
}
}

View File

@ -1,4 +1,3 @@
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:card_app/domain/models/card.dart';
import 'package:card_app/domain/models/home.dart';
@ -8,18 +7,14 @@ part 'state.g.dart';
@CopyWith()
class HomeState extends Equatable {
final HomeData? data;
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
final String? error;
const HomeState({
this.data,
this.isLoading = false,
this.isPaginationLoading = false,
this.error});
const HomeState(
{this.data, this.isLoading = false, this.isPaginationLoading = false, this.error});
@override
List<Object?> get props => [data, isLoading, isPaginationLoading, error];
}
}

View File

@ -1,8 +1,9 @@
part of 'home_page.dart';
typedef OnKnowCallBack = void Function(String title, bool isKnow)?;
typedef OnKnowCallBack = void Function(String? id, String title, bool isKnow)?;
// Класс карточки
class _Card extends StatefulWidget {
class _Card extends StatelessWidget {
final String word;
final String translation;
final String image;
@ -10,6 +11,9 @@ class _Card extends StatefulWidget {
final OnKnowCallBack onKnow;
final VoidCallback? onTap;
final String? id;
final isKnown;
const _Card({
required this.word,
required this.translation,
@ -17,17 +21,89 @@ class _Card extends StatefulWidget {
this.mark = 0,
this.onKnow,
this.onTap,
this.id,
this.isKnown = false,
});
factory _Card.fromData(
CardData data, {
OnKnowCallBack? onKnow,
VoidCallback? onTap,
CardData data, {
OnKnowCallBack? onKnow,
VoidCallback? onTap,
bool isKnown = false,
}) =>
_Card(word: data.word, translation: data.translation, image: data.image ?? "", mark: data.mark, onKnow: onKnow, onTap: onTap,);
_Card(
word: data.word,
translation: data.translation,
image: data.image ?? "",
mark: data.mark,
onKnow: onKnow,
onTap: onTap,
id: data.id,
isKnown: isKnown,
);
@override
State<_Card> createState() => _CardState();
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
constraints: const BoxConstraints(minHeight: 140, maxWidth: 240),
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(10),
),
child: LayoutBuilder(builder: (context, constraints) {
double imageWidth = constraints.maxWidth;
{
return Stack(
children: [
Column(
children: [
Column(
children: [
Image.network(image, width: 300),
Text(
word,
style: Theme.of(context).textTheme.headlineLarge,
),
Text(
translation,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: GestureDetector(
onTap: () => onKnow?.call(id, word, isKnown),
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
child: isKnown
? const Icon(Icons.check_circle,
color: Colors.green, key: ValueKey(0))
: const Icon(Icons.check_circle_outline, key: ValueKey(1)),
),
),
),
),
],
),
Align(
alignment: Alignment.center,
)
],
);
}
})),
);
}
}

View File

@ -1,7 +1,12 @@
import 'package:card_app/components/extensions/context_x.dart';
import 'package:card_app/components/utils/debounce.dart';
import 'package:card_app/domain/models/card.dart';
import 'package:card_app/presentation/common/svg_objects.dart';
import 'package:card_app/presentation/home_page/bloc/bloc.dart';
import 'package:card_app/presentation/home_page/bloc/events.dart';
import 'package:card_app/presentation/like_bloc/know_bloc.dart';
import 'package:card_app/presentation/like_bloc/know_event.dart';
import 'package:card_app/presentation/locale_bloc/locale_events.dart';
import 'package:card_app/repositories/WordsRepository.dart';
import 'package:card_app/repositories/mock_repository.dart';
import 'package:flutter/cupertino.dart';
@ -9,6 +14,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../details_page/details_page.dart';
import '../like_bloc/know_state.dart';
import '../locale_bloc/locale_bloc.dart';
import '../locale_bloc/locale_state.dart';
import 'bloc/state.dart';
part 'card.dart';
@ -48,18 +56,21 @@ class _BodyState extends State<Body> {
@override
void initState() {
SvgObjects.init();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
context.read<KnowBloc>().add(const LoadKnowsEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState();
//data = WordsRepository().loadData(); // Инициализация данных
}
void _onNextPageListener(){
if (scrollController.offset > scrollController.position.maxScrollExtent - 300){
void _onNextPageListener() {
if (scrollController.offset > scrollController.position.maxScrollExtent - 300) {
final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading){
if (!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent(
search: searchController.text,
nextPage: bloc.state.data?.nextPage,
@ -80,51 +91,75 @@ class _BodyState extends State<Body> {
return Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: Column(children: [
Padding(
padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField(
onChanged: (search) {
Debounce.run(() =>
context.read<HomeBloc>().add(HomeLoadDataEvent(search: search)));
},
),
Row(
children: [
Expanded(
flex: 4,
child: Padding(
padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField(
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(right: 12),
child: BlocBuilder<LocaleBloc, LocaleState>(
builder: (context, state) {
return state.currentLocale.languageCode == 'ru'
? const SvgRu()
: const SvgUk();
},
),
),
),
),
],
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.error != null
? Text(state.error ?? '',
? Text(state.error ?? '',
style: Theme.of(context).textTheme.headlineLarge?.copyWith(color: Colors.red))
: state.isLoading
? const CircularProgressIndicator()
: Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
child: ListView.builder(
controller: scrollController,
padding: EdgeInsets.zero,
itemCount: state.data?.data?.length ?? 0,
itemBuilder: (context, index) {
final data = state.data?.data?[index];
return data != null
? _Card.fromData(
data,
onKnow: (title, isKnown) =>
_showSnackBar(context, title, isKnown),
onTap: () => _navToDetails(context, data),
)
: const SizedBox.shrink();
},
),
)
),
: state.isLoading
? const CircularProgressIndicator()
: BlocBuilder<KnowBloc, KnowState>(
builder: (context, knowState) {
return Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
child: ListView.builder(
controller: scrollController,
padding: EdgeInsets.zero,
itemCount: state.data?.data?.length ?? 0,
itemBuilder: (context, index) {
final data = state.data?.data?[index];
return data != null
? _Card.fromData(
data,
onKnow:_onKnow,
isKnown: knowState.knownIds?.contains(data.id) == true,
onTap: () => _navToDetails(context, data),
)
: const SizedBox.shrink();
},
),
));
}
),
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),)
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),
)
]));
}
@ -139,7 +174,7 @@ class _BodyState extends State<Body> {
WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
'Now you ${isKnow ? 'know' : 'don\'t know'} word $title',
'${context.locale.start} ${isKnow ? context.locale.known : context.locale.unknown} ${context.locale.end} $title',
style: Theme.of(context).textTheme.bodyLarge,
),
backgroundColor: Colors.indigoAccent,
@ -148,78 +183,81 @@ class _BodyState extends State<Body> {
});
}
Future<void> _onRefresh(){
Future<void> _onRefresh() {
context.read<HomeBloc>().add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
}
class _CardState extends State<_Card> {
bool isKnow = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Container(
constraints: const BoxConstraints(minHeight: 140, maxWidth: 240),
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(10),
),
child: LayoutBuilder(builder: (context, constraints) {
double imageWidth = constraints.maxWidth;
{
return Stack(
children: [
Column(
children: [
Column(
children: [
Image.network(widget.image, width: 300),
Text(
widget.word,
style: Theme.of(context).textTheme.headlineLarge,
),
Text(
widget.translation,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: GestureDetector(
onTap: () {
setState(() {
isKnow = !isKnow;
});
widget.onKnow?.call(widget.word, isKnow);
},
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
child: isKnow
? const Icon(Icons.check_circle,
color: Colors.green, key: ValueKey(0))
: const Icon(Icons.check_circle_outline,
key: ValueKey(1)),
),
),
),
),
],
),
Align(
alignment: Alignment.center,
)
],
);
}
})),
);
void _onKnow(String? id, String title, bool isKnown){
if (id != null){
context.read<KnowBloc>().add(ChangeKnowEvent(id));
_showSnackBar(context, title, !isKnown);
}
}
}
// class _CardState extends State<_Card> {
// bool isKnow = false;
//
// @override
// Widget build(BuildContext context) {
// return GestureDetector(
// onTap: widget.onTap,
// child: Container(
// constraints: const BoxConstraints(minHeight: 140, maxWidth: 240),
// padding: const EdgeInsets.all(20),
// margin: const EdgeInsets.all(10),
// decoration: BoxDecoration(
// color: Colors.black12,
// borderRadius: BorderRadius.circular(10),
// ),
// child: LayoutBuilder(builder: (context, constraints) {
// double imageWidth = constraints.maxWidth;
// {
// return Stack(
// children: [
// Column(
// children: [
// Column(
// children: [
// Image.network(widget.image, width: 300),
// Text(
// widget.word,
// style: Theme.of(context).textTheme.headlineLarge,
// ),
// Text(
// widget.translation,
// style: Theme.of(context).textTheme.bodyMedium,
// ),
// ],
// ),
// Align(
// alignment: Alignment.bottomRight,
// child: Padding(
// padding: const EdgeInsets.only(left: 8.0),
// child: GestureDetector(
// onTap: () => onKnow?.call(id, text, isKnown),
// child: AnimatedSwitcher(
// duration: const Duration(milliseconds: 200),
// child: isKnow
// ? const Icon(Icons.check_circle,
// color: Colors.green, key: ValueKey(0))
// : const Icon(Icons.check_circle_outline, key: ValueKey(1)),
// ),
// ),
// ),
// ),
// ],
// ),
// Align(
// alignment: Alignment.center,
// )
// ],
// );
// }
// })),
// );
// }
// }

View File

@ -0,0 +1,38 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'know_event.dart';
import 'know_state.dart';
const String _knownPrefsKey = 'known';
class KnowBloc extends Bloc<KnowEvent, KnowState> {
KnowBloc() : super(const KnowState(knownIds: [])) {
on<ChangeKnowEvent>(_onChangeKnow);
on<LoadKnowsEvent>(_onLoadKnows);
}
Future<void> _onLoadKnows(
LoadKnowsEvent event, Emitter<KnowState> emit) async {
final prefs = await SharedPreferences.getInstance();
final data = prefs.getStringList(_knownPrefsKey);
emit(state.copyWith(knownIds: data));
}
Future<void> _onChangeKnow(
ChangeKnowEvent event, Emitter<KnowState> emit) async {
final updatedList = List<String>.from(state.knownIds ?? []);
if (updatedList.contains(event.id)) {
updatedList.remove(event.id);
} else {
updatedList.add(event.id);
}
final prefs = await SharedPreferences.getInstance();
prefs.setStringList(_knownPrefsKey, updatedList);
emit(state.copyWith(knownIds: updatedList));
}
}

View File

@ -0,0 +1,13 @@
abstract class KnowEvent {
const KnowEvent();
}
class LoadKnowsEvent extends KnowEvent {
const LoadKnowsEvent();
}
class ChangeKnowEvent extends KnowEvent {
final String id;
const ChangeKnowEvent(this.id);
}

View File

@ -0,0 +1,14 @@
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:equatable/equatable.dart';
part 'know_state.g.dart';
@CopyWith()
class KnowState extends Equatable {
final List<String>? knownIds;
const KnowState({required this.knownIds});
@override
List<Object?> get props => [knownIds];
}

View File

@ -0,0 +1,56 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'know_state.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$KnowStateCWProxy {
KnowState knownIds(List<String>? knownIds);
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `KnowState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// KnowState(...).copyWith(id: 12, name: "My name")
/// ````
KnowState call({
List<String>? knownIds,
});
}
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfKnowState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfKnowState.copyWith.fieldName(...)`
class _$KnowStateCWProxyImpl implements _$KnowStateCWProxy {
const _$KnowStateCWProxyImpl(this._value);
final KnowState _value;
@override
KnowState knownIds(List<String>? knownIds) => this(knownIds: knownIds);
@override
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `KnowState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// KnowState(...).copyWith(id: 12, name: "My name")
/// ````
KnowState call({
Object? knownIds = const $CopyWithPlaceholder(),
}) {
return KnowState(
knownIds: knownIds == const $CopyWithPlaceholder()
? _value.knownIds
// ignore: cast_nullable_to_non_nullable
: knownIds as List<String>?,
);
}
}
extension $KnowStateCopyWith on KnowState {
/// Returns a callable class that can be used as follows: `instanceOfKnowState.copyWith(...)` or like so:`instanceOfKnowState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$KnowStateCWProxy get copyWith => _$KnowStateCWProxyImpl(this);
}

View File

@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../components/locale/l10n/app_locale.dart';
import 'locale_events.dart';
import 'locale_state.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

@ -1,4 +1,3 @@
import 'package:card_app/data/dtos/words_dto.dart';
import 'package:card_app/data/mappers/words_mapper.dart';
import 'package:card_app/repositories/api_interface.dart';
@ -8,43 +7,35 @@ import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../domain/models/card.dart';
import '../domain/models/home.dart';
class WordsRepository extends ApiInterface{
class WordsRepository extends ApiInterface {
static final Dio _dio = Dio()
..interceptors.add(PrettyDioLogger(
requestHeader: true,
requestBody: true,
));
..interceptors.add(PrettyDioLogger(
requestHeader: true,
requestBody: true,
));
static const String _baseUrl = 'https://api.potterdb.com';
@override
Future<HomeData?> loadData({
OnErrorCallback? onError,
String? q,
int page = 1,
int pageSize = 5,
}) async{
}) async {
try {
const String url = '$_baseUrl/v1/characters';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
url,
queryParameters: {
'filter[name_cont]': q,
'page[number]': page,
'page[size]': pageSize
},
queryParameters: {'filter[name_cont]': q, 'page[number]': page, 'page[size]': pageSize},
);
final WordsDto dto = WordsDto.fromJson(response.data as Map<String, dynamic>);
final HomeData data = dto.toDomain();
return data;
} on DioException catch (e) {
onError?.call(e.error?.toString());
return null;
return null;
}
}
}
}

View File

@ -3,7 +3,6 @@ import 'package:card_app/domain/models/home.dart';
typedef OnErrorCallback = void Function(String? error);
abstract class ApiInterface{
abstract class ApiInterface {
Future<HomeData?> loadData({OnErrorCallback? onError});
}
}

View File

@ -254,6 +254,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.1"
ffi:
dependency: transitive
description:
name: ffi
sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6"
url: "https://pub.dev"
source: hosted
version: "2.1.3"
file:
dependency: transitive
description:
@ -299,11 +307,29 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.0.0"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_svg:
dependency: "direct main"
description:
name: flutter_svg
sha256: "8c5d68a82add3ca76d792f058b186a0599414f279f00ece4830b9b231b570338"
url: "https://pub.dev"
source: hosted
version: "2.0.7"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
frontend_server_client:
dependency: transitive
description:
@ -328,6 +354,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.2"
http:
dependency: transitive
description:
name: http
sha256: b9c29a161230ee03d3ccf545097fccd9b87a5264228c5d348202e0f0c28f9010
url: "https://pub.dev"
source: hosted
version: "1.2.2"
http_multi_server:
dependency: transitive
description:
@ -352,6 +386,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.3.0"
intl:
dependency: "direct main"
description:
name: intl
sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf
url: "https://pub.dev"
source: hosted
version: "0.19.0"
io:
dependency: transitive
description:
@ -488,6 +530,38 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.0"
path_parsing:
dependency: transitive
description:
name: path_parsing
sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
url: "https://pub.dev"
source: hosted
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
url: "https://pub.dev"
source: hosted
version: "2.3.0"
petitparser:
dependency: transitive
description:
@ -496,6 +570,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.2"
platform:
dependency: transitive
description:
name: platform
sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
url: "https://pub.dev"
source: hosted
version: "3.1.6"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pool:
dependency: transitive
description:
@ -536,6 +626,62 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.0"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: d3bbe5553a986e83980916ded2f0b435ef2e1893dfaa29d5a7a790d0eca12180
url: "https://pub.dev"
source: hosted
version: "2.2.3"
shared_preferences_android:
dependency: transitive
description:
name: shared_preferences_android
sha256: "7f172d1b06de5da47b6264c2692ee2ead20bbbc246690427cdb4fc301cd0c549"
url: "https://pub.dev"
source: hosted
version: "2.3.4"
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "07e050c7cd39bad516f8d64c455f04508d09df104be326d8c02551590a0d513d"
url: "https://pub.dev"
source: hosted
version: "2.5.3"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
sha256: d2ca4132d3946fec2184261726b355836a82c33d7d5b67af32692aff18a4684e
url: "https://pub.dev"
source: hosted
version: "2.4.2"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shelf:
dependency: transitive
description:
@ -645,6 +791,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vector_graphics:
dependency: transitive
description:
name: vector_graphics
sha256: "27d5fefe86fb9aace4a9f8375b56b3c292b64d8c04510df230f849850d912cb7"
url: "https://pub.dev"
source: hosted
version: "1.1.15"
vector_graphics_codec:
dependency: transitive
description:
name: vector_graphics_codec
sha256: "2430b973a4ca3c4dbc9999b62b8c719a160100dcbae5c819bae0cacce32c9cdb"
url: "https://pub.dev"
source: hosted
version: "1.1.12"
vector_graphics_compiler:
dependency: transitive
description:
name: vector_graphics_compiler
sha256: "1b4b9e706a10294258727674a340ae0d6e64a7231980f9f9a3d12e4b42407aad"
url: "https://pub.dev"
source: hosted
version: "1.1.16"
vector_math:
dependency: transitive
description:
@ -693,6 +863,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.1"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
xml:
dependency: transitive
description:
@ -711,4 +889,4 @@ packages:
version: "3.1.2"
sdks:
dart: ">=3.5.2 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"
flutter: ">=3.24.0"

View File

@ -44,6 +44,14 @@ dependencies:
flutter_bloc: ^8.1.5
copy_with_extension_gen: ^5.0.4
flutter_svg: 2.0.7
flutter_localizations:
sdk: flutter
intl: 0.19.0
shared_preferences: 2.2.3