In the code below (Dart 2.4.0 Windows), returning null from a future that indicates a return type of String results in:
I/flutter ( 8735): The following assertion was thrown building Builder:
I/flutter ( 8735): type 'Future<dynamic>' is not a subtype of type 'Future<String>'
If I return "null as String;", VSCode shows a warning "unnecessary cast", however, the code works and I don't get the fatal error. The Code in question is below. I have commented out the line that was causing the problem and now return "null as String". I use a null String all the time in Dart without a problem, so it only appears to be a problem with Futures AFAIK. Is this just a known fact about Dart and Futures and this is the workaround ("return null as String")?
@override
void initState() {
super.initState();
Future<String> future = _initPreferences();
future.then((sError) {
if (sError != null) debugPrint("\n*** Error from initPrefs = $sError\n");
if (sError == null) debugPrint("\n***Preferences were initialized OK\n");
});
}
Future<String> _initPreferences() {
return SharedPreferences.getInstance().then((prefs) {
_prefs = prefs;
//return null;
return null as String;
}).catchError((vError) {
return "Unable to load categories";
});
}