If your class is just a service/repository that won't be involved in updating state and rebuilding widgets, then it's wise to use a Provider
for graceful dependency injection.
If your variable myVariable
will be some state, based on which your widgets should be rebuilt, then
- in the simplest case use
StateProvider
| FutureProvider
- in case your state needs complex/several methods to change it, then use
(Async)NotifierProvider
In the latter case, your code will look something like this:
final variableProvider = NotifierProvider<TodosNotifier, List<Map<String, dynamic>>?>(VariableNotifier.new);
class VariableNotifier extends Notifier<List<Map<String, dynamic>>?> {
@override
List<Map<String, dynamic>>? build() {
return null;
}
Future<void> toDoWithMyVar() async {
state = ...;
}
You should probably also look into packages like freezed
, which allow you to conveniently manage immutable objects. The fact is that for these providers to work correctly, your state must be immutable with a correctly redefined hashcode|==