7 лайки готовы

This commit is contained in:
GokaPek 2024-10-20 21:54:03 +04:00
parent f4cbfe7e68
commit 25e9a42eb4
13 changed files with 206 additions and 60 deletions

View File

@ -4,6 +4,7 @@
"search": "Search", "search": "Search",
"liked": "liked!", "liked": "liked!",
"disliked": "disliked :(", "disliked": "disliked :(",
"bread": "Unknown",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)" "arbEnding": "Чтобы не забыть про отсутствие запятой :)"
} }

View File

@ -4,6 +4,7 @@
"search": "Поиск", "search": "Поиск",
"liked": "Добавлено в понравившиеся :)", "liked": "Добавлено в понравившиеся :)",
"disliked": "Удалено из понравившегося :(", "disliked": "Удалено из понравившегося :(",
"bread": "Неизвестное название",
"arbEnding": "Чтобы не забыть про отсутствие запятой :)" "arbEnding": "Чтобы не забыть про отсутствие запятой :)"
} }

View File

@ -5,6 +5,9 @@ import 'package:labs_petrushin/Presentation/common/svg_objects.dart';
import 'package:labs_petrushin/Presentation/home_page/bloc/bloc.dart'; 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/events.dart';
import 'package:labs_petrushin/Presentation/home_page/bloc/state.dart'; import 'package:labs_petrushin/Presentation/home_page/bloc/state.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_bloc.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_event.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_state.dart';
import 'package:labs_petrushin/Presentation/locale_bloc/locale_bloc.dart'; import 'package:labs_petrushin/Presentation/locale_bloc/locale_bloc.dart';
import 'package:labs_petrushin/Presentation/locale_bloc/locale_events.dart'; import 'package:labs_petrushin/Presentation/locale_bloc/locale_events.dart';
import 'package:labs_petrushin/Presentation/locale_bloc/locale_state.dart'; import 'package:labs_petrushin/Presentation/locale_bloc/locale_state.dart';
@ -45,6 +48,7 @@ class BodyState extends State<Body> {
void initState() { void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent()); context.read<HomeBloc>().add(const HomeLoadDataEvent());
context.read<LikeBloc>().add(const LoadLikesEvent());
}); });
scrollController.addListener(_onNextPageListener); scrollController.addListener(_onNextPageListener);
@ -111,27 +115,31 @@ class BodyState extends State<Body> {
) )
: state.isLoading : state.isLoading
? const CircularProgressIndicator() ? const CircularProgressIndicator()
: Expanded( : BlocBuilder<LikeBloc, LikeState>(
child: RefreshIndicator( builder: (context, likeState) {
onRefresh: _onRefresh, return Expanded(
child: ListView.builder( child: RefreshIndicator(
controller: scrollController, onRefresh: _onRefresh,
padding: EdgeInsets.zero, child: ListView.builder(
itemCount: state.data?.data?.length ?? 0, controller: scrollController,
itemBuilder: (context, index) { padding: EdgeInsets.zero,
final data = state.data?.data?[index]; itemCount: state.data?.data?.length ?? 0,
return data != null itemBuilder: (context, index) {
? MyCard.fromData( final data = state.data?.data?[index];
data, return data != null
onLike: (title, isLiked) => ? MyCard.fromData(
_showSnackBar(context, title, isLiked), data,
onTap: () => _navToDetails(context, data), onLike: _onLike,
) isLiked: likeState.likedIds?.contains(data.id.toString()) == true,
: const SizedBox.shrink(); onTap: () => _navToDetails(context, data),
}, )
), : const SizedBox.shrink();
), },
), ),
),
);
}
),
), ),
BlocBuilder<HomeBloc, HomeState>( BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading builder: (context, state) => state.isPaginationLoading
@ -167,4 +175,11 @@ class BodyState extends State<Body> {
)); ));
}); });
} }
void _onLike(String? id, String title, bool isLiked) {
if (id != null) {
context.read<LikeBloc>().add(ChangeLikeEvent(id));
_showSnackBar(context, title, !isLiked);
}
}
} }

View File

@ -0,0 +1,35 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_event.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_state.dart';
import 'package:shared_preferences/shared_preferences.dart';
const String _likedPrefsKey = 'liked';
class LikeBloc extends Bloc<LikeEvent, LikeState> {
LikeBloc() : super(const LikeState(likedIds: [])) {
on<ChangeLikeEvent>(_onChangeLike);
on<LoadLikesEvent>(_onLoadLikes);
}
Future<void> _onLoadLikes(LoadLikesEvent event, Emitter<LikeState> emit) async {
final prefs = await SharedPreferences.getInstance();
final data = prefs.getStringList(_likedPrefsKey);
emit(state.copyWith(likedIds: data));
}
Future<void> _onChangeLike(ChangeLikeEvent event, Emitter<LikeState> emit) async {
final updatedList = List<String>.from(state.likedIds ?? []);
if (updatedList.contains(event.id)) {
updatedList.remove(event.id);
} else {
updatedList.add(event.id);
}
final prefs = await SharedPreferences.getInstance();
prefs.setStringList(_likedPrefsKey, updatedList);
emit(state.copyWith(likedIds: updatedList));
}
}

View File

@ -0,0 +1,13 @@
abstract class LikeEvent {
const LikeEvent();
}
class LoadLikesEvent extends LikeEvent {
const LoadLikesEvent();
}
class ChangeLikeEvent extends LikeEvent {
final String id;
const ChangeLikeEvent(this.id);
}

View File

@ -0,0 +1,14 @@
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:equatable/equatable.dart';
part 'like_state.g.dart';
@CopyWith()
class LikeState extends Equatable {
final List<String>? likedIds;
const LikeState({required this.likedIds});
@override
List<Object?> get props => [likedIds];
}

View File

@ -0,0 +1,56 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'like_state.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$LikeStateCWProxy {
LikeState likedIds(List<String>? likedIds);
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LikeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// LikeState(...).copyWith(id: 12, name: "My name")
/// ````
LikeState call({
List<String>? likedIds,
});
}
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfLikeState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfLikeState.copyWith.fieldName(...)`
class _$LikeStateCWProxyImpl implements _$LikeStateCWProxy {
const _$LikeStateCWProxyImpl(this._value);
final LikeState _value;
@override
LikeState likedIds(List<String>? likedIds) => this(likedIds: likedIds);
@override
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `LikeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// LikeState(...).copyWith(id: 12, name: "My name")
/// ````
LikeState call({
Object? likedIds = const $CopyWithPlaceholder(),
}) {
return LikeState(
likedIds: likedIds == const $CopyWithPlaceholder()
? _value.likedIds
// ignore: cast_nullable_to_non_nullable
: likedIds as List<String>?,
);
}
}
extension $LikeStateCopyWith on LikeState {
/// Returns a callable class that can be used as follows: `instanceOfLikeState.copyWith(...)` or like so:`instanceOfLikeState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$LikeStateCWProxy get copyWith => _$LikeStateCWProxyImpl(this);
}

View File

@ -2,6 +2,7 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:labs_petrushin/Presentation/home_page/bloc/bloc.dart'; import 'package:labs_petrushin/Presentation/home_page/bloc/bloc.dart';
import 'package:labs_petrushin/Presentation/like_bloc/like_bloc.dart';
import 'package:labs_petrushin/Presentation/locale_bloc/locale_bloc.dart'; import 'package:labs_petrushin/Presentation/locale_bloc/locale_bloc.dart';
import 'package:labs_petrushin/Presentation/locale_bloc/locale_state.dart'; import 'package:labs_petrushin/Presentation/locale_bloc/locale_state.dart';
import 'package:labs_petrushin/components/locale/l10n/app_locale.dart'; import 'package:labs_petrushin/components/locale/l10n/app_locale.dart';
@ -9,6 +10,8 @@ import 'package:labs_petrushin/repositories/food_repository.dart';
import 'home_page/home_page.dart'; import 'home_page/home_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'like_bloc/like_bloc.dart';
void main() { void main() {
runApp(const MyApp()); runApp(const MyApp());
} }
@ -36,11 +39,15 @@ class MyApp extends StatelessWidget {
home: RepositoryProvider<FoodRepository>( home: RepositoryProvider<FoodRepository>(
lazy: true, lazy: true,
create: (_) => FoodRepository(), create: (_) => FoodRepository(),
child: BlocProvider<HomeBloc>( child: BlocProvider<LikeBloc>(
lazy: false, lazy: false,
create: (context) => HomeBloc(context.read<FoodRepository>()), create: (context) => LikeBloc(),
child: const MyHomePage( child: BlocProvider<HomeBloc>(
title: 'Петрушин Егор Александрович', lazy: false,
create: (context) => HomeBloc(context.read<FoodRepository>()),
child: const MyHomePage(
title: 'Петрушин Егор Александрович',
),
), ),
))); )));
} }

View File

@ -113,6 +113,12 @@ abstract class AppLocale {
/// **'Удалено из понравившегося :('** /// **'Удалено из понравившегося :('**
String get disliked; String get disliked;
/// No description provided for @bread.
///
/// In ru, this message translates to:
/// **'Неизвестное название'**
String get bread;
/// No description provided for @arbEnding. /// No description provided for @arbEnding.
/// ///
/// In ru, this message translates to: /// In ru, this message translates to:

View File

@ -15,6 +15,9 @@ class AppLocaleEn extends AppLocale {
@override @override
String get disliked => 'disliked :('; String get disliked => 'disliked :(';
@override
String get bread => 'Unknown';
@override @override
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)'; String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
} }

View File

@ -15,6 +15,9 @@ class AppLocaleRu extends AppLocale {
@override @override
String get disliked => 'Удалено из понравившегося :('; String get disliked => 'Удалено из понравившегося :(';
@override
String get bread => 'Неизвестное название';
@override @override
String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)'; String get arbEnding => 'Чтобы не забыть про отсутствие запятой :)';
} }

View File

@ -5,7 +5,7 @@ import '../../domain/models/home.dart';
extension CharacterDataDtoToModel on FoodDataDto { extension CharacterDataDtoToModel on FoodDataDto {
CardData toDomain() => CardData( CardData toDomain() => CardData(
text: brandName ?? "Просто хлэп", info: description ?? "Очень кусьна", urlImage: image); text: brandName ?? "Unknown", info: description ?? "Unknown", urlImage: image, id: fdcId!);
} }
extension CharactersDtoToModel on FoodsDto { extension CharactersDtoToModel on FoodsDto {

View File

@ -1,21 +1,24 @@
part of '../../Presentation/home_page/home_page.dart'; part of '../../Presentation/home_page/home_page.dart';
typedef OnLikeCallback = void Function(String title, bool isLiked)?; typedef OnLikeCallback = void Function(String? id, String title, bool isLiked)?;
class CardData { class CardData {
final int id;
final String text; final String text;
final String info; final String info;
final String? urlImage; final String? urlImage;
CardData({required this.text, required this.info, required this.urlImage}); CardData({required this.text, required this.info, required this.urlImage, required this.id});
} }
class MyCard extends StatefulWidget { class MyCard extends StatelessWidget {
final String text; final String text;
final String info; final String info;
final String? urlImage; final String? urlImage;
final OnLikeCallback onLike; final OnLikeCallback onLike;
final VoidCallback? onTap; final VoidCallback? onTap;
final int id;
final bool isLiked;
const MyCard( const MyCard(
{super.key, {super.key,
@ -23,27 +26,24 @@ class MyCard extends StatefulWidget {
required this.info, required this.info,
required this.urlImage, required this.urlImage,
this.onLike, this.onLike,
this.onTap}); this.onTap,
required this.id, this.isLiked = false});
factory MyCard.fromData(CardData data, {OnLikeCallback onLike, VoidCallback? onTap}) => MyCard( factory MyCard.fromData(CardData data, {OnLikeCallback onLike, VoidCallback? onTap, bool isLiked = false}) => MyCard(
text: data.text, text: data.text,
info: data.info, info: data.info,
urlImage: data.urlImage, urlImage: data.urlImage,
onLike: onLike, onLike: onLike,
onTap: onTap, onTap: onTap,
isLiked: isLiked,
id: data.id.toInt()
); );
@override
State<MyCard> createState() => _MyCardState();
}
class _MyCardState extends State<MyCard> {
bool isLiked = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return GestureDetector(
onTap: widget.onTap, onTap: onTap,
child: Container( child: Container(
margin: const EdgeInsets.all(16), margin: const EdgeInsets.all(16),
constraints: const BoxConstraints(minHeight: 140), constraints: const BoxConstraints(minHeight: 140),
@ -65,7 +65,7 @@ class _MyCardState extends State<MyCard> {
height: double.infinity, height: double.infinity,
width: 160, width: 160,
child: Image.network( child: Image.network(
widget.urlImage ?? urlImage ??
'https://hlebzavod3.ru/images/virtuemart/product/011_IMG_9657.jpg', 'https://hlebzavod3.ru/images/virtuemart/product/011_IMG_9657.jpg',
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const Placeholder(), errorBuilder: (_, __, ___) => const Placeholder(),
@ -79,11 +79,11 @@ class _MyCardState extends State<MyCard> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
widget.text, text,
style: Theme.of(context).textTheme.headlineLarge, style: Theme.of(context).textTheme.headlineLarge,
), ),
Text( Text(
widget.info, info,
style: Theme.of(context).textTheme.bodyLarge, style: Theme.of(context).textTheme.bodyLarge,
), ),
], ],
@ -93,30 +93,22 @@ class _MyCardState extends State<MyCard> {
Align( Align(
alignment: Alignment.bottomRight, alignment: Alignment.bottomRight,
child: Padding( child: Padding(
padding: const EdgeInsets.only( padding:
left: 8.0, const EdgeInsets.only(left: 8, right: 16, bottom: 16),
right: 16.0,
bottom: 16.0,
),
child: GestureDetector( child: GestureDetector(
onTap: () { onTap: () => onLike?.call(id.toString(), text, isLiked),
setState(() {
isLiked = !isLiked;
});
widget.onLike?.call(widget.text, isLiked);
},
child: AnimatedSwitcher( child: AnimatedSwitcher(
duration: const Duration(milliseconds: 300), duration: const Duration(milliseconds: 200),
child: isLiked child: isLiked
? const Icon( ? const Icon(
Icons.favorite, Icons.favorite,
color: Colors.redAccent, color: Colors.redAccent,
key: ValueKey<int>(0), key: ValueKey<int>(0),
) )
: const Icon( : const Icon(
Icons.favorite_border, Icons.favorite_border,
key: ValueKey<int>(1), key: ValueKey<int>(1),
), ),
), ),
), ),
), ),