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 <list
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<List
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<FavoriteMealsNotifier, List
return FavoriteMealsNotifier();
});
This is the provider, you need to set other classes to ConsumerWidget if stateless and ConsumerStatefulWidget if stateful.