Skip to content

Instantly share code, notes, and snippets.

@AlexKenbo
Created March 9, 2020 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexKenbo/dab0a2fefc95d60c006dae2addb3d12c to your computer and use it in GitHub Desktop.
Save AlexKenbo/dab0a2fefc95d60c006dae2addb3d12c to your computer and use it in GitHub Desktop.
Stream & StreamBuilder in Flutter
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: HomePage(),
title: 'Stream Demo',
));
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stream Demo'),
),
body: Center(
child: StreamBuilder(
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Text(
'1 Minute Completed',
style: TextStyle(
fontSize: 30.0,
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Text(
'Waiting For Stream',
style: TextStyle(
fontSize: 30.0,
),
);
}
return Text(
'00:${snapshot.data.toString().padLeft(2,'0')}',
style: TextStyle(
fontSize: 30.0,
),
);
},
initialData: 0,
stream: _stream(),
),
),
);
}
Stream<int> _stream() {
Duration interval = Duration(seconds: 1);
Stream<int> stream = Stream<int>.periodic(interval, transform);
stream = stream.take(59);
return stream;
}
int transform(int value) {
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment