import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class StreambuilderTest extends StatefulWidget {
@override
_StreambuilderTestState createState() => _StreambuilderTestState();
}
class _StreambuilderTestState extends State<StreambuilderTest> {
var streamController = StreamController();
bool streamActive = true;
@override
void initState() {
myStream();
super.initState();
}
void myStream() async {
var random = Random();
while (streamActive) {
await Future.delayed(Duration(milliseconds: 500));
streamController.add(random.nextInt(1000));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () => streamActive = false,
icon: Icon(Icons.pause),
label: Text('Pause stream'),
),
body: Container(
margin: EdgeInsets.all(20),
child: StreamBuilder(
stream: streamController.stream,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
{
if (snapshot.hasData) {
return Text('Active (snapshot=${snapshot.data})');
} else if (snapshot.hasError) {
return Text('Stream error: ${snapshot.error}');
}
}
break;
case ConnectionState.done:
{
return Text('Done');
}
break;
case ConnectionState.waiting:
{
return Center(
child: CircularProgressIndicator(),
);
}
break;
default:
{
return Text('Undefined');
}
}
}),
),
);
}
}