This is my code for main.dart :
class HomePage extends StatefulWidget {
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future userFuture; //error is here
Future<List<String>> getData() async {
var databaseRef2 = FirebaseDatabase.instance.reference();
databaseRef2 = FirebaseDatabase.instance.reference().child("Sliders");
DatabaseEvent event = await databaseRef2.once();
Map<dynamic, dynamic> values =
event.snapshot.value as Map<dynamic, dynamic>;
values.forEach((key, values) {
imgList.add(values["img"]);
});
return imgList;
}
}
}
If I declare Future as:
Future userFuture;
I get this error :
Non-nullable instance field 'userFuture' must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it
Please tell me how to fix it ? Thanks in advance
CodePudding user response:
As per flutter null-safety try to add ?
Future? userFuture;
Or
late Future userFuture;
CodePudding user response:
Well from sdk 2.12 onwards, dart supports null-safety
there are two ways to fix this error, since you haven't mentioned the use of userFuture.
- add late keyboard before the initialisation
late Future userFuture
- add null safety operator
Future? userFuture