diff --git a/lib/data/dtos/house_dto_json.dart b/lib/data/dtos/house_dto_json.dart deleted file mode 100644 index d151646..0000000 --- a/lib/data/dtos/house_dto_json.dart +++ /dev/null @@ -1,33 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'houses_dto.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - - -HousesDto _$HousesDtoFromJson(Map json) => - HousesDto( - data: (json['data'] as List?) - ?.map((e) => HouseDataDto.fromJson(e as Map)) - .toList(), - ); - -HouseDataDto _$HouseDataDtoFromJson(Map json) => - HouseDataDto( - json['id'] as String?, - json['attributes'] == null - ? null - : HouseAttributesDataDto.fromJson( - json['attributes'] as Map), - ); - -HouseAttributesDataDto _$HouseAttributesDataDtoFromJson( - Map json) => - HouseAttributesDataDto( - json['name'] as String?, - json['location'] as String?, - json['image'] as String?, - json['description'] as String?, - ); diff --git a/lib/data/dtos/houses_dto.dart b/lib/data/dtos/houses_dto.dart index 505260f..8584634 100644 --- a/lib/data/dtos/houses_dto.dart +++ b/lib/data/dtos/houses_dto.dart @@ -1,17 +1,41 @@ import 'package:json_annotation/json_annotation.dart'; // dart run build_runner build --delete-conflicting-outputs +// flutter pub run build_runner build --delete-conflicting-outputs -part 'house_dto_json.dart'; - +part 'houses_dto.g.dart'; @JsonSerializable(createToJson: false) class HousesDto { final List? data; + final MetaDto? meta; - const HousesDto({this.data}); + const HousesDto({this.data, this.meta}); - factory HousesDto.fromJson(Map json) => _$HousesDtoFromJson(json); + factory HousesDto.fromJson(Map json) => + _$HousesDtoFromJson(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) @@ -21,7 +45,8 @@ class HouseDataDto { const HouseDataDto(this.id, this.attributes); - factory HouseDataDto.fromJson(Map json) => _$HouseDataDtoFromJson(json); + factory HouseDataDto.fromJson(Map json) => + _$HouseDataDtoFromJson(json); } @JsonSerializable(createToJson: false) @@ -31,7 +56,9 @@ class HouseAttributesDataDto { final String? image; final String? description; - HouseAttributesDataDto(this.name, this.location, this.image, this.description); + HouseAttributesDataDto( + this.name, this.location, this.image, this.description); - factory HouseAttributesDataDto.fromJson(Map json) => _$HouseAttributesDataDtoFromJson(json); + factory HouseAttributesDataDto.fromJson(Map json) => + _$HouseAttributesDataDtoFromJson(json); } diff --git a/lib/data/mapper/house_mapper.dart b/lib/data/mapper/house_mapper.dart index 72c563e..8b2b4df 100644 --- a/lib/data/mapper/house_mapper.dart +++ b/lib/data/mapper/house_mapper.dart @@ -1,4 +1,5 @@ import '../dtos/houses_dto.dart'; +import 'package:pmd/models/home_data.dart'; import 'package:pmd/models/card_data.dart'; extension HouseDataDtoToModel on HouseDataDto { @@ -8,4 +9,10 @@ extension HouseDataDtoToModel on HouseDataDto { image: attributes?.image ?? "https://upload.wikimedia.org/wikipedia/commons/a/a2/Person_Image_Placeholder.png", description: attributes?.description ?? "UNKNOWN" ); +} + +extension HousesDtoToModel on HousesDto { + HomeData toDomain() => HomeData( + data: data?.map((e) => e.toDomain()).toList(), + nextPage: meta?.pagination?.next); } \ No newline at end of file diff --git a/lib/data/repositories/api_interface.dart b/lib/data/repositories/api_interface.dart new file mode 100644 index 0000000..cd3cdbd --- /dev/null +++ b/lib/data/repositories/api_interface.dart @@ -0,0 +1,7 @@ +import 'package:pmd/models/home_data.dart'; + +typedef OnErrorCallback = void Function(String? error); + +abstract class ApiInterface { + Future loadData ({OnErrorCallback? onError}); +} \ No newline at end of file diff --git a/lib/data/repositories/mock_repository.dart b/lib/data/repositories/mock_repository.dart new file mode 100644 index 0000000..56c51c6 --- /dev/null +++ b/lib/data/repositories/mock_repository.dart @@ -0,0 +1,78 @@ +import 'package:pmd/models/card_data.dart'; +import 'package:pmd/data/repositories/api_interface.dart'; +import 'package:pmd/models/home_data.dart'; + +class MockRepository extends ApiInterface { + // Список всех данных + final List allData = [ + const CardData( + name: "house 0", + image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", + location: "Moscow", + description: "description null"), + const CardData( + name: "house 1", + image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", + location: "Samara", + description: "null"), + const CardData( + name: "house 2", + image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", + location: "Moscow", + description: "house good, very good"), + const CardData( + name: "house 3", + image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", + location: "Kazan", + description: "house good"), + const CardData( + name: "house 4", + image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", + location: "Moscow", + description: "Moscow city") + ]; + + @override + Future loadData({ + String? q, // Поисковый запрос + int page = 1, // Страница по умолчанию + int pageSize = 2, // Количество элементов на странице + List? currentData, // Текущие данные для динамического обновления + OnErrorCallback? onError, +}) async { + try { + // Симуляция задержки сети для динамического обновления + await Future.delayed(const Duration(seconds: 1)); + + // Фильтрация данных по запросу, если он задан + List filteredData = allData + .where((card) => q == null || card.name.toLowerCase().contains(q.toLowerCase())) + .toList(); + + // Определяем начало и конец диапазона для пагинации + final int startIndex = (page - 1) * pageSize; + final int endIndex = startIndex + pageSize; + + // Убедитесь, что индекс не выходит за пределы списка + if (startIndex >= filteredData.length) { + return HomeData(data: currentData ?? []); // Возвращаем текущие данные, если больше нет данных + } + + // Извлекаем нужную страницу данных + List paginatedData = filteredData.sublist( + startIndex, + endIndex > filteredData.length ? filteredData.length : endIndex, + ); + + // Добавляем новые данные к текущим + if (currentData != null) { + paginatedData = [...currentData, ...paginatedData]; + } + + return HomeData(data: paginatedData); + } catch (e) { + if (onError != null) onError(e.toString()); + return null; + } + } +} \ No newline at end of file diff --git a/lib/repositories/potter_repository.dart b/lib/data/repositories/potter_repository.dart similarity index 53% rename from lib/repositories/potter_repository.dart rename to lib/data/repositories/potter_repository.dart index dd932ed..7180d8a 100644 --- a/lib/repositories/potter_repository.dart +++ b/lib/data/repositories/potter_repository.dart @@ -3,37 +3,44 @@ import 'dart:developer'; import 'package:dio/dio.dart'; import 'package:pmd/data/mapper/house_mapper.dart'; import 'package:pmd/data/dtos/houses_dto.dart'; -import 'package:pmd/models/card_data.dart'; -import 'package:pmd/repositories/api_interface.dart'; +import 'package:pmd/models/home_data.dart'; +import 'package:pmd/data/repositories/api_interface.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart'; - class PotterRepository extends ApiInterface { static final Dio _dio = Dio( - BaseOptions(connectTimeout: Duration(seconds: 10))) + BaseOptions(connectTimeout: const Duration(seconds: 10))) ..interceptors.add( PrettyDioLogger(request: true, requestHeader: true, requestBody: true)); - static const String _baseUrl = "https://api.potterdb.com/v1"; // https://api.realtor.com/v1 + static const String _baseUrl = + "https://api.potterdb.com/v1"; // https://api.realtor.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 HousesDto dto = HousesDto.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/home_page/bloc/bloc.dart b/lib/home_page/bloc/bloc.dart new file mode 100644 index 0000000..8458427 --- /dev/null +++ b/lib/home_page/bloc/bloc.dart @@ -0,0 +1,39 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:pmd/data/repositories/mock_repository.dart'; +import 'package:pmd/data/repositories/potter_repository.dart'; +import 'package:pmd/home_page/bloc/events.dart'; +import 'package:pmd/home_page/bloc/state.dart'; + +class HomeBloc extends Bloc { + final PotterRepository repository; + + // final MockRepository repository; + + HomeBloc(this.repository) : 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 repository.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/home_page/bloc/events.dart b/lib/home_page/bloc/events.dart new file mode 100644 index 0000000..025c2b0 --- /dev/null +++ b/lib/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/lib/home_page/bloc/state.dart b/lib/home_page/bloc/state.dart new file mode 100644 index 0000000..74b0777 --- /dev/null +++ b/lib/home_page/bloc/state.dart @@ -0,0 +1,31 @@ +import 'package:equatable/equatable.dart'; +import 'package:pmd/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); + + // Поля, по которым Equtable сравнивает состояния + @override + List get props => [data, isLoading, isPaginationLoading, error]; +} diff --git a/lib/home_page/card.dart b/lib/home_page/card.dart index 6b79065..0cf13f9 100644 --- a/lib/home_page/card.dart +++ b/lib/home_page/card.dart @@ -14,8 +14,7 @@ class _Card extends StatefulWidget { const _Card( {required this.name, required this.location, required this.image, required this.description, required this.onLike, required this.onTap}); - factory _Card.fromData(CardData data, OnLikeFunction? onLike, - VoidCallback? onTap) => + factory _Card.fromData(CardData data, {OnLikeFunction? onLike, VoidCallback? onTap}) => _Card( name: data.name, location: data.location, diff --git a/lib/home_page/home_page.dart b/lib/home_page/home_page.dart index 167894c..6ac66d0 100644 --- a/lib/home_page/home_page.dart +++ b/lib/home_page/home_page.dart @@ -1,11 +1,16 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:pmd/utils/debounce.dart'; +import 'package:pmd/home_page/bloc/bloc.dart'; +import 'package:pmd/home_page/bloc/events.dart'; +import 'package:pmd/home_page/bloc/state.dart'; import 'package:pmd/models/card_data.dart'; import 'package:pmd/details_page/details_page.dart'; -import 'package:pmd/repositories/api_interface.dart'; -import 'package:pmd/repositories/mock_repository.dart'; +import 'package:pmd/data/repositories/api_interface.dart'; -import '../repositories/potter_repository.dart'; +import 'package:pmd/data/repositories/mock_repository.dart'; +import '../data/repositories/potter_repository.dart'; part 'card.dart'; @@ -20,14 +25,49 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { final TextEditingController _searchController = TextEditingController(); - // final ApiInterface repository = PotterRepository(); - final ApiInterface repository = MockRepository(); - late Future?> _data; + final _scrollController = ScrollController(); @override void initState() { + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().add(const HomeLoadDataEvent()); + }); + + _scrollController.addListener(_onNextPageListener); super.initState(); - _data = repository.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) { @@ -54,51 +94,62 @@ class _MyHomePageState extends State { 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 = repository.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, bottom: 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.symmetric( + vertical: 20, horizontal: 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/main.dart b/lib/main.dart index 474a8fd..9c3c7fc 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,4 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:pmd/data/repositories/mock_repository.dart'; +import 'package:pmd/data/repositories/potter_repository.dart'; +import 'package:pmd/home_page/bloc/bloc.dart'; import 'package:pmd/home_page/home_page.dart'; void main() { @@ -17,7 +21,15 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), - home: const MyHomePage(title: 'Laboratory 5: API and Repositories.... '), + home: RepositoryProvider( + lazy: true, + create: (_) => PotterRepository(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const MyHomePage(title: 'Laboratory 6: Architecture (Debounce and Bloc)'), + ), + ), ); } } diff --git a/lib/models/home_data.dart b/lib/models/home_data.dart new file mode 100644 index 0000000..76d9a41 --- /dev/null +++ b/lib/models/home_data.dart @@ -0,0 +1,8 @@ +import 'package:pmd/models/card_data.dart'; + +class HomeData { + final List? data; + final int? nextPage; + + HomeData({this.data, this.nextPage}); +} \ No newline at end of file diff --git a/lib/repositories/api_interface.dart b/lib/repositories/api_interface.dart deleted file mode 100644 index 2c96211..0000000 --- a/lib/repositories/api_interface.dart +++ /dev/null @@ -1,5 +0,0 @@ -import 'package:pmd/models/card_data.dart'; - -abstract class ApiInterface { - Future?> loadData (String? q); -} \ No newline at end of file diff --git a/lib/repositories/mock_repository.dart b/lib/repositories/mock_repository.dart deleted file mode 100644 index 57298e7..0000000 --- a/lib/repositories/mock_repository.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'package:pmd/models/card_data.dart'; -import 'package:pmd/repositories/api_interface.dart'; - -class MockRepository extends ApiInterface { - @override - Future> loadData(String? q) async { - return [ - CardData( - name: "house 0", - image: - "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", - location: "Moscow", - description: "description null"), - CardData( - name: "house 1", - image: - "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", - location: "Samara", - description: "null"), - CardData( - name: "house 2", - image: - "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", - location: "Moscow", - description: "house good, very good"), - CardData( - name: "house 3", - image: - "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", - location: "Kazan", - description: "house good"), - CardData( - name: "house 4", - image: - "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg", - location: "Moscow", - description: "Moscow city") - ]; - } -} \ No newline at end of file diff --git a/lib/utils/debounce.dart b/lib/utils/debounce.dart new file mode 100644 index 0000000..8e44e39 --- /dev/null +++ b/lib/utils/debounce.dart @@ -0,0 +1,23 @@ +import 'dart:async'; +import 'dart:ui'; + +class Debounce { + // Фабричный конструктор, возвращающий экзепляр класса Debounce. Паттерн Singleton + factory Debounce() => _instance; + + // Приватный конструктор (Не даёт создание класса извне) + Debounce._(); + + // Статический экземпляр класса + static final Debounce _instance = Debounce._(); + + static Timer? _timer; + + // Статический метод, где action функция, совершающая действие, а delay совершает задержку) + static void run( + {required VoidCallback action, + Duration delay = const Duration(milliseconds: 500)}) { + _timer?.cancel(); + _timer = Timer(delay, action); + } +} diff --git a/pubspec.lock b/pubspec.lock index cb2934a..85cd7f9 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: diff --git a/pubspec.yaml b/pubspec.yaml index a39488c..2f4560c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -43,6 +43,10 @@ dependencies: dio: ^5.4.2+1 pretty_dio_logger: ^1.3.1 + # Bloc (business logical component) + flutter_bloc: ^8.1.5 + equatable: ^2.0.5 + dev_dependencies: flutter_test: sdk: flutter