Ad
Dart Says "non-nullable Variable Must Be Initialized Before Use", Even After Assigning With If, Else Block
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
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad