1

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;
}

3 Answers 3

1

You can make getter:

List get newList {
   return datesMap[DateTime.now()];
 }
Sign up to request clarification or add additional context in comments.

Comments

1

You can use late like this:

Map<DateTime,List>? datesMap;

late List? newList = datesMap?[DateTime.now()];

1 Comment

what version of flutter you are use?I think null safety is not active in your project right? @LateBoy
1

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

5 Comments

What difference the keyword "static" makes?
I will explain by example, when we have a class that contains some variables, when we create multiple objects of that class, each one of theme will have a those variables belongs to just that instance object.
with the static keyword, you make a variable belonging to the original class, and what the number of instances you made of that class, the static variable only refers to the original class and it doesn't only by an instance, but it belongs to all of them.
did you solve the issue ?
Thank you, I found your answer useful, but for this specific use case I found the getter method more straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.