implement BLoC, Debounce, add refresh, pagination, error alerts, button "to top"

This commit is contained in:
shirotame 2024-10-06 00:37:40 +04:00
parent 72affbaf25
commit cf6fce5ec5
18 changed files with 507 additions and 78 deletions

2
Makefile Normal file
View File

@ -0,0 +1,2 @@
gen:
flutter pub run build_runner build --delete-conflicting-outputs

View File

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

View File

@ -0,0 +1 @@
typedef OnErrorCallback = void Function(String? error)?;

View File

@ -5,13 +5,28 @@ part "animes_dto.g.dart";
@JsonSerializable(createToJson: false)
class AnimesDto {
final List<AnimeDto>? data;
const AnimesDto({this.data});
final PaginationDto? pagination;
const AnimesDto({this.data, this.pagination});
factory AnimesDto.fromJson(Map<String, dynamic> json) =>
_$AnimesDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PaginationDto {
@JsonKey(name: 'last_visible_page')
final int? lastPage;
@JsonKey(name: 'has_next_page')
final bool? hasNextPage;
@JsonKey(name: 'current_page')
final int? currentPage;
const PaginationDto({this.currentPage, this.hasNextPage, this.lastPage});
factory PaginationDto.fromJson(Map<String, dynamic> json) =>
_$PaginationDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class AnimeDto {
final String? title;

View File

@ -10,6 +10,16 @@ AnimesDto _$AnimesDtoFromJson(Map<String, dynamic> json) => AnimesDto(
data: (json['data'] as List<dynamic>?)
?.map((e) => AnimeDto.fromJson(e as Map<String, dynamic>))
.toList(),
pagination: json['pagination'] == null
? null
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
);
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) =>
PaginationDto(
currentPage: (json['current_page'] as num?)?.toInt(),
hasNextPage: json['has_next_page'] as bool?,
lastPage: (json['last_visible_page'] as num?)?.toInt(),
);
AnimeDto _$AnimeDtoFromJson(Map<String, dynamic> json) => AnimeDto(

View File

@ -1,13 +1,22 @@
import 'package:flutter_project/domain/models/card.dart';
import 'package:flutter_project/domain/models/home.dart';
import '../dtos/animes_dto.dart';
extension AnimesMapper on AnimesDto {
HomeData toDomain() => HomeData(
data: data?.map((dto) => dto.toDomain()).toList(),
nextPage: (pagination?.hasNextPage ?? false)
? ((pagination?.currentPage ?? 0) + 1)
: null);
}
extension AnimeMapper on AnimeDto {
CardData toDomain() => CardData(
name: title ?? "",
imageUrl: images?.jpg?.imageUrl ?? "placeholder.co/250",
descr:
"Rating: ${rating ?? "unknown"}, Year: ${year ?? "unknown"}, type: ${type ?? "unknown"}.\n\n${synopsis ?? "No description provided"} ",
"Rating: ${rating ?? "unknown"}\nYear: ${year ?? "unknown"}\nType: ${type ?? "unknown"}.\n\n${synopsis ?? "No description provided"} ",
cuttedDescr:
"Rating: ${rating ?? "unknown"}, Year: ${year ?? "unknown"}, type: ${type ?? "unknown"}");
"Rating: ${rating ?? "unknown"}\nYear: ${year ?? "unknown"}\nType: ${type ?? "unknown"}");
}

View File

@ -1,10 +1,11 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter_project/components/utils/error_callback.dart';
import 'package:flutter_project/data/mappers/animes_mapper.dart';
import 'package:flutter_project/data/repositories/api_interface.dart';
import '../../domain/models/card.dart';
import '../../domain/models/home.dart';
import '../dtos/animes_dto.dart';
class AnimeRepository extends ApiInterface {
@ -13,22 +14,32 @@ class AnimeRepository extends ApiInterface {
static const String _baseUrl = "https://api.jikan.moe";
@override
Future<List<CardData>?> loadData({String? q}) async {
Future<HomeData?> loadData(
{OnErrorCallback onError,
String? q,
int page = 1,
int pageSize = 25}) async {
try {
const String url = "$_baseUrl/v4/anime?sfw";
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
url,
queryParameters: q != null ? {'q': q} : null);
final Response<dynamic> response = await _dio
.get<Map<dynamic, dynamic>>(url, queryParameters: {
'q': q,
'page': page,
'limit': !(pageSize > 25) ? pageSize : 25
});
final AnimesDto dto =
AnimesDto.fromJson(response.data as Map<String, dynamic>);
List<CardData> data = dto.data?.map((d) => d.toDomain()).toList() ?? [];
final HomeData data = dto.toDomain();
return data;
} on DioException catch (e) {
log("Exception. ${e.message.toString()}", error: e);
Response<dynamic>? errorResp = e.response;
onError?.call(e.error?.toString());
log("Exception. ${errorResp?.data['message']}", error: e);
return null;
}
}

View File

@ -1,5 +1,7 @@
import 'package:flutter_project/domain/models/card.dart';
import 'package:flutter_project/domain/models/home.dart';
import '../../components/utils/error_callback.dart';
abstract class ApiInterface {
Future<List<CardData>?> loadData();
Future<HomeData?> loadData({OnErrorCallback onError});
}

View File

@ -1,29 +1,33 @@
import 'package:flutter_project/components/utils/error_callback.dart';
import 'package:flutter_project/data/repositories/api_interface.dart';
import '../../domain/models/card.dart';
import '../../domain/models/home.dart';
class MockRepository extends ApiInterface {
@override
Future<List<CardData>?> loadData() async {
return [
CardData(
name: "Test",
imageUrl: "https://loremflickr.com/250/150/cat",
descr: "Description",
cuttedDescr: "cutted",
),
CardData(
name: "Test 2",
imageUrl: "https://loremflickr.com/200/250/cat",
descr: "Description",
cuttedDescr: "cutted",
),
CardData(
name: "Test 3",
imageUrl: "https://loremflickr.com/200/200/cat",
descr: "Description",
cuttedDescr: "cutted",
),
];
Future<HomeData?> loadData({OnErrorCallback onError}) async {
return HomeData(
data: [
CardData(
name: "Test",
imageUrl: "https://loremflickr.com/250/150/cat",
descr: "Description",
cuttedDescr: "cutted",
),
CardData(
name: "Test 2",
imageUrl: "https://loremflickr.com/200/250/cat",
descr: "Description",
cuttedDescr: "cutted",
),
CardData(
name: "Test 3",
imageUrl: "https://loremflickr.com/200/200/cat",
descr: "Description",
cuttedDescr: "cutted",
),
],
);
}
}

View File

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

View File

@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_project/data/repositories/anime_repository.dart';
import 'package:flutter_project/views/home_page/bloc/bloc.dart';
import 'package:flutter_project/views/home_page/home_page.dart';
void main() {
@ -10,13 +13,21 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.lightGreen),
useMaterial3: true,
return RepositoryProvider<AnimeRepository>(
lazy: true,
create: (_) => AnimeRepository(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<AnimeRepository>()),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.lightGreen),
useMaterial3: true,
),
home: const HomePage(),
),
),
home: const HomePage(),
);
}
}

View File

@ -0,0 +1,40 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_project/data/repositories/anime_repository.dart';
import 'package:flutter_project/views/home_page/bloc/events.dart';
import 'package:flutter_project/views/home_page/bloc/state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final AnimeRepository repo;
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
Future<void> _onLoadData(
HomeLoadDataEvent event, Emitter<HomeState> emit) async {
if (event.hasError != null && event.hasError == true) {
emit(state.copyWith(error: null));
}
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

@ -0,0 +1,11 @@
abstract class HomeEvent {
const HomeEvent();
}
class HomeLoadDataEvent extends HomeEvent {
final String? search;
final int? nextPage;
final bool? hasError;
const HomeLoadDataEvent({this.search, this.nextPage, this.hasError});
}

View File

@ -0,0 +1,22 @@
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_project/domain/models/home.dart';
part "state.g.dart";
@CopyWith()
class HomeState extends Equatable {
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
final String? error;
const HomeState(
{this.data,
this.isLoading = false,
this.isPaginationLoading = false,
this.error});
@override
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,13 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_project/data/repositories/anime_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_project/components/utils/debounce.dart';
import 'package:flutter_project/domain/models/card.dart';
import 'package:flutter_project/views/details_page/details_page.dart';
import 'package:flutter_project/views/home_page/bloc/events.dart';
import 'package:flutter_project/views/home_page/bloc/state.dart';
import 'bloc/bloc.dart';
part 'card.dart';
@ -14,16 +19,22 @@ class HomePage extends StatefulWidget {
}
class _HomePageState extends State<HomePage> {
final body = Body();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
flexibleSpace: GestureDetector(
onTap: () => print("to top"),
),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(
'Item list',
title: Center(
child: Text(
'Anime list',
),
),
),
body: Body());
body: body);
}
}
@ -35,49 +46,151 @@ class Body extends StatefulWidget {
}
class _BodyState extends State<Body> {
final AnimeRepository repo = AnimeRepository();
var data = AnimeRepository().loadData();
final scrollController = ScrollController();
final searchController = TextEditingController();
bool isButtonToTopShown = false;
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback(
(_) => context.read<HomeBloc>().add(const HomeLoadDataEvent()));
scrollController.addListener(_viewListScrollListener);
super.initState();
}
@override
void dispose() {
scrollController.dispose();
searchController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
child: CupertinoSearchTextField(
onChanged: (search) {
setState(() {
data = repo.loadData(q: search);
});
},
),
),
Expanded(
child: Center(
child: FutureBuilder<List<CardData>?>(
future: data,
builder: (context, snapshot) => SingleChildScrollView(
child: snapshot.hasData
? Column(
children: snapshot.data
?.map((data) => _Card.withData(
data,
onLike: (String title, bool isLiked) =>
_showSnackBar(
context, isLiked, title),
onTap: () => _navToDetails(context, data),
))
.toList() ??
[])
: const CircularProgressIndicator(),
return Stack(children: [
Column(
children: [
Padding(
padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
child: Center(
child: CupertinoSearchTextField(
controller: searchController,
onChanged: (search) {
Debounce.run(() => context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: search)));
},
),
),
),
),
],
BlocConsumer<HomeBloc, HomeState>(
listener: (context, state) {
if (state.error != null) {
_onErrorShowDialog(context, state);
}
},
builder: (context, state) => state.isLoading
? const CircularProgressIndicator()
: Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
child: ListView.builder(
controller: scrollController,
padding: EdgeInsets.only(bottom: 10),
itemCount: state.data?.data?.length ?? 0,
itemBuilder: (context, index) {
final data = state.data?.data?[index];
return data != null
? _Card.withData(data,
onLike: (title, isLiked) =>
_showSnackBar(context, isLiked, title),
onTap: () => _navToDetails(context, data))
: const SizedBox.shrink();
},
),
)),
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink())
],
),
isButtonToTopShown
? Container(
alignment: Alignment.topRight,
padding: EdgeInsets.only(right: 16, top: 64),
child: FloatingActionButton(
onPressed: _goToTop,
child: Icon(Icons.arrow_upward_rounded),
))
: SizedBox.shrink()
]);
}
void _onErrorShowDialog(BuildContext context, HomeState state) {
showCupertinoDialog(
context: context,
builder: (_) => CupertinoAlertDialog(
title: Text("Error occurred"),
content: Text(state.error ?? 'No message provided'),
actions: <Widget>[
CupertinoDialogAction(
onPressed: () {
Navigator.of(context).pop();
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(hasError: true));
},
child: Text("Retry"))
],
));
}
void _goToTop() {
scrollController.animateTo(
0,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
void _viewListScrollListener() {
if (!isButtonToTopShown) {
if (scrollController.offset >= 400) {
setState(() {
isButtonToTopShown = true;
});
}
} else {
if (scrollController.offset < 400) {
setState(() {
isButtonToTopShown = false;
});
}
}
if (scrollController.offset >= scrollController.position.maxScrollExtent) {
final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading &&
bloc.state.data?.nextPage != null) {
bloc.add(HomeLoadDataEvent(
search: searchController.text,
nextPage: bloc.state.data?.nextPage));
}
}
}
Future<void> _onRefresh() {
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
void _showSnackBar(BuildContext context, bool isLiked, String title) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(

View File

@ -38,6 +38,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.11.0"
bloc:
dependency: transitive
description:
name: bloc
sha256: "106842ad6569f0b60297619e9e0b1885c2fb9bf84812935490e6c5275777804e"
url: "https://pub.dev"
source: hosted
version: "8.1.4"
boolean_selector:
dependency: transitive
description:
@ -158,6 +166,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
copy_with_extension:
dependency: "direct dev"
description:
name: copy_with_extension
sha256: fbcf890b0c34aedf0894f91a11a579994b61b4e04080204656b582708b5b1125
url: "https://pub.dev"
source: hosted
version: "5.0.4"
copy_with_extension_gen:
dependency: "direct dev"
description:
name: copy_with_extension_gen
sha256: "51cd11094096d40824c8da629ca7f16f3b7cea5fc44132b679617483d43346b0"
url: "https://pub.dev"
source: hosted
version: "5.0.4"
crypto:
dependency: transitive
description:
@ -198,6 +222,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
equatable:
dependency: "direct main"
description:
name: equatable
sha256: c2b87cb7756efdf69892005af546c56c0b5037f54d2a88269b4f347a505e3ca2
url: "https://pub.dev"
source: hosted
version: "2.0.5"
fake_async:
dependency: transitive
description:
@ -227,6 +259,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_bloc:
dependency: "direct main"
description:
name: flutter_bloc
sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a
url: "https://pub.dev"
source: hosted
version: "8.1.6"
flutter_lints:
dependency: "direct dev"
description:
@ -392,6 +432,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
package_config:
dependency: transitive
description:
@ -424,6 +472,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
provider:
dependency: transitive
description:
name: provider
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
url: "https://pub.dev"
source: hosted
version: "6.1.2"
pub_semver:
dependency: transitive
description:

View File

@ -38,6 +38,8 @@ dependencies:
json_annotation: ^4.9.0
dio: ^5.7.0
pretty_dio_logger: ^1.4.0
flutter_bloc: ^8.1.6
equatable: ^2.0.5
dev_dependencies:
flutter_test:
@ -50,6 +52,8 @@ dev_dependencies:
# rules and activating additional ones.
flutter_lints: ^5.0.0
copy_with_extension_gen: ^5.0.4
copy_with_extension: ^5.0.4
json_serializable: ^6.7.1
build_runner: ^2.4.9