Hi, Flutter community and welcome to day 19 of my challenge ๐
While I'm learning Riverpod, I keep exploring core Dart concepts. Today is a good time for the Future!
Futures
Dart is a single-threaded language that runs an event loop to process things in an asynchronous, non-blocking way. Dart offers two concepts for writing async code: Futures and Streams.
For those who are familiar with Javascript, futures are promises from the Dart world. This Futter in Focus video explains Futures very well: youtube.com/watch?v=OTS-ap9_aXc
As Dart has a sound type system, most of the time you will see the Future keyword in combination with its value type:
// Future's value will be bolean.
Future<bool> fileContains(String path, String needle) async { ... }
// Future's value will be a list of products.
Future<List<Product>> fetchProducts() { ... }
Streams
While a Future resolves to one specific value (or error), Streams can emit multiple values over time. Again, the concept of streams isn't new to me, thanks to Node.js.
Stream<List<Notification>> watchNotifications() { ... }
A classic stream example is the file system. In the code below I open a CSV file for reading, apply multiple transforms (such as a CSV converter) on the fly and finally get a list of results.
final input = File('data/data.csv').openRead();
final List<List<dynamic>> data = await input
.transform(utf8.decoder)
.transform(CsvToListConverter(eol: '\n'))
.toList();
Widget of the day - FutureBuilder
To continue on the asynchronous topic, I picked the FutureBuilder
widget. It's a handy helper to render Flutter UI based on the Future at hand.
FutureBuilder(
future: http.get('https://example.com/data'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return MyData(snapshot.data);
}
else {
return LoadingIndicator();
}
}
)
We can go further and use StreamBuilder instead which will reactively update our UI based on the results from the stream.
Summary
Futures
and Streams
in Dart look very clear and robust. With the addition of helper widgets like FutureBuilder
and StreamBuilder
, the async programming in Flutter should be a breeze! โ๏ธ