I am building a Flutter app with a ChangeNotifier provider. When the app is started, I make a call to the Firebase api and save the results in a Provider variable:
Map<DateTime,List> datesMap;
How can I define another variable in the same Provider, based on the first variable? for example:
List newList = datesMap[DateTime.now()]
If I try to do it I get an error:
The instance member 'params' can't be accessed in an initializer
And if I place the second variable in a Constructor, I will get an error because the first variable datesMap
is null until the Firebase api is completed.
Example code:
class ShiftsProvider with ChangeNotifier {
Map<DateTime,List> datesMap;
List newList = datesMap[DateTime.now()];
Future<void> getDatesMapfromFirebase () {
some code...
datesMap = something;
notifyListeners();
return;
}
CodePudding user response:
You can use late
like this:
Map<DateTime,List>? datesMap;
late List? newList = datesMap?[DateTime.now()];
CodePudding user response:
You can make getter
:
List get newList {
return datesMap[DateTime.now()];
}
CodePudding user response:
since like I see that datesMap
variable is related to the specific class, you can mark it with static
keyword, this will fix your problem:
class ShiftsProvider with ChangeNotifier {
static Map<DateTime,List> datesMap;
List? newList = datesMap[DateTime.now()];
Future<void> getDatesMapfromFirebase () {
some code...
datesMap = something;
notifyListeners();
return;
}
}
just note that if you want to use that static variable, you can access it like this:
ShiftsProvider.datesMap