Costyli vo blago (Six done)

This commit is contained in:
Serxiolog 2024-11-18 19:35:01 +04:00
parent 3b20f98ff3
commit d482c57819
15 changed files with 338 additions and 63 deletions

View File

@ -0,0 +1,17 @@
import 'dart:async';
import 'dart:ui';
class Debouce {
factory Debouce() => _instance;
Debouce._();
static final Debouce _instance = Debouce._();
static Timer? _timer;
static void run(VoidCallback action, {Duration delay = const Duration(milliseconds: 500),}) {
_timer?.cancel();
_timer = Timer(delay, action);
}
}

View File

@ -5,8 +5,9 @@ part 'anime_dto.g.dart';
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class AnimesDto { class AnimesDto {
final List<AnimeDataDto>? data; final List<AnimeDataDto>? data;
final PaginationDto? pagination;
const AnimesDto({this.data}); const AnimesDto({this.data, this.pagination});
factory AnimesDto.fromJson(Map<String, dynamic> json) => _$AnimesDtoFromJson(json); factory AnimesDto.fromJson(Map<String, dynamic> json) => _$AnimesDtoFromJson(json);
} }
@ -45,3 +46,17 @@ class AnimeImagesJpgDto {
const AnimeImagesJpgDto(this.image, this.smallImage, this.largeImage); const AnimeImagesJpgDto(this.image, this.smallImage, this.largeImage);
factory AnimeImagesJpgDto.fromJson(Map<String, dynamic> json) => _$AnimeImagesJpgDtoFromJson(json); factory AnimeImagesJpgDto.fromJson(Map<String, dynamic> json) => _$AnimeImagesJpgDtoFromJson(json);
} }
@JsonSerializable(createToJson: false)
class PaginationDto {
@JsonKey(name: "last_visible_page")
final int? last;
@JsonKey(name: "current_page")
final int? current;
@JsonKey(name: "has_next_page")
final bool? next;
const PaginationDto({this.current, this.last, this.next});
factory PaginationDto.fromJson(Map<String, dynamic> json) => _$PaginationDtoFromJson(json);
}

View File

@ -10,6 +10,9 @@ AnimesDto _$AnimesDtoFromJson(Map<String, dynamic> json) => AnimesDto(
data: (json['data'] as List<dynamic>?) data: (json['data'] as List<dynamic>?)
?.map((e) => AnimeDataDto.fromJson(e as Map<String, dynamic>)) ?.map((e) => AnimeDataDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
pagination: json['pagination'] == null
? null
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
); );
AnimeDataDto _$AnimeDataDtoFromJson(Map<String, dynamic> json) => AnimeDataDto( AnimeDataDto _$AnimeDataDtoFromJson(Map<String, dynamic> json) => AnimeDataDto(
@ -35,3 +38,10 @@ AnimeImagesJpgDto _$AnimeImagesJpgDtoFromJson(Map<String, dynamic> json) =>
json['small_image_url'] as String?, json['small_image_url'] as String?,
json['large_image_url'] as String?, json['large_image_url'] as String?,
); );
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) =>
PaginationDto(
current: (json['current_page'] as num?)?.toInt(),
last: (json['last_visible_page'] as num?)?.toInt(),
next: json['has_next_page'] as bool?,
);

View File

@ -1,4 +1,5 @@
import 'package:first_project/data/dtos/anime_dto.dart'; import 'package:first_project/data/dtos/anime_dto.dart';
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart'; import 'package:first_project/presentation/home_page/home_page.dart';
extension AnimeDataDtoToModel on AnimeDataDto { extension AnimeDataDtoToModel on AnimeDataDto {
@ -9,3 +10,10 @@ extension AnimeDataDtoToModel on AnimeDataDto {
description: synopsis == null ? "NONE" : synopsis!.split('\n').sublist(0, synopsis!.split('\n').length - 1).join('\n'), description: synopsis == null ? "NONE" : synopsis!.split('\n').sublist(0, synopsis!.split('\n').length - 1).join('\n'),
); );
} }
extension AnimesDataDtoToModel on AnimesDto {
HomeData toDomain() => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: pagination!.next! ? pagination!.current! + 1 : 0,
);
}

View File

@ -1,8 +1,8 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:first_project/data/dtos/anime_dto.dart'; import 'package:first_project/data/dtos/anime_dto.dart';
import 'package:first_project/data/mappers/anime_mapper.dart'; import 'package:first_project/data/mappers/anime_mapper.dart';
import 'package:first_project/data/repositories/api_interface.dart'; import 'package:first_project/data/repositories/api_interface.dart';
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart'; import 'package:first_project/presentation/home_page/home_page.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart';
@ -16,21 +16,22 @@ class AnimeRepository extends ApiInterface {
static const String _baseUrl = 'https://api.jikan.moe'; static const String _baseUrl = 'https://api.jikan.moe';
@override @override
Future<List<CardData>?> loadData({String? q}) async{ Future<HomeData?> loadData({OnErrorCallback? onError,String? q, int page = 1, int pageSize = 25}) async{
try try
{ {
const String url = '$_baseUrl/v4/anime'; const String url = '$_baseUrl/v4/anime';
Map<String, dynamic> query = {'limit' : 5, 'q' : q}; Map<String, dynamic> query = {'q' : q, 'page' : page, 'limit' : pageSize};
final Response<dynamic> response = final Response<dynamic> response =
await _dio.get<Map<dynamic, dynamic>>( await _dio.get<Map<dynamic, dynamic>>(
url, url,
queryParameters: query, queryParameters: query,
); );
final AnimesDto dto = AnimesDto.fromJson(response.data as Map<String, dynamic>); final AnimesDto dto = AnimesDto.fromJson(response.data as Map<String, dynamic>);
final List<CardData>? data = dto.data?.map((e) => e.toDomain()).toList(); final HomeData data = dto.toDomain();
return data; return data;
} on DioException catch (e) } on DioException catch (e)
{ {
onError?.call(e.error?.toString());
return null; return null;
} }
} }

View File

@ -1,6 +1,9 @@
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart'; import 'package:first_project/presentation/home_page/home_page.dart';
typedef OnErrorCallback = void Function(String? error);
abstract class ApiInterface { abstract class ApiInterface {
Future<List<CardData>?> loadData(); Future<HomeData?> loadData({OnErrorCallback? onError});
} }

View File

@ -1,11 +1,12 @@
import 'package:first_project/data/repositories/api_interface.dart'; import 'package:first_project/data/repositories/api_interface.dart';
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart'; import 'package:first_project/presentation/home_page/home_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class MockRepository extends ApiInterface { class MockRepository extends ApiInterface {
@override @override
Future<List<CardData>?> loadData() async { Future<HomeData?> loadData({OnErrorCallback? onError}) async {
return [ return HomeData(data:[
const CardData( const CardData(
"First", "First",
score: 5, score: 5,
@ -25,6 +26,6 @@ class MockRepository extends ApiInterface {
icon: Icons.offline_bolt_outlined, icon: Icons.offline_bolt_outlined,
description: "Wow >_<", description: "Wow >_<",
), ),
]; ]);
} }
} }

View File

@ -0,0 +1,8 @@
import 'package:first_project/presentation/home_page/home_page.dart';
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.nextPage});
}

View File

@ -1,5 +1,3 @@
import 'package:first_project/data/repositories/anime_repository.dart'; import 'package:first_project/data/repositories/anime_repository.dart';
import 'package:first_project/presentation/home_page/bloc/events.dart'; import 'package:first_project/presentation/home_page/bloc/events.dart';
import 'package:first_project/presentation/home_page/bloc/state.dart'; import 'package:first_project/presentation/home_page/bloc/state.dart';
@ -12,7 +10,30 @@ class HomeBloc extends Bloc<HomeEvent, HomeState> {
on<HomeLoadDataEvent>(_onLoadData); on<HomeLoadDataEvent>(_onLoadData);
} }
void _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) { Future<void> _onLoadData(
emit(state.copyWith(data: repo.loadData())); HomeLoadDataEvent event, Emitter<HomeState> emit) async {
if (event.nextPage == null) {
emit(state.copyWith(isLoading: true));
} else {
emit(state.copyWith(isPaginationLoading: true));
}
String? error;
final data = await repo.loadData(
q: event.search,
page: event.nextPage ?? 1,
onError: (e) => error = e,
);
if (event.nextPage != null) {
data?.data?.insertAll(0, state.data?.data ?? []);
}
emit(state.copyWith(
data: data,
isLoading: false,
isPaginationLoading: false,
error: error,
));
} }
} }

View File

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

View File

@ -1,15 +1,42 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:first_project/domain/models/card.dart'; import 'package:first_project/domain/models/card.dart';
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart'; import 'package:first_project/presentation/home_page/home_page.dart';
import 'package:copy_with_extension/copy_with_extension.dart';
part 'state.g.dart';
@CopyWith()
class HomeState extends Equatable { class HomeState extends Equatable {
final Future<List<CardData>?>? data; final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
final String? error;
const HomeState({this.data}); const HomeState({
this.data,
this.isLoading = false,
this.isPaginationLoading = false,
this.error,
});
HomeState copyWith({Future<List<CardData>?>? data}) => HomeState copyWith(
HomeState(data: data ?? this.data); {HomeData? data,
bool? isLoading,
bool? isPaginationLoading,
String? error}) =>
HomeState(
data: data ?? this.data,
isLoading: isLoading ?? this.isLoading,
isPaginationLoading: isPaginationLoading ?? this.isPaginationLoading,
error: error ?? this.error,
);
@override @override
List<Object?> get props => [data]; List<Object?> get props => [
data,
isLoading,
isPaginationLoading,
error,
];
} }

View File

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

View File

@ -1,8 +1,14 @@
import 'package:first_project/data/repositories/anime_repository.dart'; import 'package:first_project/data/repositories/anime_repository.dart';
import 'package:first_project/data/repositories/mock_repository.dart'; import 'package:first_project/data/repositories/mock_repository.dart';
import 'package:first_project/domain/models/card.dart'; import 'package:first_project/domain/models/card.dart';
import 'package:first_project/presentation/home_page/bloc/bloc.dart';
import 'package:first_project/presentation/home_page/bloc/events.dart';
import 'package:first_project/presentation/home_page/bloc/state.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:first_project/Components/utils/debounce.dart';
part 'card.dart'; part 'card.dart';
@ -38,64 +44,103 @@ class _MyHomePageState extends State<MyHomePage> {
backgroundColor: Colors.purple, backgroundColor: Colors.purple,
title: Text(widget.title), title: Text(widget.title),
), ),
body: const Body(), body: const _Body(),
); );
} }
} }
class Body extends StatefulWidget {
const Body({super.key}); class _Body extends StatefulWidget {
const _Body({super.key});
@override @override
State<Body> createState() => _BodyState(); State<_Body> createState() => _BodyState();
} }
class _BodyState extends State<Body> { class _BodyState extends State<_Body> {
final AnimeRepository repos = AnimeRepository();
final searchController = TextEditingController(); final searchController = TextEditingController();
late Future<List<CardData>?> data; final scrollController = ScrollController();
@override @override
void initState() { void initState() {
data = repos.loadData(); WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState(); super.initState();
} }
void _onNextPageListener() {
if (scrollController.offset > scrollController.position.maxScrollExtent - 50) {
final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent(
search: searchController.text,
nextPage: bloc.state.data?.nextPage,
));
}
}
}
@override
void dispose() {
searchController.dispose();
scrollController.dispose();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Center( return BlocBuilder<HomeBloc, HomeState>(
child: FutureBuilder<List<CardData>?>( builder: (context, state) => state.error != null
future: data, ? Text(
builder: (context, snapshot) => SingleChildScrollView( state.error ?? '',
child: snapshot.hasData style: Theme.of(context)
? Column( .textTheme
mainAxisAlignment: MainAxisAlignment.center, .headlineSmall
children: [ ?.copyWith(color: Colors.red),
)
: state.isLoading
? const CircularProgressIndicator()
: Column(children: [
Padding( Padding(
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
child: CupertinoSearchTextField( child: CupertinoSearchTextField(
controller: searchController, controller: searchController,
onChanged: (search) { onChanged: (search) {
setState(() { Debouce.run(() => context
data = repos.loadData(q : search); .read<HomeBloc>()
}); .add(HomeLoadDataEvent(search: search)));
}, },
), ),
), ),
...snapshot.data!.map( Expanded(
(e) { child: RefreshIndicator(
return _Card.fromData( onRefresh: _onRefresh,
e, child: ListView.builder(
onLike: (String title, bool isLiked) => 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,
onLike: (title, isLiked) =>
_showLiked(context, title, isLiked), _showLiked(context, title, isLiked),
onTap: () => _navToDetails(context, e), onTap: () => _navToDetails(context, data),
);
},
).toList()
],
) )
: const CircularProgressIndicator(), : const SizedBox.shrink();
}),
), ),
)); ),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),
)
]));
} }
void _navToDetails(BuildContext context, CardData data) { void _navToDetails(BuildContext context, CardData data) {
@ -117,4 +162,11 @@ class _BodyState extends State<Body> {
)); ));
}); });
} }
Future<void> _onRefresh() {
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
} }

View File

@ -166,6 +166,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.1.2" version: "3.1.2"
copy_with_extension:
dependency: transitive
description:
name: copy_with_extension
sha256: fbcf890b0c34aedf0894f91a11a579994b61b4e04080204656b582708b5b1125
url: "https://pub.dev"
source: hosted
version: "5.0.4"
copy_with_extension_gen:
dependency: "direct main"
description:
name: copy_with_extension_gen
sha256: "51cd11094096d40824c8da629ca7f16f3b7cea5fc44132b679617483d43346b0"
url: "https://pub.dev"
source: hosted
version: "5.0.4"
crypto: crypto:
dependency: transitive dependency: transitive
description: description:

View File

@ -42,6 +42,7 @@ dependencies:
#BLoC #BLoC
equatable: ^2.0.5 equatable: ^2.0.5
flutter_bloc: ^8.1.5 flutter_bloc: ^8.1.5
copy_with_extension_gen: ^5.0.4
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter