Created
February 14, 2022 11:39
-
-
Save wingkit-leung/b08f7dd66fcb2e15d3ca5e91b0b336bf to your computer and use it in GitHub Desktop.
Flutter Example of using FutureBuilder and StreamBuilder
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
// CopsOnRoad https://stackoverflow.com/questions/50844519/flutter-streambuilder-vs-futurebuilder | |
import 'package:flutter/material.dart'; | |
void main() => runApp(const MaterialApp(home: HomePage())); | |
class HomePage extends StatefulWidget { | |
const HomePage({Key? key}) : super(key: key); | |
@override | |
_HomePageState createState() => _HomePageState(); | |
} | |
class _HomePageState extends State<HomePage> { | |
int _count = 0; // used by StreamBuilder | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
_buildFutureBuilder(), | |
const SizedBox(height: 24), | |
_buildStreamBuilder(), | |
], | |
), | |
); | |
} | |
Widget _buildFutureBuilder() { | |
return Center( | |
child: FutureBuilder<int>( | |
future: _calculateSquare(10), | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.done) { | |
return Text("Square = ${snapshot.data}"); | |
} | |
return const CircularProgressIndicator(); | |
}, | |
), | |
); | |
} | |
Future<int> _calculateSquare(int num) async { | |
await Future.delayed(const Duration(seconds: 5)); | |
return num * num; | |
} | |
Widget _buildStreamBuilder() { | |
return Center( | |
child: StreamBuilder<int>( | |
stream: _stopwatch(), | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.active) { | |
return Text("Stopwatch = ${snapshot.data}"); | |
} | |
return const CircularProgressIndicator(); | |
}, | |
), | |
); | |
} | |
Stream<int> _stopwatch() async* { | |
while (true) { | |
await Future.delayed(const Duration(seconds: 1)); | |
yield _count++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment