Use Global Stream
Complete Code For Use Global Stream In Flutter
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
Stream<int> timedCounter(Duration interval, [int maxCount]) async* {
int i = 0;
while (true) {
await Future.delayed(interval);
yield i++;
if (i == maxCount) break;
}
}
Stream<int> myGlobalStream = timedCounter(Duration(seconds: 2), 50);
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
@override
void initState() {
super.initState();
myGlobalStream.listen((count) => setState(() => counter = count));
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.blue[900],
title: Text("Using Global Stream"
)),
body: Center(child: Text("$counter", style: TextStyle(fontSize: 35,color: Colors.lightGreen))),
);
}
}