I'm new to flutter. I'm using SharedPreferences to store data. I have this dynamic function:
_loadFromLocal(index) async {
var data = await getFromLocal();
return data?.elementAt(index);
}
Future<List<String>?> getFromLocal() async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList('data_prices');
}
I need to call this dynamic fucntion _loadFromLocal in Widget build
class _ScanState extends State<Scan> {
@override
Widget build(BuildContext context) {
return
Scaffold(
child: Container(
child:Text(
_loadFromLocal(0),
)),);
}
}
How can I do that
You can't call async code as you mentioned, instead you should call it in initState()
like below
class _ScanState extends State<Scan> {
dynamic value;
@override
void initState() {
super.initState();
_loadFromLocal(0).then((data) {
setState(() {
value = data;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Text(
value ?? '',
),
),
);
}
// omit the rest code
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.