flutterdartinitializationnon-nullable

Resolving 'Non-nullable instance field must be initialized' Error in Dart Flutter


I'm working with Dart in a Flutter application and encountered an error related to initializing non-nullable instance fields. The error suggests using an initializer expression, adding a field initializer in the constructor, or marking the field as 'late'. Despite following these suggestions, I'm still facing issues.

Here's the relevant portion of my code:

class _DayViewState extends State<DayView> {
  List<charts.Series<TaskData, int>> listOfTasks;
  Map<int, String> days = new Map();
  int day; // Error points to this line

  _DayViewState(List<charts.Series<TaskData, int>> list, int day) {
    this.listOfTasks = list;
    this.day = day;
  }

  setIt() {
    setState() {
      build(context);
    }
  }

Despite initializing day in the constructor, the error persists. Can someone explain what I'm missing or suggest a solution?

Thank you in advance for any help.


Solution

  • You can include late keyword as error message suggested.

    class _DayViewState extends State<DayView> {
      late List<charts.Series<TaskData, int>> listOfTasks;
      Map<int, String> days = new Map();
      late int day;
    

    Can also be nullable or you can just do

    _DayViewState(this.listOfTasks, this.day);
    

    Find more about null-safety