Created
March 9, 2020 17:49
-
-
Save AlexKenbo/dab0a2fefc95d60c006dae2addb3d12c to your computer and use it in GitHub Desktop.
Stream & StreamBuilder in Flutter
This file contains 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'; | |
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