diff --git a/lib/components/utils/debounce.dart b/lib/components/utils/debounce.dart new file mode 100644 index 0000000..24e1c89 --- /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); + } +} \ No newline at end of file diff --git a/lib/data/repository/api_interface.dart b/lib/data/repository/api_interface.dart index f914192..d215334 100644 --- a/lib/data/repository/api_interface.dart +++ b/lib/data/repository/api_interface.dart @@ -1,5 +1,7 @@ import 'package:pmu/domain/models/card.dart'; +typedef OnErrorCallback = void Function(String? error); + abstract class ApiInterface{ Future?> loadData(); } \ No newline at end of file diff --git a/lib/data/repository/food_repository.dart b/lib/data/repository/food_repository.dart index da64963..21e89fe 100644 --- a/lib/data/repository/food_repository.dart +++ b/lib/data/repository/food_repository.dart @@ -14,7 +14,7 @@ class FoodRepository extends ApiInterface{ static const String _baseUrl = 'https://www.themealdb.com/api/json/v1/1'; @override - Future?> loadData({String? q}) async { + Future?> loadData({OnErrorCallback? onError, String? q}) async { try { final String url = q != null ? '$_baseUrl/search.php' : '$_baseUrl/filter.php?i=chicken_breast'; @@ -27,7 +27,7 @@ class FoodRepository extends ApiInterface{ final List? items = dto.meals?.map((e) => e.toDomain()).toList(); return items; } on DioException catch (e) { - print('Ошибка запроса: $e'); + onError?.call(e.error?.toString()); return null; } } diff --git a/lib/main.dart b/lib/main.dart index 47f6f32..b5fd1bd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,4 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:pmu/data/repository/food_repository.dart'; +import 'package:pmu/presentation/home_page/bloc/bloc.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pmu/presentation/home_page/home_page.dart'; void main() { @@ -16,7 +19,15 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: Color(0xFFFFA400)), useMaterial3: true, ), - home: const MyHomePage(title: 'Магизин у дома'), + home: RepositoryProvider( + lazy: true, + create: (_) => FoodRepository(), + child: BlocProvider( + lazy: false, + create: (context) => HomeBloc(context.read()), + child: const MyHomePage(title: "Food cort"), + ), + ) ); } } diff --git a/lib/presentation/home_page/bloc/bloc.dart b/lib/presentation/home_page/bloc/bloc.dart new file mode 100644 index 0000000..ffe1e8a --- /dev/null +++ b/lib/presentation/home_page/bloc/bloc.dart @@ -0,0 +1,29 @@ +import 'package:pmu/data/repository/food_repository.dart'; +import 'package:pmu/presentation/home_page/bloc/events.dart'; +import 'package:pmu/presentation/home_page/bloc/state.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class HomeBloc extends Bloc { + final FoodRepository repo; + + HomeBloc(this.repo) : super(const HomeState()) { + on(_onLoadData); + } + + void _onLoadData(HomeLoadDataEvent event, Emitter emit) async { + emit(state.copyWith(isLoading: true)); + + String? error; + + final data = await repo.loadData( + q: event.search, + onError: (e) => error = e, + ); + + emit(state.copyWith( + isLoading: 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..1e0b10c --- /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; + + const HomeLoadDataEvent({this.search}); +} \ 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..4b9795d --- /dev/null +++ b/lib/presentation/home_page/bloc/state.dart @@ -0,0 +1,33 @@ +import 'package:equatable/equatable.dart'; +import 'package:pmu/domain/models/card.dart'; + + +class HomeState extends Equatable { + final List? data; + final bool isLoading; + final String? error; + + const HomeState({ + this.data, + this.isLoading = false, + this.error, + }); + + HomeState copyWith({ + List? data, + bool? isLoading, + String? error, + }) => + HomeState( + data: data ?? this.data, + isLoading: isLoading ?? this.isLoading, + error: error ?? this.error, + ); + + @override + List get props => [ + data, + isLoading, + error, + ]; +} diff --git a/lib/presentation/home_page/home_page.dart b/lib/presentation/home_page/home_page.dart index 4d183b2..c44573e 100644 --- a/lib/presentation/home_page/home_page.dart +++ b/lib/presentation/home_page/home_page.dart @@ -1,9 +1,15 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:pmu/components/utils/debounce.dart'; import 'package:pmu/data/repository/food_repository.dart'; import 'package:pmu/data/repository/mock_repository.dart'; import 'package:pmu/domain/models/card.dart'; +import 'package:pmu/main.dart'; import 'package:pmu/presentation/details_page/details_page.dart'; +import 'package:pmu/presentation/home_page/bloc/bloc.dart'; +import 'package:pmu/presentation/home_page/bloc/events.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:pmu/presentation/home_page/bloc/state.dart'; part 'card.dart'; @@ -21,12 +27,29 @@ class _MyHomePageState extends State { final searchController = TextEditingController(); late Future?> data; final repo = FoodRepository(); + @override void initState() { - data = repo.loadData(); + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().add(const HomeLoadDataEvent()); + }); + super.initState(); } + @override + void dispose() { + searchController.dispose(); + super.dispose(); + } + + Future _onRefresh() { + context + .read() + .add(HomeLoadDataEvent(search: searchController.text)); + return Future.value(null); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -38,62 +61,68 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(12), child: CupertinoSearchTextField( controller: searchController, - style: const TextStyle(color: Colors.white), - onSubmitted: (search) { - setState(() { - data = repo.loadData(q: search); - }); + onChanged: (search) { + Debounce.run(() => context + .read() + .add(HomeLoadDataEvent(search: 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 _MarketCard.fromData( - data, - onLike: (String title, bool isLiked) => - _showSnackBar(context, title, isLiked), - onTap: () => _navToDetails(context, data), - ); - }).toList() ?? - [], - ) - : const CircularProgressIndicator(), - ), - ), - ), - ), + 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( + padding: EdgeInsets.zero, + itemCount: state.data?.length ?? 0, + itemBuilder: (context, index) { + final data = state.data?[index]; + return data != null + ? _MarketCard.fromData( + data, + onLike: (title, isLiked) => + _showSnackBar( + context, title, isLiked), + onTap: () => + _navToDetails(context, data), + ) + : const SizedBox.shrink(); + }, + ), + ))), ], ), ), ); } - - void _showSnackBar(BuildContext context, String title, bool isLiked) { - WidgetsBinding.instance.addPostFrameCallback((_) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( - content: Text( - 'Товар $title ${isLiked ? 'добавлен в избранное' : 'удален из избранного'}', - style: Theme.of(context).textTheme.bodyLarge, - ), - backgroundColor: Colors.orangeAccent, - duration: const Duration(seconds: 1), - )); - }); - } + WidgetsBinding.instance.addPostFrameCallback((_) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text( + 'Товар $title ${isLiked ? 'добавлен в избранное' : 'удален из избранного'}', + style: Theme.of(context).textTheme.bodyLarge, + ), + backgroundColor: Colors.orangeAccent, + duration: const Duration(seconds: 1), + )); + }); + } - void _navToDetails(BuildContext context, MarketData data) { - Navigator.push( - context, - CupertinoPageRoute(builder: (context) => DetailsPage(data)), - ); - } + void _navToDetails(BuildContext context, MarketData data) { + Navigator.push( + context, + CupertinoPageRoute(builder: (context) => DetailsPage(data)), + ); + } } diff --git a/pubspec.lock b/pubspec.lock index 5f86281..5b4fc40 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: @@ -158,6 +166,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + 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 dev" + 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 dev" + description: + name: equatable + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.dev" + source: hosted + version: "2.0.7" fake_async: dependency: transitive description: @@ -227,6 +259,14 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_bloc: + dependency: "direct dev" + 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/pubspec.yaml b/pubspec.yaml index 74edf93..51030a5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -47,6 +47,10 @@ dev_dependencies: build_runner: ^2.4.9 json_serializable: ^6.7.1 + equatable: ^2.0.5 + flutter_bloc: ^8.1.5 + copy_with_extension_gen: ^5.0.4 + # The "flutter_lints" package below contains a set of recommended lints to # encourage good coding practices. The lint set provided by the package is # activated in the `analysis_options.yaml` file located at the root of your