For this recipe, we will create a stream and use StreamBuilder to update the user interface. Perform the following steps:
- In your new app, in the lib folder of your project, create a new file, called stream.dart.
- In the stream.dart file, create a class called NumberStream:
class NumberStream {}
- Inside the NumberStream class, add a method that returns a stream of the int type and returns a new random number each second:
import 'dart:math';
class NumberStream {
Stream<int> getNumbers() async* {
yield* Stream.periodic(Duration(seconds: 1), (int t) {
Random random = Random();
int myNum = random.nextInt(10);
return myNum;
});
}
}
- In the main.dart file, edit the existing code of the sample app so that it looks like the following:
import 'package:flutter/material.dart';
import 'stream.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget...