Last active
March 17, 2022 10:07
-
-
Save hotdang-ca/43150abfcafba43962bc56feeb5049b1 to your computer and use it in GitHub Desktop.
Random Flutter Stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:async'; | |
import 'dart:math'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class RandomNumberStream { | |
final StreamController<int> _nextRandomNumberController = StreamController<int>(); | |
Stream<int> get stream => _nextRandomNumberController.stream; | |
RandomNumberStream() { | |
Timer.periodic(Duration(seconds: 2), (t) { | |
_nextRandomNumberController.sink.add(nextRandomInt()); | |
}); | |
} | |
int nextRandomInt() { | |
return Random().nextInt(100); | |
} | |
void dispose() { | |
_nextRandomNumberController.close(); | |
} | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark(), | |
debugShowCheckedModeBanner: true, | |
home: Scaffold( | |
body: Center( | |
child: StreamBuilder<int>( | |
stream: RandomNumberStream().stream, | |
builder: (BuildContext context, AsyncSnapshot<int> snapshot) { | |
Widget output; | |
final textStyle = TextStyle(fontSize: 24.0); | |
switch (snapshot.connectionState) { | |
case ConnectionState.waiting: | |
output = Text('Waiting...', style: textStyle); | |
break; | |
case ConnectionState.none: | |
output = Text('None...', style: textStyle); | |
break; | |
case ConnectionState.active: | |
output = Text(snapshot.data.toString(), style: textStyle); | |
break; | |
case ConnectionState.done: | |
output = Text('Done...', style: textStyle); | |
} | |
return output; | |
} | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment