From fe11a5b67839af75b13b09f7e353595afc2b9c1f Mon Sep 17 00:00:00 2001 From: dyakonovr Date: Wed, 25 Sep 2024 14:35:14 +0400 Subject: [PATCH] final? --- lib/components/utils/debounce.dart | 20 +++ lib/data/dtos/characters_dto.dart | 40 ++++- lib/data/dtos/characters_dto.g.dart | 16 ++ lib/data/mappers/characters_mapper.dart | 7 + lib/data/repositories/api_interface.dart | 7 + .../repositories/mock_repository.dart | 13 +- .../repositories/potter_repository.dart | 27 ++-- lib/domain/models/home_data.dart | 8 + lib/main.dart | 14 +- lib/presentation/home_page/bloc/bloc.dart | 36 +++++ lib/presentation/home_page/bloc/events.dart | 10 ++ lib/presentation/home_page/bloc/state.dart | 31 ++++ lib/presentation/home_page/card.dart | 2 +- lib/presentation/home_page/home_page.dart | 146 ++++++++++++------ lib/repositories/api_interface.dart | 5 - pubspec.lock | 40 +++++ pubspec.yaml | 3 + 17 files changed, 344 insertions(+), 81 deletions(-) create mode 100644 lib/components/utils/debounce.dart create mode 100644 lib/data/repositories/api_interface.dart rename lib/{ => data}/repositories/mock_repository.dart (65%) rename lib/{ => data}/repositories/potter_repository.dart (58%) create mode 100644 lib/domain/models/home_data.dart create mode 100644 lib/presentation/home_page/bloc/bloc.dart create mode 100644 lib/presentation/home_page/bloc/events.dart create mode 100644 lib/presentation/home_page/bloc/state.dart delete mode 100644 lib/repositories/api_interface.dart diff --git a/lib/components/utils/debounce.dart b/lib/components/utils/debounce.dart new file mode 100644 index 0000000..6ebc241 --- /dev/null +++ b/lib/components/utils/debounce.dart @@ -0,0 +1,20 @@ +import 'dart:async'; +import 'dart:ui'; + +class Debounce { + factory Debounce() => _instance; + + // Приватный конструктор + Debounce._(); + + static final Debounce _instance = Debounce._(); + + static Timer? _timer; + + static void run( + {required VoidCallback action, + Duration delay = const Duration(milliseconds: 500)}) { + _timer?.cancel(); + _timer = Timer(delay, action); + } +} diff --git a/lib/data/dtos/characters_dto.dart b/lib/data/dtos/characters_dto.dart index 0b864f3..dbf04a1 100644 --- a/lib/data/dtos/characters_dto.dart +++ b/lib/data/dtos/characters_dto.dart @@ -1,16 +1,40 @@ import 'package:json_annotation/json_annotation.dart'; -// dart run build_runner build --delete-conflicting-outputs - part 'characters_dto.g.dart'; +// dart run build_runner build --delete-conflicting-outputs + @JsonSerializable(createToJson: false) class CharactersDto { final List? data; + final MetaDto? meta; - const CharactersDto({ this.data }); + const CharactersDto({this.data, this.meta}); - factory CharactersDto.fromJson(Map json) => _$CharactersDtoFromJson(json); + factory CharactersDto.fromJson(Map json) => + _$CharactersDtoFromJson(json); +} + +@JsonSerializable(createToJson: false) +class MetaDto { + final PaginationDto? pagination; + + const MetaDto({this.pagination}); + + factory MetaDto.fromJson(Map json) => + _$MetaDtoFromJson(json); +} + +@JsonSerializable(createToJson: false) +class PaginationDto { + final int? current; + final int? next; + final int? last; + + const PaginationDto({this.current, this.last, this.next}); + + factory PaginationDto.fromJson(Map json) => + _$PaginationDtoFromJson(json); } @JsonSerializable(createToJson: false) @@ -20,7 +44,8 @@ class CharacterDataDto { const CharacterDataDto(this.id, this.attributes); - factory CharacterDataDto.fromJson(Map json) => _$CharacterDataDtoFromJson(json); + factory CharacterDataDto.fromJson(Map json) => + _$CharacterDataDtoFromJson(json); } @JsonSerializable(createToJson: false) @@ -31,5 +56,6 @@ class CharacterAttributesDataDto { CharacterAttributesDataDto(this.name, this.image, this.species); - factory CharacterAttributesDataDto.fromJson(Map json) => _$CharacterAttributesDataDtoFromJson(json); -} \ No newline at end of file + factory CharacterAttributesDataDto.fromJson(Map json) => + _$CharacterAttributesDataDtoFromJson(json); +} diff --git a/lib/data/dtos/characters_dto.g.dart b/lib/data/dtos/characters_dto.g.dart index fc4583a..06ce41d 100644 --- a/lib/data/dtos/characters_dto.g.dart +++ b/lib/data/dtos/characters_dto.g.dart @@ -11,6 +11,22 @@ CharactersDto _$CharactersDtoFromJson(Map json) => data: (json['data'] as List?) ?.map((e) => CharacterDataDto.fromJson(e as Map)) .toList(), + meta: json['meta'] == null + ? null + : MetaDto.fromJson(json['meta'] as Map), + ); + +MetaDto _$MetaDtoFromJson(Map json) => MetaDto( + pagination: json['pagination'] == null + ? null + : PaginationDto.fromJson(json['pagination'] as Map), + ); + +PaginationDto _$PaginationDtoFromJson(Map json) => + PaginationDto( + current: (json['current'] as num?)?.toInt(), + last: (json['last'] as num?)?.toInt(), + next: (json['next'] as num?)?.toInt(), ); CharacterDataDto _$CharacterDataDtoFromJson(Map json) => diff --git a/lib/data/mappers/characters_mapper.dart b/lib/data/mappers/characters_mapper.dart index 2e15d84..7c94908 100644 --- a/lib/data/mappers/characters_mapper.dart +++ b/lib/data/mappers/characters_mapper.dart @@ -1,5 +1,6 @@ import 'package:lab/data/dtos/characters_dto.dart'; import 'package:lab/domain/models/card_data.dart'; +import 'package:lab/domain/models/home_data.dart'; extension CharacterDataDtoToModel on CharacterDataDto { CardData toDomain() => CardData( @@ -8,3 +9,9 @@ extension CharacterDataDtoToModel on CharacterDataDto { "https://upload.wikimedia.org/wikipedia/commons/a/a2/Person_Image_Placeholder.png", species: attributes?.species ?? "UNKNOWN"); } + +extension ChatactersDtoToModel on CharactersDto { + HomeData toDomain() => HomeData( + data: data?.map((e) => e.toDomain()).toList(), + nextPage: meta?.pagination?.next); +} diff --git a/lib/data/repositories/api_interface.dart b/lib/data/repositories/api_interface.dart new file mode 100644 index 0000000..543a8be --- /dev/null +++ b/lib/data/repositories/api_interface.dart @@ -0,0 +1,7 @@ +import 'package:lab/domain/models/home_data.dart'; + +typedef OnErrorCallback = void Function(String? error); + +abstract class ApiInterface { + Future loadData({OnErrorCallback? onError}); +} diff --git a/lib/repositories/mock_repository.dart b/lib/data/repositories/mock_repository.dart similarity index 65% rename from lib/repositories/mock_repository.dart rename to lib/data/repositories/mock_repository.dart index 2bde7e5..3e3814a 100644 --- a/lib/repositories/mock_repository.dart +++ b/lib/data/repositories/mock_repository.dart @@ -1,20 +1,21 @@ +import 'package:lab/data/repositories/api_interface.dart'; import 'package:lab/domain/models/card_data.dart'; -import 'package:lab/repositories/api_interface.dart'; +import 'package:lab/domain/models/home_data.dart'; class MockRepository extends ApiInterface { @override - Future> loadData(String? q) async { - return [ - CardData( + Future loadData({OnErrorCallback? onError}) async { + return HomeData(data: [ + const CardData( name: "test 0", species: "Species 0", image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtAT11wKgHrJBUYzIBFogucXg0a9fE0fQXDQ&s"), - CardData( + const CardData( name: "test 1", species: "Species 1", image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtAT11wKgHrJBUYzIBFogucXg0a9fE0fQXDQ&s") - ]; + ]); } } diff --git a/lib/repositories/potter_repository.dart b/lib/data/repositories/potter_repository.dart similarity index 58% rename from lib/repositories/potter_repository.dart rename to lib/data/repositories/potter_repository.dart index 0e7a152..1456872 100644 --- a/lib/repositories/potter_repository.dart +++ b/lib/data/repositories/potter_repository.dart @@ -1,36 +1,43 @@ import 'dart:developer'; - import 'package:dio/dio.dart'; import 'package:lab/data/dtos/characters_dto.dart'; import 'package:lab/data/mappers/characters_mapper.dart'; -import 'package:lab/domain/models/card_data.dart'; -import 'package:lab/repositories/api_interface.dart'; +import 'package:lab/data/repositories/api_interface.dart'; +import 'package:lab/domain/models/home_data.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart'; class PotterRepository extends ApiInterface { - static final Dio _dio = Dio(BaseOptions(connectTimeout: Duration(seconds: 10))) + static final Dio _dio = Dio( + BaseOptions(connectTimeout: const Duration(seconds: 10))) ..interceptors.add( PrettyDioLogger(request: true, requestHeader: true, requestBody: true)); static const String _baseUrl = "https://api.potterdb.com/v1"; @override - Future?> loadData(String? q) async { + Future loadData( + {OnErrorCallback? onError, + String? q, + int page = 1, + int pageSize = 10}) async { try { - const String url = '$_baseUrl/characters?page[size]=5'; + const String url = '$_baseUrl/characters'; final Response response = await _dio.get>( url, - queryParameters: q != null ? {"filter[name_cont]": q} : null, + queryParameters: { + 'filter[name_cont]': q, + 'page[number]': page, + 'page[size]': pageSize + }, ); final CharactersDto dto = CharactersDto.fromJson(response.data as Map); - final List? data = dto.data?.map((e) => e.toDomain()).toList(); - - return data; + return dto.toDomain(); } on DioException catch (e) { log("DioException: $e"); + onError?.call(e.error?.toString()); return null; } catch (e) { log('Unknown error: $e'); diff --git a/lib/domain/models/home_data.dart b/lib/domain/models/home_data.dart new file mode 100644 index 0000000..46d680b --- /dev/null +++ b/lib/domain/models/home_data.dart @@ -0,0 +1,8 @@ +import 'package:lab/domain/models/card_data.dart'; + +class HomeData { + final List? data; + final int? nextPage; + + HomeData({this.data, this.nextPage}); +} diff --git a/lib/main.dart b/lib/main.dart index 65c9339..c0f9722 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,4 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:lab/data/repositories/potter_repository.dart'; +import 'package:lab/presentation/home_page/bloc/bloc.dart'; import 'package:lab/presentation/home_page/home_page.dart'; void main() { @@ -17,8 +20,15 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: Colors.white), useMaterial3: true, ), - home: const MyHomePage(title: 'Lab 5: API and friends'), + home: RepositoryProvider( + lazy: true, + create: (_) => PotterRepository(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const MyHomePage(title: 'Lab 6: Architecture'), + ), + ), ); } } - diff --git a/lib/presentation/home_page/bloc/bloc.dart b/lib/presentation/home_page/bloc/bloc.dart new file mode 100644 index 0000000..dab7910 --- /dev/null +++ b/lib/presentation/home_page/bloc/bloc.dart @@ -0,0 +1,36 @@ +import 'package:lab/data/repositories/potter_repository.dart'; +import 'package:lab/presentation/home_page/bloc/events.dart'; +import 'package:lab/presentation/home_page/bloc/state.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class HomeBloc extends Bloc { + final PotterRepository 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)); + } + + 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( + isLoading: false, + isPaginationLoading: false, + data: data, + error: error)); + } +} diff --git a/lib/presentation/home_page/bloc/events.dart b/lib/presentation/home_page/bloc/events.dart new file mode 100644 index 0000000..cefba70 --- /dev/null +++ b/lib/presentation/home_page/bloc/events.dart @@ -0,0 +1,10 @@ +abstract class HomeEvent { + const HomeEvent(); +} + +class HomeLoadDataEvent extends HomeEvent { + final String? search; + final int? nextPage; + + const HomeLoadDataEvent({this.search, this.nextPage}); +} diff --git a/lib/presentation/home_page/bloc/state.dart b/lib/presentation/home_page/bloc/state.dart new file mode 100644 index 0000000..361aa61 --- /dev/null +++ b/lib/presentation/home_page/bloc/state.dart @@ -0,0 +1,31 @@ +import 'package:equatable/equatable.dart'; +import 'package:lab/domain/models/home_data.dart'; + +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}); + + // Получение нового экземпляра состояния + HomeState copyWith( + {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); + + // Поля, по которым Equatable сравнивает состояния + @override + List get props => [data, isLoading, isPaginationLoading, error]; +} diff --git a/lib/presentation/home_page/card.dart b/lib/presentation/home_page/card.dart index df1d90e..7bbe8ce 100644 --- a/lib/presentation/home_page/card.dart +++ b/lib/presentation/home_page/card.dart @@ -18,7 +18,7 @@ class _Card extends StatefulWidget { this.onTap}); factory _Card.fromData( - CardData data, OnLikeFunction? onLike, VoidCallback? onTap) => + CardData data, {OnLikeFunction? onLike, VoidCallback? onTap}) => _Card( name: data.name, image: data.image, diff --git a/lib/presentation/home_page/home_page.dart b/lib/presentation/home_page/home_page.dart index 30177ed..53329ac 100644 --- a/lib/presentation/home_page/home_page.dart +++ b/lib/presentation/home_page/home_page.dart @@ -1,9 +1,12 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:lab/components/utils/debounce.dart'; import 'package:lab/domain/models/card_data.dart'; import 'package:lab/presentation/details_page/details_page.dart'; -import 'package:lab/repositories/api_interface.dart'; -import 'package:lab/repositories/potter_repository.dart'; +import 'package:lab/presentation/home_page/bloc/bloc.dart'; +import 'package:lab/presentation/home_page/bloc/events.dart'; +import 'package:lab/presentation/home_page/bloc/state.dart'; part 'card.dart'; @@ -18,13 +21,49 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { final TextEditingController _searchController = TextEditingController(); - final ApiInterface repo = PotterRepository(); - late Future?> _data; + final _scrollController = ScrollController(); @override void initState() { + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().add(const HomeLoadDataEvent()); + }); + + _scrollController.addListener(_onNextPageListener); + super.initState(); - _data = repo.loadData(null); + } + + @override + void dispose() { + _searchController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + 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)); + } + } + } + + Future _onRefresh() { + context + .read() + .add(HomeLoadDataEvent(search: _searchController.text)); + return Future.value(null); + } + + void _onSearchInputChange(search) { + Debounce.run( + action: () => + context.read().add(HomeLoadDataEvent(search: search))); } void _showSnackBar(BuildContext context, String text) { @@ -46,58 +85,65 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { - // final d = repo.loadData(null); return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title), ), - body: ListView( + body: Column( children: [ - Column( - children: [ - Padding( - padding: const EdgeInsets.only(right: 30, left: 30, top: 20), - child: CupertinoSearchTextField( - controller: _searchController, - onChanged: (search) { - setState(() { - _data = repo.loadData(search); - }); - }, - ), - ), - FutureBuilder?>( - future: _data, - builder: (context, snapshot) => SingleChildScrollView( - padding: const EdgeInsets.symmetric( - horizontal: 30, - vertical: 15, - ), - child: snapshot.hasData - ? Column( - mainAxisAlignment: MainAxisAlignment.center, - children: snapshot.data?.map((cardData) { - return Column( - children: [ - const SizedBox(height: 20), - _Card.fromData( - cardData, - (String text) => + Padding( + padding: const EdgeInsets.only(right: 30, left: 30, top: 20), + child: CupertinoSearchTextField( + controller: _searchController, + onChanged: _onSearchInputChange, + ), + ), + BlocBuilder( + builder: (context, state) => state.error != null + ? Text( + state.error ?? "", + style: Theme.of(context) + .textTheme + .headlineSmall + ?.copyWith(color: Colors.red), + ) + : state.isLoading + ? const Padding( + padding: EdgeInsets.only(top: 20), + child: CircularProgressIndicator(), + ) + : Expanded( + child: RefreshIndicator( + onRefresh: _onRefresh, + child: ListView.separated( + controller: _scrollController, + padding: const EdgeInsets.all(30), + separatorBuilder: (context, index) => + const SizedBox(height: 20), + itemCount: state.data?.data?.length ?? 0, + itemBuilder: (context, index) { + final data = state.data?.data?[index]; + + return data == null + ? const SizedBox.shrink() + : _Card.fromData( + data, + onLike: (String text) => _showSnackBar(context, text), - () => _navigateToDetailsPage( - context, cardData), - ), - const SizedBox(height: 20) - ], - ); - }).toList() ?? - []) - : const CircularProgressIndicator(), - ), - ), - ], - ) + onTap: () => + _navigateToDetailsPage(context, data), + ); + }, + ), + ), + ), + ), + BlocBuilder( + builder: (context, state) => state.isPaginationLoading + ? const CircularProgressIndicator() + : const SizedBox.shrink(), + ), ], ), ); diff --git a/lib/repositories/api_interface.dart b/lib/repositories/api_interface.dart deleted file mode 100644 index b344d3a..0000000 --- a/lib/repositories/api_interface.dart +++ /dev/null @@ -1,5 +0,0 @@ -import 'package:lab/domain/models/card_data.dart'; - -abstract class ApiInterface { - Future?> loadData(String? q); -} diff --git a/pubspec.lock b/pubspec.lock index e4c7f4e..cf63f83 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: @@ -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: @@ -227,6 +243,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 +416,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.6" + 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 9a475e8..06ebd47 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -40,6 +40,9 @@ dependencies: dio: ^5.4.2+1 pretty_dio_logger: ^1.3.1 + flutter_bloc: ^8.1.5 + equatable: ^2.0.5 + dev_dependencies: flutter_test: sdk: flutter