From 57d946a8a29b78e70c288c093830a0f3f6cbcdc2 Mon Sep 17 00:00:00 2001 From: halina Date: Tue, 12 Nov 2024 00:23:53 +0400 Subject: [PATCH] =?UTF-8?q?6=20=D0=BB=D0=B0=D0=B1=D0=B0=20=D1=83=D1=80?= =?UTF-8?q?=D0=B0=20=D0=BF=D0=BE=D0=B1=D0=B5=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/components/utils/debounce.dart | 20 +++ .../lib/data/dtos/thrones_character_dto.dart | 70 ++++++--- .../data/dtos/thrones_character_dto.g.dart | 38 +++-- .../lib/data/mappers/characters_mapper.dart | 12 +- .../lib/data/repositories/api_interface.dart | 3 +- .../lib/data/repositories/got_repository.dart | 36 +++-- .../data/repositories/mock_repository.dart | 142 +++++++++--------- flutter_app/lib/domain/models/card.dart | 10 +- flutter_app/lib/domain/models/home.dart | 8 + flutter_app/lib/main.dart | 18 ++- .../details_page/details_page.dart | 2 +- .../lib/presentation/home_page/bloc/bloc.dart | 39 +++++ .../presentation/home_page/bloc/events.dart | 10 ++ .../presentation/home_page/bloc/state.dart | 43 ++++++ .../presentation/home_page/bloc/state.g.dart | 92 ++++++++++++ .../lib/presentation/home_page/card.dart | 6 +- .../lib/presentation/home_page/home_page.dart | 107 +++++++------ flutter_app/pubspec.lock | 56 +++++++ flutter_app/pubspec.yaml | 3 + 19 files changed, 543 insertions(+), 172 deletions(-) create mode 100644 flutter_app/lib/components/utils/debounce.dart create mode 100644 flutter_app/lib/domain/models/home.dart create mode 100644 flutter_app/lib/presentation/home_page/bloc/bloc.dart create mode 100644 flutter_app/lib/presentation/home_page/bloc/events.dart create mode 100644 flutter_app/lib/presentation/home_page/bloc/state.dart create mode 100644 flutter_app/lib/presentation/home_page/bloc/state.g.dart diff --git a/flutter_app/lib/components/utils/debounce.dart b/flutter_app/lib/components/utils/debounce.dart new file mode 100644 index 0000000..b4e1f35 --- /dev/null +++ b/flutter_app/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 ( + VoidCallback action, { + Duration delay = const Duration(milliseconds: 500), + }) { + _timer?.cancel(); + _timer = Timer(delay, action); + } +} \ No newline at end of file diff --git a/flutter_app/lib/data/dtos/thrones_character_dto.dart b/flutter_app/lib/data/dtos/thrones_character_dto.dart index 277f44a..70ab86f 100644 --- a/flutter_app/lib/data/dtos/thrones_character_dto.dart +++ b/flutter_app/lib/data/dtos/thrones_character_dto.dart @@ -3,26 +3,56 @@ import 'package:json_annotation/json_annotation.dart'; part 'thrones_character_dto.g.dart'; @JsonSerializable(createToJson: false) -class ThronesCharacterDto { - final int id; - final String firstName; - final String lastName; - final String fullName; - final String title; - final String family; - final String image; - final String imageUrl; +class ThronesCharactersDto { + final List characters; + final InfoDto? info; - ThronesCharacterDto({ - required this.id, - required this.firstName, - required this.lastName, - required this.fullName, - required this.title, - required this.family, - required this.image, - required this.imageUrl, - }); + const ThronesCharactersDto({required this.characters, this.info}); - factory ThronesCharacterDto.fromJson(Map json) => _$ThronesCharacterDtoFromJson(json); + factory ThronesCharactersDto.fromJson(List json) { + final List characters = json + .map((item) => ThronesCharacterDataDto.fromJson(item as Map)) + .toList(); + return ThronesCharactersDto(characters: characters); + } +} + +@JsonSerializable(createToJson: false) +class ThronesCharacterDataDto { + final int? id; + final String? firstName; + final String? lastName; + final String? fullName; + final String? title; + final String? family; + final String? image; + final String? imageUrl; + + const ThronesCharacterDataDto( + {this.id, this.firstName, this.lastName, this.fullName, this.title, this.family, this.image, this.imageUrl,}); + + factory ThronesCharacterDataDto.fromJson(Map json) => + _$ThronesCharacterDataDtoFromJson(json); +} + +@JsonSerializable(createToJson: false) +class InfoDto { + final String? next; + final String? last; + final int? nextPage; + final int? lastPage; + + InfoDto({this.next, this.last}) + : nextPage = _extractPageNumber(next), + lastPage = _extractPageNumber(last); + + static int? _extractPageNumber(String? url) { + if (url == null) return null; + final RegExp regExp = RegExp(r'page=(\d+)'); + final Match? match = regExp.firstMatch(url); + return match != null ? int.parse(match.group(1)!) : null; + } + + factory InfoDto.fromJson(Map json) => + _$InfoDtoFromJson(json); } \ No newline at end of file diff --git a/flutter_app/lib/data/dtos/thrones_character_dto.g.dart b/flutter_app/lib/data/dtos/thrones_character_dto.g.dart index c0e5cfb..2176d6f 100644 --- a/flutter_app/lib/data/dtos/thrones_character_dto.g.dart +++ b/flutter_app/lib/data/dtos/thrones_character_dto.g.dart @@ -6,14 +6,32 @@ part of 'thrones_character_dto.dart'; // JsonSerializableGenerator // ************************************************************************** -ThronesCharacterDto _$ThronesCharacterDtoFromJson(Map json) => - ThronesCharacterDto( - id: (json['id'] as num).toInt(), - firstName: json['firstName'] as String, - lastName: json['lastName'] as String, - fullName: json['fullName'] as String, - title: json['title'] as String, - family: json['family'] as String, - image: json['image'] as String, - imageUrl: json['imageUrl'] as String, +ThronesCharactersDto _$ThronesCharactersDtoFromJson( + Map json) => + ThronesCharactersDto( + characters: (json['characters'] as List) + .map((e) => + ThronesCharacterDataDto.fromJson(e as Map)) + .toList(), + info: json['info'] == null + ? null + : InfoDto.fromJson(json['info'] as Map), + ); + +ThronesCharacterDataDto _$ThronesCharacterDataDtoFromJson( + Map json) => + ThronesCharacterDataDto( + id: (json['id'] as num?)?.toInt(), + firstName: json['firstName'] as String?, + lastName: json['lastName'] as String?, + fullName: json['fullName'] as String?, + title: json['title'] as String?, + family: json['family'] as String?, + image: json['image'] as String?, + imageUrl: json['imageUrl'] as String?, + ); + +InfoDto _$InfoDtoFromJson(Map json) => InfoDto( + next: json['next'] as String?, + last: json['last'] as String?, ); diff --git a/flutter_app/lib/data/mappers/characters_mapper.dart b/flutter_app/lib/data/mappers/characters_mapper.dart index 5e50b6f..1c02009 100644 --- a/flutter_app/lib/data/mappers/characters_mapper.dart +++ b/flutter_app/lib/data/mappers/characters_mapper.dart @@ -1,18 +1,19 @@ import 'package:flutter_app/data/dtos/thrones_character_dto.dart'; import 'package:flutter_app/domain/models/card.dart'; +import 'package:flutter_app/domain/models/home.dart'; const _imagePlaceholder = 'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png'; -extension ThronesCharacterDtoToModel on ThronesCharacterDto { +extension ThronesCharacterDtoToModel on ThronesCharacterDataDto { CardData toDomain() => CardData( descriptionText: _makeDescriptionText(title, family), - imageUrl: imageUrl, firstName: firstName, lastName: lastName, title: title, family: family, fullName: fullName, + imageUrl: imageUrl, text: '', ); @@ -25,4 +26,11 @@ extension ThronesCharacterDtoToModel on ThronesCharacterDto { ? 'Family: $family' : ''; } +} + +extension ThronesCharactersDtoToModel on ThronesCharactersDto { + HomeData toDomain() => HomeData( + data: characters.map((e) => e.toDomain()).toList(), + nextPage: info?.nextPage, + ); } \ No newline at end of file diff --git a/flutter_app/lib/data/repositories/api_interface.dart b/flutter_app/lib/data/repositories/api_interface.dart index c75917e..2edb0ef 100644 --- a/flutter_app/lib/data/repositories/api_interface.dart +++ b/flutter_app/lib/data/repositories/api_interface.dart @@ -1,7 +1,8 @@ import 'package:flutter_app/domain/models/card.dart'; +import 'package:flutter_app/domain/models/home.dart'; typedef OnErrorCallback = void Function(String? error); abstract class ApiInterface { - Future?> loadData({OnErrorCallback? onError}); + Future loadData({OnErrorCallback? onError}); } \ No newline at end of file diff --git a/flutter_app/lib/data/repositories/got_repository.dart b/flutter_app/lib/data/repositories/got_repository.dart index d81c92b..efd96ba 100644 --- a/flutter_app/lib/data/repositories/got_repository.dart +++ b/flutter_app/lib/data/repositories/got_repository.dart @@ -3,34 +3,48 @@ import 'package:flutter_app/data/dtos/thrones_character_dto.dart'; import 'package:flutter_app/data/mappers/characters_mapper.dart'; import 'package:flutter_app/data/repositories/api_interface.dart'; import 'package:flutter_app/domain/models/card.dart'; +import 'package:flutter_app/domain/models/home.dart'; +import 'package:pretty_dio_logger/pretty_dio_logger.dart'; class ThronesRepository extends ApiInterface { - static final Dio _dio = Dio(); + static final Dio _dio = Dio() + ..interceptors.add(PrettyDioLogger( + requestHeader: true, + requestBody: true, + )); static const String _baseUrl = 'https://thronesapi.com'; - static const _imagePlaceholder = - 'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png'; - @override - Future?> loadData({String? q, OnErrorCallback? onError}) async { + Future loadData({ + OnErrorCallback? onError, + String? q, + int page = 1, + }) async { try { const String url = '$_baseUrl/api/v2/Characters'; - final Response response = await _dio.get>(url); + final Response response = await _dio.get>( + url, + ); - final List characters = (response.data as List) - .map((e) => ThronesCharacterDto.fromJson(e as Map)) + final List characters = (response.data as List) + .map((e) => ThronesCharacterDataDto.fromJson(e as Map)) .toList(); final List data = characters - .where((character) => q == null || character.fullName.toLowerCase().contains(q.toLowerCase())) + .where((character) => q == null || character.fullName!.toLowerCase().contains(q.toLowerCase())) .map((e) => e.toDomain()) .toList(); - return data; + final HomeData homeData = HomeData( + data: data, + nextPage: null, // Если API не поддерживает пагинацию, то nextPage будет null + ); + + return homeData; } on DioException catch (e) { - onError?.call(e.response?.statusMessage); + onError?.call(e.error?.toString()); return null; } } diff --git a/flutter_app/lib/data/repositories/mock_repository.dart b/flutter_app/lib/data/repositories/mock_repository.dart index 7a4e594..113e1ff 100644 --- a/flutter_app/lib/data/repositories/mock_repository.dart +++ b/flutter_app/lib/data/repositories/mock_repository.dart @@ -2,74 +2,74 @@ import 'package:flutter/material.dart'; import 'package:flutter_app/data/repositories/api_interface.dart'; import 'package:flutter_app/domain/models/card.dart'; -class MockRepository extends ApiInterface { - @override - Future?> loadData({OnErrorCallback? onError}) async { - return [ - CardData( - fullName: 'Daenerys Targaryen', - descriptionText: 'Mother of Dragons', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/daenerys.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Samwell Tarly', - descriptionText: 'Maester', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/sam.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Jon Snow', - descriptionText: 'King of the North', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/jon-snow.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Arya Stark', - descriptionText: 'No One', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/arya-stark.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Sansa Stark', - descriptionText: 'Lady of Winterfell', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/sansa-stark.jpeg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Brandon Stark', - descriptionText: 'Lord of Winterfell', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/bran-stark.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Ned Stark', - descriptionText: 'Lord of Winterfell', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/ned-stark.jpg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - CardData( - fullName: 'Robert Baratheon', - descriptionText: 'Lord of the Seven Kingdoms', - icon: Icons.favorite, - imageUrl: - 'https://thronesapi.com/assets/images/robert-baratheon.jpeg', - text: '', firstName: '', lastName: '', title: '', family: '', - ), - ]; - } -} \ No newline at end of file +// class MockRepository extends ApiInterface { +// @override +// Future?> loadData({OnErrorCallback? onError}) async { +// return [ +// CardData( +// fullName: 'Daenerys Targaryen', +// descriptionText: 'Mother of Dragons', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/daenerys.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Samwell Tarly', +// descriptionText: 'Maester', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/sam.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Jon Snow', +// descriptionText: 'King of the North', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/jon-snow.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Arya Stark', +// descriptionText: 'No One', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/arya-stark.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Sansa Stark', +// descriptionText: 'Lady of Winterfell', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/sansa-stark.jpeg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Brandon Stark', +// descriptionText: 'Lord of Winterfell', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/bran-stark.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Ned Stark', +// descriptionText: 'Lord of Winterfell', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/ned-stark.jpg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// CardData( +// fullName: 'Robert Baratheon', +// descriptionText: 'Lord of the Seven Kingdoms', +// icon: Icons.favorite, +// imageUrl: +// 'https://thronesapi.com/assets/images/robert-baratheon.jpeg', +// text: '', firstName: '', lastName: '', title: '', family: '', +// ), +// ]; +// } +// } \ No newline at end of file diff --git a/flutter_app/lib/domain/models/card.dart b/flutter_app/lib/domain/models/card.dart index 25179be..76301a3 100644 --- a/flutter_app/lib/domain/models/card.dart +++ b/flutter_app/lib/domain/models/card.dart @@ -5,11 +5,11 @@ class CardData { final String descriptionText; final IconData icon; final String? imageUrl; - final String firstName; - final String lastName; - final String fullName; - final String title; - final String family; + final String? firstName; + final String? lastName; + final String? fullName; + final String? title; + final String? family; CardData({ required this.text, diff --git a/flutter_app/lib/domain/models/home.dart b/flutter_app/lib/domain/models/home.dart new file mode 100644 index 0000000..8898182 --- /dev/null +++ b/flutter_app/lib/domain/models/home.dart @@ -0,0 +1,8 @@ +import 'card.dart'; + +class HomeData { + final List data; + final int? nextPage; + + HomeData({required this.data, this.nextPage}); +} \ No newline at end of file diff --git a/flutter_app/lib/main.dart b/flutter_app/lib/main.dart index e20300e..5643e54 100644 --- a/flutter_app/lib/main.dart +++ b/flutter_app/lib/main.dart @@ -1,5 +1,7 @@ import 'package:flutter/material.dart'; - +import 'package:flutter_app/data/repositories/got_repository.dart'; +import 'package:flutter_app/presentation/home_page/bloc/bloc.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'presentation/home_page/home_page.dart'; void main() { @@ -17,11 +19,15 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: const Color.fromARGB(255, 20, 40, 150)), useMaterial3: true, ), - darkTheme: ThemeData.dark().copyWith( - colorScheme: ColorScheme.fromSeed(seedColor: const Color.fromARGB(255, 20, 40, 150)), - ), - themeMode: ThemeMode.light, // Можно изменить на ThemeMode.light или ThemeMode.dark - home: const MyHomePage(title: '7 Kingdoms'), + home: RepositoryProvider( + lazy: true, + create: (_) => ThronesRepository(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const MyHomePage(title: '7 Kingdoms'), + ), + ) ); } } diff --git a/flutter_app/lib/presentation/details_page/details_page.dart b/flutter_app/lib/presentation/details_page/details_page.dart index d54037e..e9a4c64 100644 --- a/flutter_app/lib/presentation/details_page/details_page.dart +++ b/flutter_app/lib/presentation/details_page/details_page.dart @@ -33,7 +33,7 @@ class DetailsPage extends StatelessWidget { Padding( padding: const EdgeInsets.only(bottom: 4.0), child: Text( - data.fullName, + data.fullName ?? 'Default Name', style: Theme.of(context).textTheme.bodyLarge?.copyWith( fontSize: 27.0, fontFamily: 'Times New Roman', diff --git a/flutter_app/lib/presentation/home_page/bloc/bloc.dart b/flutter_app/lib/presentation/home_page/bloc/bloc.dart new file mode 100644 index 0000000..8245b5c --- /dev/null +++ b/flutter_app/lib/presentation/home_page/bloc/bloc.dart @@ -0,0 +1,39 @@ +import 'package:flutter_app/data/repositories/got_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 ThronesRepository 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, + )); + } +} \ No newline at end of file diff --git a/flutter_app/lib/presentation/home_page/bloc/events.dart b/flutter_app/lib/presentation/home_page/bloc/events.dart new file mode 100644 index 0000000..4cd4a6b --- /dev/null +++ b/flutter_app/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}); +} \ No newline at end of file diff --git a/flutter_app/lib/presentation/home_page/bloc/state.dart b/flutter_app/lib/presentation/home_page/bloc/state.dart new file mode 100644 index 0000000..5e56101 --- /dev/null +++ b/flutter_app/lib/presentation/home_page/bloc/state.dart @@ -0,0 +1,43 @@ +import 'package:flutter_app/domain/models/card.dart'; +import 'package:flutter_app/domain/models/home.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:copy_with_extension/copy_with_extension.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, + }); + + 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, + ); + + @override + List get props => [ + data, + isLoading, + isPaginationLoading, + error, + ]; +} diff --git a/flutter_app/lib/presentation/home_page/bloc/state.g.dart b/flutter_app/lib/presentation/home_page/bloc/state.g.dart new file mode 100644 index 0000000..114ac25 --- /dev/null +++ b/flutter_app/lib/presentation/home_page/bloc/state.g.dart @@ -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); +} diff --git a/flutter_app/lib/presentation/home_page/card.dart b/flutter_app/lib/presentation/home_page/card.dart index eba3893..44df693 100644 --- a/flutter_app/lib/presentation/home_page/card.dart +++ b/flutter_app/lib/presentation/home_page/card.dart @@ -5,7 +5,7 @@ typedef OnLikeCallback = void Function(String title, bool isLiked)?; class _Card extends StatefulWidget { final String text; final String descriptionText; - final String fullName; + final String? fullName; final IconData icon; final String? imageUrl; final OnLikeCallback onLike; @@ -70,7 +70,7 @@ class _CardState extends State<_Card> { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - widget.fullName, + widget.fullName ?? 'Default Name', style: Theme.of(context).textTheme.bodyLarge?.copyWith( fontSize: 20.0, fontFamily: 'Times New Roman', @@ -96,7 +96,7 @@ class _CardState extends State<_Card> { setState(() { isLiked = !isLiked; }); - widget.onLike?.call(widget.fullName, isLiked); + widget.onLike?.call(widget.fullName ?? 'Default Name', isLiked); }, child: AnimatedSwitcher( duration: const Duration(milliseconds: 300), diff --git a/flutter_app/lib/presentation/home_page/home_page.dart b/flutter_app/lib/presentation/home_page/home_page.dart index cb1e1ca..6e14671 100644 --- a/flutter_app/lib/presentation/home_page/home_page.dart +++ b/flutter_app/lib/presentation/home_page/home_page.dart @@ -1,7 +1,12 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_app/components/utils/debounce.dart'; import 'package:flutter_app/data/repositories/got_repository.dart'; import 'package:flutter_app/domain/models/card.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 '../details_page/details_page.dart'; part 'card.dart'; @@ -30,21 +35,35 @@ class Body extends StatefulWidget { } class _BodyState extends State { - late TextEditingController searchController; - late Future?> data; - - final repo = ThronesRepository(); + final searchController = TextEditingController(); + final scrollController = ScrollController(); @override void initState() { - data = repo.loadData(); - searchController = TextEditingController(); - data = repo.loadData(); + 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(); } @@ -59,51 +78,55 @@ class _BodyState extends State { child: CupertinoSearchTextField( controller: searchController, onChanged: (search) { - setState(() { - data = repo.loadData(q: search); - }); + Debounce.run(() => context.read().add(HomeLoadDataEvent(search: search))); }, ), ), - Expanded( - child: Center( - child: FutureBuilder?>( - future: data, - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const CircularProgressIndicator(); - } else if (snapshot.hasError) { - return Center( - child: Text('Error: ${snapshot.error}'), - ); - } else if (!snapshot.hasData || snapshot.data!.isEmpty) { - return const Center( - child: Text('No data found'), - ); - } else { - return ListView.builder( - shrinkWrap: true, - itemCount: snapshot.data!.length, - itemBuilder: (context, index) { - final cardData = snapshot.data![index]; - return _Card.fromData( - cardData, - onLike: (String title, bool isLiked) => - _showSnackBar(context, title, isLiked), - onTap: () => _navToDetails(context, cardData), - ); - }, - ); - } - }, + BlocBuilder( + builder: (context, state) => state.error != null + ? Text( + state.error ?? '', + style: Theme.of(context).textTheme.headlineSmall?.copyWith(color: Colors.red), + ) + : state.isLoading + ? const 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(), + ), ], ), ); } + Future _onRefresh() { + context.read().add(HomeLoadDataEvent(search: searchController.text)); + return Future.value(null); + } + void _navToDetails(BuildContext context, CardData data) { Navigator.push( context, diff --git a/flutter_app/pubspec.lock b/flutter_app/pubspec.lock index ee34858..66c079e 100644 --- a/flutter_app/pubspec.lock +++ b/flutter_app/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: @@ -158,6 +166,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.1" + 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: 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: diff --git a/flutter_app/pubspec.yaml b/flutter_app/pubspec.yaml index 58d2904..0f29eaf 100644 --- a/flutter_app/pubspec.yaml +++ b/flutter_app/pubspec.yaml @@ -34,6 +34,9 @@ dependencies: dio: ^5.4.2+1 pretty_dio_logger: ^1.3.1 cupertino_icons: ^1.0.8 + flutter_bloc: ^8.1.6 + equatable: ^2.0.5 + copy_with_extension_gen: ^5.0.4 dev_dependencies: flutter_test: