Home > OS >  Flutter Provider initialize default state?
Flutter Provider initialize default state?

Time:03-23

I have a Provider that I was creating with:

ChangeNotifierProvider<WeekList>(create: (context) => WeekList()

But I wanted to initialize the list with adding one week to it at the start. I was pretty stumbed until I read this Stack Overflow article: Flutter/provider- initializing a state with a constructor

But then when I tried it myself with:

    ChangeNotifierProvider<WeekList>(create: (context) => WeekList().addWeek(budget: 300.00)),

I got this error:

The return type 'void' isn't a 'WeekList', as required by the closure's context.dartreturn_of_invalid_type_from_closure

Since its a void I tried removing the type like this:

    ChangeNotifierProvider(create: (context) => WeekList().addWeek(budget: 300.00)),

But that also did not work.

My WeekList class is:

class WeekList extends ChangeNotifier {
  List<Week> listOfWeeks = [];

  void addWeek({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );
    listOfWeeks.add(newWeek);
    
  }
}

CodePudding user response:

In create you need to return a WeekList. The function addWeek has a type of void not WeekList. You can change that function to return WeekList that will then create the ChangeNotifierProvider with the listOfWeeks containing the newWeek because now the listOfWeeks will be returned.

class WeekList extends ChangeNotifier {
  List<Week> listOfWeeks = [];

  WeekList createWeekList({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );
    listOfWeeks.add(newWeek);
    return listOfWeeks; 
  }
}

An other option is to initialise the listOfWeeks with a Week and then not use addWeek in create

ChangeNotifierProvider<WeekList>(create: (context) => WeekList())

...

class WeekList extends ChangeNotifier {
  List<Week> listOfWeeks = [Week(budget: budget: 300.00)];

  void addWeek({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );
    listOfWeeks.add(newWeek);
    
  }
}

And another option if you need specify the budget amount would be to initials WeekList with a budget amount.

ChangeNotifierProvider<WeekList>(create: (context) => WeekList(budget: 300.00))

...

class WeekList extends ChangeNotifier {
  final double budget;
  const WeekList({required this.budget}){
    listOfWeeks = [Week(budget: budget: budget)]
  }
  Late final List<Week> listOfWeeks;

  void addWeek({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );
    listOfWeeks.add(newWeek);
    
  }
}

Then there is one more option i can think of and that is to use the cascade notation. https://dart.dev/guides/language/language-tour#cascade-notation Which would look like this.

 ChangeNotifierProvider<WeekList>(create: (context) => WeekList()..addWeek(budget: 300.00)),
  • Related