6 вроде работает

This commit is contained in:
GokaPek 2024-10-18 23:47:45 +04:00
parent 0bd037888d
commit 6c7b2245c9
15 changed files with 411 additions and 157 deletions

3
devtools_options.yaml Normal file
View File

@ -0,0 +1,3 @@
description: This file stores settings for Dart & Flutter DevTools.
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
extensions:

View File

@ -4,13 +4,35 @@ import 'package:labs_petrushin/Presentation/home_page/bloc/state.dart';
import 'package:labs_petrushin/repositories/food_repository.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final FoodRepository repository;
final FoodRepository repo;
HomeBloc(this.repository) : super(const HomeState()) {
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
void _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) {
emit(state.copyWith(data: repository.loadData()));
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> 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,
);
if (event.nextPage != null) {
data?.data?.insertAll(0, state.data?.data ?? []);
}
emit(state.copyWith(
isLoading: false,
isPaginationLoading: false,
data: data,
error: error,
));
}
}

View File

@ -1,8 +1,10 @@
abstract class HomeEvent {
const HomeEvent();
}
class HomeLoadDataEvent extends HomeEvent {
const HomeLoadDataEvent();
final String? search;
final int? nextPage;
const HomeLoadDataEvent({this.search, this.nextPage});
}

View File

@ -1,14 +1,28 @@
import 'package:equatable/equatable.dart';
import 'package:labs_petrushin/Presentation/home_page/home_page.dart';
import 'package:copy_with_extension/copy_with_extension.dart';
import '../../../domain/models/home.dart';
part 'state.g.dart';
@CopyWith()
class HomeState extends Equatable {
final Future<List<CardData>?>? data;
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
final String? error;
const HomeState({this.data});
HomeState copyWith({Future<List<CardData>?>? data}) => HomeState(data: data ?? this.data);
const HomeState({
this.data,
this.isLoading = false,
this.isPaginationLoading = false,
this.error,
});
@override
List<Object?> get props => [data];
List<Object?> get props => [
data,
isLoading,
isPaginationLoading,
error,
];
}

View File

@ -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);
}

View File

@ -5,6 +5,7 @@ import 'package:labs_petrushin/Presentation/home_page/bloc/bloc.dart';
import 'package:labs_petrushin/Presentation/home_page/bloc/events.dart';
import 'package:labs_petrushin/Presentation/home_page/bloc/state.dart';
import '../../Presentation/detailPage.dart';
import '../../components/util/Debounce.dart';
import '../../repositories/food_repository.dart';
part '../../domain/models/card.dart';
@ -18,106 +19,128 @@ class MyHomePage extends StatefulWidget {
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: const Body(),
);
return const Scaffold(body: Body());
}
}
class Body extends StatefulWidget {
const Body({super.key});
const Body();
@override
State<Body> createState() => _BodyState();
State<Body> createState() => BodyState();
}
class _BodyState extends State<Body> {
final TextEditingController searchController = TextEditingController();
late Future<List<CardData>?> data;
final repo = FoodRepository();
class BodyState extends State<Body> {
final searchController = TextEditingController();
final scrollController = ScrollController();
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
// data = repo.loadData();
scrollController.addListener(_onNextPageListener);
super.initState();
}
void _onNextPageListener() {
if (scrollController.offset > scrollController.position.maxScrollExtent) {
final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent(
search: searchController.text,
nextPage: bloc.state.data?.nextPage,
));
}
}
}
@override
void dispose() {
searchController.dispose();
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: Padding(padding: const EdgeInsets.all(12),
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) {
setState(() {
data = repo.loadData(q: search);
});
Debounce.run(() => context.read<HomeBloc>().add(HomeLoadDataEvent(search: search)));
},
)
),
),
),
BlocBuilder<HomeBloc,HomeState>(
builder: (context, state) => FutureBuilder<List<CardData>?>(
future: state.data,
builder: (context, snapshot) => snapshot.hasData
? Expanded(
child: Center(
child: FutureBuilder<List<CardData>?>(
future: data,
builder: (context, snapshot) =>
SingleChildScrollView(
child: snapshot.hasData ? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: snapshot.data?.map((e) => MyCard.fromData(
e,
onLike: () => _showSnackBar(context),
)).toList() ?? [],
)
: const CircularProgressIndicator(),
),
BlocBuilder<HomeBloc, HomeState>(
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
? MyCard.fromData(
data,
onLike: (title, isLiked) =>
_showSnackBar(context, title, isLiked),
onTap: () => _navToDetails(context, data),
)
: const SizedBox.shrink();
},
),
),
)
: const CircularProgressIndicator(),
)
),
],
),
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),
),
],
),
);
}
void _showSnackBar(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_){
Future<void> _onRefresh() {
context.read<HomeBloc>().add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
void _navToDetails(BuildContext context, CardData data) {
Navigator.push(
context,
CupertinoPageRoute(builder: (context) => DetailPage(info: data.info, imgUrl: data.urlImage)),
);
}
void _showSnackBar(BuildContext context, String title, bool isLiked) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
'Food liked!',
'$title ${isLiked ? 'liked!' : 'disliked :('}',
style: Theme.of(context).textTheme.bodyLarge,
),
backgroundColor: Colors.red,
backgroundColor: Colors.redAccent,
duration: const Duration(seconds: 1),
));
});

View File

@ -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);
}
}

View File

@ -3,13 +3,14 @@ import 'dart:ffi';
import 'package:json_annotation/json_annotation.dart';
part 'Foods_dto.g.dart';
part 'foods_dto.g.dart';
@JsonSerializable(createToJson: false)
class FoodsDto {
final List<FoodDataDto>? foods;
final MetaDto? meta;
const FoodsDto({this.foods});
const FoodsDto({this.foods, this.meta});
factory FoodsDto.fromJson(Map<String, dynamic> json) => _$FoodsDtoFromJson(json);
@ -25,4 +26,24 @@ class FoodDataDto {
const FoodDataDto({this.fdcId, this.brandName, this.description, this.image});
factory FoodDataDto.fromJson(Map<String, dynamic> json) => _$FoodDataDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class MetaDto {
final PaginationDto? pagination;
const MetaDto({this.pagination});
factory MetaDto.fromJson(Map<String, dynamic> json) => _$MetaDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PaginationDto {
final int? current;
final int? next;
final int? last;
const PaginationDto({this.current, this.next, this.last});
factory PaginationDto.fromJson(Map<String, dynamic> json) => _$PaginationDtoFromJson(json);
}

View File

@ -0,0 +1,33 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'foods_dto.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
FoodsDto _$FoodsDtoFromJson(Map<String, dynamic> json) => FoodsDto(
foods: (json['foods'] as List<dynamic>?)
?.map((e) => FoodDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
);
FoodDataDto _$FoodDataDtoFromJson(Map<String, dynamic> json) => FoodDataDto(
fdcId: (json['fdcId'] as num?)?.toInt(),
brandName: json['brandName'] as String?,
description: json['description'] as String?,
image: json['image'] as String?,
);
MetaDto _$MetaDtoFromJson(Map<String, dynamic> json) => MetaDto(
pagination: json['pagination'] == null
? null
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
);
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) =>
PaginationDto(
current: (json['current'] as num?)?.toInt(),
next: (json['next'] as num?)?.toInt(),
last: (json['last'] as num?)?.toInt(),
);

View File

@ -2,9 +2,18 @@
import 'package:labs_petrushin/Presentation/home_page/home_page.dart';
import 'package:labs_petrushin/data/dtos/foods_dto.dart';
import '../../domain/models/home.dart';
extension CharacterDataDtoToModel on FoodDataDto {
CardData toDomain() => CardData(
text: brandName ?? "Просто хлэп",
info: description ?? "Очень кусьна",
urlImage: image);
}
extension CharactersDtoToModel on FoodsDto {
HomeData toDomain() => HomeData(
data: foods?.map((e) => e.toDomain()).toList(),
nextPage: meta?.pagination?.next,
);
}

View File

@ -1,5 +1,7 @@
part of '../../Presentation/home_page/home_page.dart';
typedef OnLikeCallback = void Function(String title, bool isLiked)?;
class CardData {
final String text;
final String info;
@ -12,15 +14,17 @@ class MyCard extends StatefulWidget {
final String text;
final String info;
final String? urlImage;
final VoidCallback? onLike;
final OnLikeCallback onLike;
final VoidCallback? onTap;
const MyCard({super.key, required this.text, required this.info, required this.urlImage, this.onLike});
const MyCard({super.key, required this.text, required this.info, required this.urlImage, this.onLike, this.onTap});
factory MyCard.fromData(CardData data, {VoidCallback? onLike}) => MyCard(
factory MyCard.fromData(CardData data, {OnLikeCallback onLike, VoidCallback? onTap}) => MyCard(
text: data.text,
info: data.info,
urlImage: data.urlImage,
onLike: onLike,
onTap: onTap,
);
@override
@ -33,71 +37,85 @@ class _MyCardState extends State<MyCard> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(info: widget.info, imgUrl: widget.urlImage),
),
);
},
child: Card(
elevation: 4.0,
margin: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Stack(
children: [
Image.network(
widget.urlImage ?? 'https://hlebzavod3.ru/images/virtuemart/product/011_IMG_9657.jpg',
fit: BoxFit.cover,
height: 150.0,
width: double.infinity,
onTap: widget.onTap,
child: Container(
margin: const EdgeInsets.all(16),
constraints: const BoxConstraints(minHeight: 140),
decoration: BoxDecoration(
color: Colors.white70,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.grey.shade200),
),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(20),
topLeft: Radius.circular(20),
),
Positioned(
top: 8.0,
right: 8.0,
child: SizedBox(
height: double.infinity,
width: 160,
child: Image.network(
widget.urlImage ?? 'https://hlebzavod3.ru/images/virtuemart/product/011_IMG_9657.jpg',
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const Placeholder(),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.text,
style: Theme.of(context).textTheme.headlineLarge,
),
Text(
widget.info,
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
),
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
right: 16.0,
bottom: 16.0,
),
child: GestureDetector(
onTap: () {
setState(() {
isLiked = !isLiked;
});
if(isLiked) widget.onLike?.call();
widget.onLike?.call(widget.text, isLiked);
},
child: Icon(
Icons.favorite,
color: isLiked ? Colors.red : Colors.blueGrey,
size: 30.0,
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: isLiked
? const Icon(
Icons.favorite,
color: Colors.redAccent,
key: ValueKey<int>(0),
)
: const Icon(
Icons.favorite_border,
key: ValueKey<int>(1),
),
),
),
),
],
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.text,
style: const TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 5.0),
Text(
widget.info,
style: const TextStyle(
fontSize: 14.0,
color: Colors.grey,
),
),
],
),
),
],
],
),
),
),
);

View File

@ -0,0 +1,9 @@
import '../../Presentation/home_page/home_page.dart';
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.nextPage});
}

View File

@ -1,6 +1,8 @@
import 'package:labs_petrushin/Presentation/home_page/home_page.dart';
import '../domain/models/home.dart';
abstract class ApiInterface {
Future<List<CardData>?> loadData();
Future<HomeData?> loadData();
}

View File

@ -6,6 +6,8 @@ import 'package:labs_petrushin/data/mappers/food_mapper.dart';
import 'package:labs_petrushin/repositories/api_interface.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../domain/models/home.dart';
class FoodRepository extends ApiInterface {
static final Dio _dio = Dio()
..interceptors.add(
@ -18,15 +20,21 @@ class FoodRepository extends ApiInterface {
static const String _baseUrl = 'https://api.nal.usda.gov';
@override
Future<List<CardData>?> loadData({String? q}) async {
Future<HomeData?> loadData({String? q, int page = 1, int pageSize = 5}) async {
try {
final String searchQuery = q ?? 'food'; // Используем 'food' как значение по умолчанию
final String url = '$_baseUrl/fdc/v1/foods/search?api_key=91xPcWwfSGljSRMuoS8IH0GP4hM9QqwwtgSzqJMw&query=$searchQuery&pageSize=10';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(url);
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(url,
queryParameters: {
'page[number]': page,
'page[size]': pageSize,
}
);
final FoodsDto dto = FoodsDto.fromJson(response.data as Map<String, dynamic>);
final List<CardData>? data = dto.foods?.map((e) => e.toDomain()).toList();
// final List<CardData>? data = dto.foods?.map((e) => e.toDomain()).toList();
final HomeData data = dto.toDomain();
return data;
} on DioException catch (e) {
// err

View File

@ -1,22 +0,0 @@
import 'package:labs_petrushin/Presentation/home_page/home_page.dart';
import 'package:labs_petrushin/repositories/api_interface.dart';
class MockRepository extends ApiInterface {
@override
Future<List<CardData>?> loadData() async {
return [
CardData(text: "Батон",
info: "Белый хлеб, испечённый в виде продолговатой булки",
urlImage: "https://hlebzavod3.ru/images/virtuemart/product/011_IMG_9657.jpg"),
CardData(text: "Багет",
info: "Длинный тонкий вид хлеба французского происхождения",
urlImage: "https://main-cdn.sbermegamarket.ru/big1/hlr-system/13/14/29/23/31/01/100027310078b0.jpg"),
CardData(text: "Круассан",
info: "Небольшое мучное кондитерское изделие, булочка в форме полумесяца из слоёного теста",
urlImage: "https://shokoladd.ru/wp-content/uploads/2019/02/Croissant_Chocolate_Plate_Two_547531_2048x1152.jpg"),
CardData(text: "Чиаба́тта",
info: "Итальянский пшеничный хлеб, выпекаемый с использованием закваски, дрожжей и оливкового масла",
urlImage: "https://avatars.mds.yandex.net/i?id=a9163f90a989a596b26b30ad39beaf47_l-10629685-images-thumbs&n=13")
];
}
}