Reputation: 53
I am a beginner to flutter and I don't quite understand how to use Async functions in flutter. For example,
Future <String> readData() async {
final file = await localFile;
String body = await file.readAsString();
return body;
}
So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.
Unfortunately, my build function in main.dart is a synchronous one and when I do:
child : Text(readData());
It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async. How do I go about waiting to get this string and display it?
Upvotes: 1
Views: 207
Reputation: 1814
You can try using FutureBuilder
child: FutureBuilder<String>(
builder: (context, data) {
return Text(data.hasData ? data.data : '');
},
future: readData(),
),
Upvotes: 1
Reputation: 103
Dart Streams - Flutter in Focus
This is very well explained I think should help you
Upvotes: 0