Ad

Dart Says "non-nullable Variable Must Be Initialized Before Use", Even After Assigning With If, Else Block

- 1 answer

Trying to do this. Would be neat if I could avoid implementing the full code in both condition.

  String dateToday;
  //if time is past 6pm, get next date:
  if (fetchTime.hour > 18){
    final dateToday = DateFormat('dd-MM-yyyy').format(fetchTime.add(Duration(days: 1)));
  }
  else{
    final dateToday = DateFormat('dd-MM-yyyy').format(fetchTime);
  }

  final Map<String, String> params = {
      'district_id': '$districtId',
      'date': dateToday                //ERROR HERE  <------
  }

ERROR:

The non-nullable local variable 'dateToday' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.

Ad

Answer

I believe you are using wrong. You have to set value to already defined variable. In other words, don't use a final keyword in this case.

  String dateToday;   //if time is past 6pm, get next date:   
  if (fetchTime.hour > 18){
    dateToday = DateFormat('dd-MM-yyyy').format(fetchTime.add(Duration(days: 1)));   
  } else{
    dateToday = DateFormat('dd-MM-yyyy').format(fetchTime);   
  }

  final Map<String, String> params = {
      'district_id': '$districtId',
      'date': dateToday    }

Update from author's comment, added by OP:

final keyword should be used when declaring a variable. Since the dateToday was already declared, using final inside the scope creates a new local variable dateToday and the outer dateToday remains unassigned.

Ad
source: stackoverflow.com
Ad