рабочая 5 лаба.2

This commit is contained in:
salih 2024-12-11 11:50:50 +04:00
parent adeb517d4e
commit a97454f8bb
3 changed files with 100 additions and 64 deletions

View File

@ -0,0 +1,19 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'food_dto.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
FoodsDto _$FoodsDtoFromJson(Map<String, dynamic> json) => FoodsDto(
meals: (json['meals'] as List<dynamic>?)
?.map((e) => FoodDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
);
FoodDataDto _$FoodDataDtoFromJson(Map<String, dynamic> json) => FoodDataDto(
idMeal: json['idMeal'] as String?,
strMeal: json['strMeal'] as String?,
strMealThumb: json['strMealThumb'] as String?,
);

View File

@ -12,19 +12,22 @@ class FoodRepository extends ApiInterface{
requestBody: true, requestBody: true,
)); ));
static const String _baseUrl = 'https://www.themealdb.com/api/json'; static const String _baseUrl = 'https://www.themealdb.com/api/json/v1/1';
@override @override
Future<List<MarketData>?> loadData() async { Future<List<MarketData>?> loadData({String? q}) async {
try { try {
const String url = '$_baseUrl/v1/1/filter.php?i=chicken_breast'; final String url = q != null ? '$_baseUrl/search.php' : '$_baseUrl/filter.php?i=chicken_breast';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(url); final Response<dynamic> response = await _dio.get(
url,
queryParameters: q != null ? {'s': q} : null,
);
final FoodsDto dto = FoodsDto.fromJson(response.data as Map<String, dynamic>); final FoodsDto dto = FoodsDto.fromJson(response.data as Map<String, dynamic>);
final List<MarketData>? items = dto.meals?.map((e) => e.toDomain()).toList(); final List<MarketData>? items = dto.meals?.map((e) => e.toDomain()).toList();
return items; return items;
} on DioException catch(e){ } on DioException catch (e) {
print('Ошибка запроса: $e');
return null; return null;
} }
} }

View File

@ -18,66 +18,80 @@ class MyHomePage extends StatefulWidget {
class _MyHomePageState extends State<MyHomePage> { class _MyHomePageState extends State<MyHomePage> {
final Color _color = const Color(0xFFFFA400); final Color _color = const Color(0xFFFFA400);
final searchController = TextEditingController();
late Future<List<MarketData>?> data;
final repo = FoodRepository();
@override
void initState() {
data = repo.loadData();
super.initState();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Padding(
appBar: AppBar( padding: EdgeInsets.only(top: MediaQuery
backgroundColor: _color, .of(context)
title: Text(widget.title), .padding
), .top),
body: const Body(), child: Column(children: [
); Padding(
} padding: const EdgeInsets.all(12),
} child: CupertinoSearchTextField(
controller: searchController,
class Body extends StatelessWidget { style: const TextStyle(color: Colors.white),
const Body({super.key}); onSubmitted: (search) {
setState(() {
@override data = repo.loadData(q: search);
Widget build(BuildContext context) { });
final marketData = FoodRepository().loadData(); },
),
return Center( ),
child: FutureBuilder<List<MarketData>?>( Expanded(
future: marketData, child: Center(
builder: (context, snapshot) => SingleChildScrollView( child: FutureBuilder<List<MarketData>?>(
child: snapshot.hasData future: data,
? Column( builder: (context, snapshot) =>
mainAxisAlignment: MainAxisAlignment.center, SingleChildScrollView(
children: snapshot.data?.map((data) { child: snapshot.hasData
return _MarketCard.fromData( ? Column(
data, mainAxisAlignment: MainAxisAlignment.center,
onLike: (String title, bool isLiked) => children: snapshot.data?.map((data) {
_showSnackBar(context, title, isLiked), return _MarketCard.fromData(
onTap: () => _navToDetails(context, data), data,
); onLike: (String title, bool isLiked) =>
}).toList() ?? _showSnackBar(context, title, isLiked),
[], onTap: () => _navToDetails(context, data),
) );
: const CircularProgressIndicator(), }).toList() ??
), [],
), )
); : const CircularProgressIndicator(),
} ),
),
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),
));
});
}
void _navToDetails(BuildContext context, MarketData data) {
Navigator.push(
context,
CupertinoPageRoute(builder: (context) => DetailsPage(data)),
);
} }
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),
));
});
}
void _navToDetails(BuildContext context, MarketData data) {
Navigator.push(
context,
CupertinoPageRoute(builder: (context) => DetailsPage(data)),
);
}
} }