6 lab architecture, pagination, searchController

This commit is contained in:
sardq 2024-10-16 14:37:36 +04:00
parent d1b552ad5d
commit cd022a58d7
16 changed files with 300 additions and 101 deletions

View File

@ -0,0 +1,22 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
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,12 +5,26 @@ part 'mangas_dto.g.dart';
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class MangasDto { class MangasDto {
final List<MangaDataDto>? data; final List<MangaDataDto>? data;
final MangaPaginationDto? pagination;
const MangasDto({this.data}); const MangasDto({this.data, this.pagination});
factory MangasDto.fromJson(Map<String, dynamic> json) => factory MangasDto.fromJson(Map<String, dynamic> json) =>
_$MangasDtoFromJson(json); _$MangasDtoFromJson(json);
} }
@JsonSerializable(createToJson: false)
class MangaPaginationDto {
@JsonKey(name: 'current_page')
final int? currentPage;
@JsonKey(name: 'has_next_page')
final bool? hasNextPage;
@JsonKey(name: 'last_visible_page')
final int? lastVisiblePage;
const MangaPaginationDto({this.currentPage, this.hasNextPage, this.lastVisiblePage});
factory MangaPaginationDto.fromJson(Map<String, dynamic> json) =>
_$MangaPaginationDtoFromJson(json);
}
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class MangaDataDto { class MangaDataDto {

View File

@ -10,6 +10,17 @@ MangasDto _$MangasDtoFromJson(Map<String, dynamic> json) => MangasDto(
data: (json['data'] as List<dynamic>?) data: (json['data'] as List<dynamic>?)
?.map((e) => MangaDataDto.fromJson(e as Map<String, dynamic>)) ?.map((e) => MangaDataDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
pagination: json['pagination'] == null
? null
: MangaPaginationDto.fromJson(
json['pagination'] as Map<String, dynamic>),
);
MangaPaginationDto _$MangaPaginationDtoFromJson(Map<String, dynamic> json) =>
MangaPaginationDto(
currentPage: (json['current_page'] as num?)?.toInt(),
hasNextPage: json['has_next_page'] as bool?,
lastVisiblePage: (json['last_visible_page'] as num?)?.toInt(),
); );
MangaDataDto _$MangaDataDtoFromJson(Map<String, dynamic> json) => MangaDataDto( MangaDataDto _$MangaDataDtoFromJson(Map<String, dynamic> json) => MangaDataDto(

View File

@ -1,5 +1,6 @@
import 'package:flutter_app/data/dtos/mangas_dto.dart'; import 'package:flutter_app/data/dtos/mangas_dto.dart';
import 'package:flutter_app/domain/models/carddata.dart'; import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
extension MangaDataDtoMapper on MangaDataDto { extension MangaDataDtoMapper on MangaDataDto {
CardData toDomain() => CardData( CardData toDomain() => CardData(
@ -9,3 +10,10 @@ extension MangaDataDtoMapper on MangaDataDto {
'Статус: ${status}. Рейтинг: ${score}. Людей поставило оценку: ${scored_by}', 'Статус: ${status}. Рейтинг: ${score}. Людей поставило оценку: ${scored_by}',
); );
} }
extension MangasDtoToModel on MangasDto {
HomeData toDomain() => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: (pagination?.hasNextPage ?? false)
? ((pagination?.currentPage ?? 0) + 1)
: null);
}

View File

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

View File

@ -1,8 +1,9 @@
import 'package:flutter_app/components/utils/error_callback.dart';
import 'package:flutter_app/data/dtos/mangas_dto.dart'; import 'package:flutter_app/data/dtos/mangas_dto.dart';
import 'package:flutter_app/data/mappers/mangas_mapper.dart'; import 'package:flutter_app/data/mappers/mangas_mapper.dart';
import 'package:flutter_app/data/repositories/api_interface.dart'; import 'package:flutter_app/data/repositories/api_interface.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter_app/domain/models/carddata.dart'; import 'package:flutter_app/presentation/home_page/home_page.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class MangaRepository extends ApiInterface { class MangaRepository extends ApiInterface {
@ -14,18 +15,28 @@ class MangaRepository 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/manga'; const String url = '$_baseUrl/v4/manga';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>( final Response<dynamic> response = await _dio
url, .get<Map<dynamic, dynamic>>(url, queryParameters: {
queryParameters: q != null ? {'q': q} : null); 'q': q,
'page': page,
'limit': !(pageSize > 25) ? pageSize : 25
});
final MangasDto dto = final MangasDto dto =
MangasDto.fromJson(response.data as Map<String, dynamic>); MangasDto.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.response?.statusMessage);
return null; return null;
} }
} }

View File

@ -1,14 +1,18 @@
import 'package:flutter_app/components/utils/error_callback.dart';
import 'package:flutter_app/data/repositories/api_interface.dart'; import 'package:flutter_app/data/repositories/api_interface.dart';
import 'package:flutter_app/domain/models/carddata.dart'; import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/presentation/home_page/home_page.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: [
CardData('JoJos Bizarre Adventure', descriptionText: 'kono dio da', imageUrl: 'https://i1.sndcdn.com/avatars-253MmMf9QZzxVBJi-rvlyeg-t1080x1080.jpg'), CardData('JoJos Bizarre Adventure', descriptionText: 'kono dio da', imageUrl: 'https://i1.sndcdn.com/avatars-253MmMf9QZzxVBJi-rvlyeg-t1080x1080.jpg'),
CardData('Example', descriptionText: 'what is this?', imageUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvaBQ6nAedlqvXsh-dLXZi2Gexy1RkDbTUKQ&s'), CardData('Example', descriptionText: 'what is this?', imageUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvaBQ6nAedlqvXsh-dLXZi2Gexy1RkDbTUKQ&s'),
CardData('Mock data', descriptionText: 'Mock data description', imageUrl: 'https://cdn-user30887.skyeng.ru/uploads/6692a339c6989979804399.png'), CardData('Mock data', descriptionText: 'Mock data description', imageUrl: 'https://cdn-user30887.skyeng.ru/uploads/6692a339c6989979804399.png'),
]; ],
);
} }
} }

View File

@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_app/data/repositories/manga_repository.dart';
import 'package:flutter_app/presentation/home_page/bloc/bloc.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart'; import 'package:flutter_app/presentation/home_page/home_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() { void main() {
runApp(const MyApp()); runApp(const MyApp());
@ -14,25 +17,18 @@ class MyApp extends StatelessWidget {
return MaterialApp( return MaterialApp(
title: 'Flutter Demo', title: 'Flutter Demo',
theme: ThemeData( theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true, useMaterial3: true,
), ),
home: const MyHomePage(title: 'Разубаев Сергей Михайлович'), home: RepositoryProvider<MangaRepository>(
lazy: true,
create: (_) => MangaRepository(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<MangaRepository>()),
child: const HomePage(),
),
)
); );
} }
} }

View File

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

View File

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

View File

@ -0,0 +1,15 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
class HomeState extends Equatable {
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
const HomeState({this.data, this.isLoading = false, this.isPaginationLoading = false});
HomeState copyWith({HomeData? data, bool? isLoading, bool? isPaginationLoading}) => HomeState(
data: data ?? this.data, isLoading: isLoading ?? this.isLoading, isPaginationLoading: isPaginationLoading ?? this.isPaginationLoading);
@override
List<Object?> get props => [data, isLoading, isPaginationLoading];
}

View File

@ -1,48 +1,35 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_app/components/utils/debounce.dart';
import 'package:flutter_app/data/repositories/manga_repository.dart'; import 'package:flutter_app/data/repositories/manga_repository.dart';
import 'package:flutter_app/data/repositories/mock_repository.dart'; import 'package:flutter_app/data/repositories/mock_repository.dart';
import 'package:flutter_app/presentation/details_page/details_page.dart'; import 'package:flutter_app/presentation/details_page/details_page.dart';
import 'package:flutter_app/presentation/home_page/bloc/bloc.dart';
import 'package:flutter_app/presentation/home_page/bloc/events.dart';
import 'package:flutter_app/presentation/home_page/bloc/state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/models/carddata.dart'; import '../../domain/models/carddata.dart';
part 'card.dart'; part 'card.dart';
class HomePage extends StatefulWidget {
class MyHomePage extends StatefulWidget { const HomePage({super.key});
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override @override
State<MyHomePage> createState() => _MyHomePageState(); State<HomePage> createState() => _HomePageState();
} }
class _MyHomePageState extends State<MyHomePage> { class _HomePageState extends State<HomePage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: Theme backgroundColor: Theme.of(context).colorScheme.inversePrimary,
.of(context)
.colorScheme
.inversePrimary,
title: Text(widget.title),
), ),
body: const Body(), body: const Body(),
); );
} }
} }
class Body extends StatefulWidget { class Body extends StatefulWidget {
@ -53,6 +40,37 @@ class Body extends StatefulWidget {
} }
class _BodyState extends State<Body> { class _BodyState extends State<Body> {
final scrollController = ScrollController();
final searchController = TextEditingController();
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState();
}
void _onNextPageListener() {
if (scrollController.offset > scrollController.position.maxScrollExtent) {
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();
}
final MangaRepository repo = MangaRepository(); final MangaRepository repo = MangaRepository();
var data = MangaRepository().loadData(); var data = MangaRepository().loadData();
@ -61,10 +79,7 @@ class _BodyState extends State<Body> {
ScaffoldMessenger.of(context).showSnackBar(SnackBar( ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text( content: Text(
'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}', 'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}',
style: Theme style: Theme.of(context).textTheme.bodyLarge,
.of(context)
.textTheme
.bodyLarge,
), ),
backgroundColor: Colors.orangeAccent, backgroundColor: Colors.orangeAccent,
duration: const Duration(seconds: 1), duration: const Duration(seconds: 1),
@ -77,6 +92,12 @@ class _BodyState extends State<Body> {
context, CupertinoPageRoute(builder: (context) => DetailsPage(data))); context, CupertinoPageRoute(builder: (context) => DetailsPage(data)));
} }
Future<void> _onRefresh() {
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -87,34 +108,49 @@ Widget build(BuildContext context) {
Padding( Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField( child: CupertinoSearchTextField(
controller: searchController,
onChanged: (search) { onChanged: (search) {
setState(() { Debounce.run(() => context
data = repo.loadData(q:search); .read<HomeBloc>()
}); .add(HomeLoadDataEvent(search: search)));
}, })),
), BlocBuilder<HomeBloc, HomeState>(
), builder: (context, state) => state.isLoading
Expanded(child: Center( ? CircularProgressIndicator()
child: FutureBuilder<List<CardData>?>( : Expanded(
future: data, child: RefreshIndicator(
builder: (context, snapshot) => onRefresh: _onRefresh,
SingleChildScrollView( child: ListView.builder(
child: snapshot.hasData ? Column( controller: scrollController,
mainAxisAlignment: MainAxisAlignment.center, padding: EdgeInsets.zero,
children: snapshot.data!.map((data) { itemCount: state.data?.data?.length ?? 0,
return _Card.fromData(data, itemBuilder: (context, index) {
onLike: (String title, bool isLiked) => final data = state.data?.data?[index];
_showSnackbar(context, title, isLiked), return data != null
onTap: () => _navToDetails(context, data),); ? _Card.fromData(
}).toList() ?? [], data,
onLike: (title, isLiked) =>
_showSnackbar(
context, title, isLiked),
onTap: () =>
_navToDetails(context, data),
) )
: const CircularProgressIndicator(), : const SizedBox.shrink();
}),
), ),
), )),
), BlocBuilder<HomeBloc, HomeState>(
) builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink())
], ],
)); ));
}} }
}
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.nextPage});
}

View File

@ -38,6 +38,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.11.0" version: "2.11.0"
bloc:
dependency: transitive
description:
name: bloc
sha256: "106842ad6569f0b60297619e9e0b1885c2fb9bf84812935490e6c5275777804e"
url: "https://pub.dev"
source: hosted
version: "8.1.4"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:
@ -154,18 +162,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: convert name: convert
sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.1.1" version: "3.1.2"
crypto: crypto:
dependency: transitive dependency: transitive
description: description:
name: crypto name: crypto
sha256: ec30d999af904f33454ba22ed9a86162b35e52b44ac4807d1d93c288041d7d27 sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.5" version: "3.0.6"
cupertino_icons: cupertino_icons:
dependency: "direct main" dependency: "direct main"
description: description:
@ -198,6 +206,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" 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: fake_async:
dependency: transitive dependency: transitive
description: description:
@ -218,15 +234,23 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: fixnum name: fixnum
sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.0" version: "1.1.1"
flutter: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" 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: flutter_lints:
dependency: "direct dev" dependency: "direct dev"
description: description:
@ -392,6 +416,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
package_config: package_config:
dependency: transitive dependency: transitive
description: description:
@ -424,6 +456,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.0" version: "1.4.0"
provider:
dependency: transitive
description:
name: provider
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
url: "https://pub.dev"
source: hosted
version: "6.1.2"
pub_semver: pub_semver:
dependency: transitive dependency: transitive
description: description:

View File

@ -15,6 +15,10 @@ dependencies:
json_annotation: ^4.8.1 json_annotation: ^4.8.1
dio: ^5.4.2+1 dio: ^5.4.2+1
pretty_dio_logger: ^1.3.1 pretty_dio_logger: ^1.3.1
equatable: ^2.0.5
flutter_bloc: ^8.1.5
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter

View File

@ -8,7 +8,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pmu_labs/main.dart'; import 'package:flutter_app/main.dart';
void main() { void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async { testWidgets('Counter increments smoke test', (WidgetTester tester) async {