So I have some question abaout how to correctly use FutureBuilder. I read somewhere that we should store the future in a variable and call that variable in the FutureBuilder instead of the future service. But how do we initalize the initial value of that variable? When I tired this, it always gives LateInitializationError: Field '_dataFuture@28307501' has not been initialized.
and should wait until the data is loaded.
late Future<List<TransaksiResp>> _dataFuture;
@override
void initState() {
super.initState();
transaksiService = TransaksiService();
getUserPrefs().then((value) {
setState(() {
_dataFuture = transaksiService.getTransaksi(user[2]);});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Flexible(
child: SizedBox(
child: FutureBuilder<List<TransaksiResp>>(
future: _dataFuture,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasError) {
print(snapshot);
return Center(
child: Text("Error"),
);
} else if (snapshot.hasData){
List<TransaksiResp> response = snapshot.data;
return _buildListView(response);
} else {
return Center(
child: Container(),
);
}
},
),
),
)
],
),
);
}
This is getUserPrefs method to get user data from Shared Preference
Future<void> getUserPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
user = prefs.getStringList("user")!;
setState(() {});
}