When we want to use provider to share data, as we know, we need to use StateNotifier and StateNotifierProvider<...>. In provider, you need to set variable, which returns StateNotifier class. Your logic is coming in this class and you need to manipulate state variable.
If you think your life is hard, it's the time to grow as human so don't think badly, cus it's kinda good thing. Whatever happens to you, it just gives you lesson. However, this lesson only comes to you when you make action because there is no challenge without obstacle, right? So I believe in what I'm doing and I promise to myself whatever happens to me, I'll try my best to get over it.
In flutter, if we use value via multiple class using constructor, it will be better to use provider. This provider is a little bit tricky but it makes sense to me. I'll share necessary function here.
1.Create class using StateNotifier. In generic, define what data you want to provide, this time >\
2.The constructor is class_name() : super([]); The parenthesis of super is [] because shared data is List type.\
3.The shared data is including in state, so if you want to manipulate shared data, use state in function. For example, state = state.where((m) => m.id != meal.id).toList(); \
4.Finally, you need to define provider which returns Notifier \
The whole code looks like below: \
\
import 'package:flutter_riverpod/flutter_riverpod.dart'; \
import 'package:meals/models/meal.dart';
\
\
class FavoriteMealsNotifier extends StateNotifier> {
FavoriteMealsNotifier() : super([]);
bool toggleMealFavoriteStatus(Meal meal) {
final mealIsFavorite = state.contains(meal);
if (mealIsFavorite) {
state = state.where((m) => m.id != meal.id).toList();
return false;
} else {
state = [...state, meal];
return true;
}
}
}
\
final favoriteMealsProvider =
StateNotifierProvider>((ref) { \
return FavoriteMealsNotifier(); \
});
This is the provider, you need to set other classes to ConsumerWidget if stateless and ConsumerStatefulWidget if stateful.
To show new page when user tap, use Navigator.of(context).push(MaterialPageRoute(builder: builder)). In this builder, it is required to provide (ctx) = {} function and inside of this blacket, you need to add what you want to show on the page.
Whatever you felt and saw before should be beautiful in your memory, so sometimes you want to go back and feel that moment again, but remember there is nothing completely same as before. If you don't wanna get hurt, please leave your memory beautiful, don't do anything for your memory or you will overwrite it with bad experience.