diff --git a/lib/components/utils/debounce.dart b/lib/components/utils/debounce.dart new file mode 100644 index 0000000..c5d641a --- /dev/null +++ b/lib/components/utils/debounce.dart @@ -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); + } +} diff --git a/lib/components/utils/error_callback.dart b/lib/components/utils/error_callback.dart new file mode 100644 index 0000000..5e3110f --- /dev/null +++ b/lib/components/utils/error_callback.dart @@ -0,0 +1 @@ +typedef OnErrorCallback = void Function(String? error)?; \ No newline at end of file diff --git a/lib/data/dtos/mangas_dto.dart b/lib/data/dtos/mangas_dto.dart index 2cb2137..7d5397d 100644 --- a/lib/data/dtos/mangas_dto.dart +++ b/lib/data/dtos/mangas_dto.dart @@ -5,12 +5,26 @@ part 'mangas_dto.g.dart'; @JsonSerializable(createToJson: false) class MangasDto { final List? data; - - const MangasDto({this.data}); + final MangaPaginationDto? pagination; + const MangasDto({this.data, this.pagination}); factory MangasDto.fromJson(Map 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 json) => + _$MangaPaginationDtoFromJson(json); +} @JsonSerializable(createToJson: false) class MangaDataDto { diff --git a/lib/data/dtos/mangas_dto.g.dart b/lib/data/dtos/mangas_dto.g.dart index ababe6c..ee18790 100644 --- a/lib/data/dtos/mangas_dto.g.dart +++ b/lib/data/dtos/mangas_dto.g.dart @@ -10,6 +10,17 @@ MangasDto _$MangasDtoFromJson(Map json) => MangasDto( data: (json['data'] as List?) ?.map((e) => MangaDataDto.fromJson(e as Map)) .toList(), + pagination: json['pagination'] == null + ? null + : MangaPaginationDto.fromJson( + json['pagination'] as Map), + ); + +MangaPaginationDto _$MangaPaginationDtoFromJson(Map 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 json) => MangaDataDto( diff --git a/lib/data/mappers/mangas_mapper.dart b/lib/data/mappers/mangas_mapper.dart index 5bc5813..ac378e1 100644 --- a/lib/data/mappers/mangas_mapper.dart +++ b/lib/data/mappers/mangas_mapper.dart @@ -1,5 +1,6 @@ import 'package:flutter_app/data/dtos/mangas_dto.dart'; import 'package:flutter_app/domain/models/carddata.dart'; +import 'package:flutter_app/presentation/home_page/home_page.dart'; extension MangaDataDtoMapper on MangaDataDto { CardData toDomain() => CardData( @@ -9,3 +10,10 @@ extension MangaDataDtoMapper on MangaDataDto { 'Статус: ${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); +} \ No newline at end of file diff --git a/lib/data/repositories/api_interface.dart b/lib/data/repositories/api_interface.dart index 070c15f..f462fc3 100644 --- a/lib/data/repositories/api_interface.dart +++ b/lib/data/repositories/api_interface.dart @@ -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 { - Future?> loadData(); + Future loadData({OnErrorCallback? onError}); } \ No newline at end of file diff --git a/lib/data/repositories/manga_repository.dart b/lib/data/repositories/manga_repository.dart index da7edaf..ac9664d 100644 --- a/lib/data/repositories/manga_repository.dart +++ b/lib/data/repositories/manga_repository.dart @@ -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/mappers/mangas_mapper.dart'; import 'package:flutter_app/data/repositories/api_interface.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'; class MangaRepository extends ApiInterface { @@ -14,18 +15,28 @@ class MangaRepository extends ApiInterface { static const String _baseUrl = 'https://api.jikan.moe'; @override - Future?> loadData({String? q}) async { + Future loadData({ + OnErrorCallback? onError, + String? q, + int page = 1, + int pageSize = 25, + }) async { try { const String url = '$_baseUrl/v4/manga'; - final Response response = await _dio.get>( - url, - queryParameters: q != null ? {'q': q} : null); + final Response response = await _dio + .get>(url, queryParameters: { + 'q': q, + 'page': page, + 'limit': !(pageSize > 25) ? pageSize : 25 + }); + final MangasDto dto = MangasDto.fromJson(response.data as Map); - final List? data = dto.data?.map((e) => e.toDomain()).toList(); + final HomeData? data = dto.toDomain(); return data; } on DioException catch (e) { + onError?.call(e.response?.statusMessage); return null; } } diff --git a/lib/data/repositories/mock_repository.dart b/lib/data/repositories/mock_repository.dart index 7423eb8..de29a9d 100644 --- a/lib/data/repositories/mock_repository.dart +++ b/lib/data/repositories/mock_repository.dart @@ -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/domain/models/carddata.dart'; +import 'package:flutter_app/presentation/home_page/home_page.dart'; class MockRepository extends ApiInterface { @override - Future?> loadData() async { - return [ + Future loadData({OnErrorCallback? onError}) async { + return HomeData( + data: [ CardData('JoJo’s 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('Mock data', descriptionText: 'Mock data description', imageUrl: 'https://cdn-user30887.skyeng.ru/uploads/6692a339c6989979804399.png'), - ]; + ], + ); } } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 301e13e..f4b01ab 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,8 @@ 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_bloc/flutter_bloc.dart'; void main() { runApp(const MyApp()); @@ -14,25 +17,18 @@ class MyApp extends StatelessWidget { return MaterialApp( title: 'Flutter Demo', 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), useMaterial3: true, ), - home: const MyHomePage(title: 'Разубаев Сергей Михайлович'), + home: RepositoryProvider( + lazy: true, + create: (_) => MangaRepository(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const HomePage(), + ), + ) ); } } diff --git a/lib/presentation/home_page/bloc/bloc.dart b/lib/presentation/home_page/bloc/bloc.dart new file mode 100644 index 0000000..c143fc1 --- /dev/null +++ b/lib/presentation/home_page/bloc/bloc.dart @@ -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{ + final MangaRepository repo; + + HomeBloc(this.repo) : super (const HomeState()) { + on(_onLoadData); + } + Future _onLoadData(HomeLoadDataEvent event, Emitter 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)); + } +} \ No newline at end of file diff --git a/lib/presentation/home_page/bloc/events.dart b/lib/presentation/home_page/bloc/events.dart new file mode 100644 index 0000000..5fc137f --- /dev/null +++ b/lib/presentation/home_page/bloc/events.dart @@ -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}); +} \ No newline at end of file diff --git a/lib/presentation/home_page/bloc/state.dart b/lib/presentation/home_page/bloc/state.dart new file mode 100644 index 0000000..f55ad18 --- /dev/null +++ b/lib/presentation/home_page/bloc/state.dart @@ -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 get props => [data, isLoading, isPaginationLoading]; +} diff --git a/lib/presentation/home_page/home_page.dart b/lib/presentation/home_page/home_page.dart index f37c738..d235b9f 100644 --- a/lib/presentation/home_page/home_page.dart +++ b/lib/presentation/home_page/home_page.dart @@ -1,48 +1,35 @@ import 'package:flutter/cupertino.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/mock_repository.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'; part 'card.dart'; - -class MyHomePage extends StatefulWidget { - 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; +class HomePage extends StatefulWidget { + const HomePage({super.key}); @override - State createState() => _MyHomePageState(); + State createState() => _HomePageState(); } -class _MyHomePageState extends State { +class _HomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - backgroundColor: Theme - .of(context) - .colorScheme - .inversePrimary, - title: Text(widget.title), + backgroundColor: Theme.of(context).colorScheme.inversePrimary, ), body: const Body(), ); } - - } class Body extends StatefulWidget { @@ -53,6 +40,37 @@ class Body extends StatefulWidget { } class _BodyState extends State { + final scrollController = ScrollController(); + final searchController = TextEditingController(); + + @override + void initState() { + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().add(const HomeLoadDataEvent()); + }); + scrollController.addListener(_onNextPageListener); + + super.initState(); + } + + void _onNextPageListener() { + if (scrollController.offset > scrollController.position.maxScrollExtent) { + final bloc = context.read(); + 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(); var data = MangaRepository().loadData(); @@ -61,10 +79,7 @@ class _BodyState extends State { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( 'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}', - style: Theme - .of(context) - .textTheme - .bodyLarge, + style: Theme.of(context).textTheme.bodyLarge, ), backgroundColor: Colors.orangeAccent, duration: const Duration(seconds: 1), @@ -77,44 +92,65 @@ class _BodyState extends State { context, CupertinoPageRoute(builder: (context) => DetailsPage(data))); } + Future _onRefresh() { + context + .read() + .add(HomeLoadDataEvent(search: searchController.text)); + return Future.value(null); + } -@override -Widget build(BuildContext context) { - return Padding( - padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), - child: Column( - children: [ - Padding( - padding: const EdgeInsets.all(12), - child: CupertinoSearchTextField( - onChanged: (search) { - setState(() { - data = repo.loadData(q:search); - }); - }, - ), - ), - Expanded(child: Center( - child: FutureBuilder?>( - future: data, - builder: (context, snapshot) => - SingleChildScrollView( - child: snapshot.hasData ? Column( - mainAxisAlignment: MainAxisAlignment.center, - children: snapshot.data!.map((data) { - return _Card.fromData(data, - onLike: (String title, bool isLiked) => - _showSnackbar(context, title, isLiked), - onTap: () => _navToDetails(context, data),); - }).toList() ?? [], - ) - : const CircularProgressIndicator(), - ), - ), - ), - ) - ], + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.all(12), + child: CupertinoSearchTextField( + controller: searchController, + onChanged: (search) { + Debounce.run(() => context + .read() + .add(HomeLoadDataEvent(search: search))); + })), + BlocBuilder( + builder: (context, state) => state.isLoading + ? 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, + onLike: (title, isLiked) => + _showSnackbar( + context, title, isLiked), + onTap: () => + _navToDetails(context, data), + ) + : const SizedBox.shrink(); + }), + ), + )), + BlocBuilder( + builder: (context, state) => state.isPaginationLoading + ? const CircularProgressIndicator() + : const SizedBox.shrink()) + ], + )); + } +} - )); -}} +class HomeData { + final List? data; + final int? nextPage; + HomeData({this.data, this.nextPage}); +} diff --git a/pubspec.lock b/pubspec.lock index afacf55..d7eca9a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -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: @@ -154,18 +162,18 @@ packages: dependency: transitive description: name: convert - sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.1.2" crypto: dependency: transitive description: name: crypto - sha256: ec30d999af904f33454ba22ed9a86162b35e52b44ac4807d1d93c288041d7d27 + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" url: "https://pub.dev" source: hosted - version: "3.0.5" + version: "3.0.6" cupertino_icons: dependency: "direct main" description: @@ -198,6 +206,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: @@ -218,15 +234,23 @@ packages: dependency: transitive description: name: fixnum - sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.1.1" flutter: dependency: "direct main" 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 +416,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 +456,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: diff --git a/pubspec.yaml b/pubspec.yaml index 183d25f..1865baf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,6 +15,10 @@ dependencies: json_annotation: ^4.8.1 dio: ^5.4.2+1 pretty_dio_logger: ^1.3.1 + + equatable: ^2.0.5 + flutter_bloc: ^8.1.5 + dev_dependencies: flutter_test: sdk: flutter diff --git a/test/widget_test.dart b/test/widget_test.dart index 17e0818..be73888 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:pmu_labs/main.dart'; +import 'package:flutter_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async {