Last active
August 19, 2020 10:07
-
-
Save nsmirosh/f8d6f0d2173dfd34dd2800ef55c91832 to your computer and use it in GitHub Desktop.
FutureBuilder example
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(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold(body: MyStatefulWidget()), | |
); | |
} | |
} | |
class MyStatefulWidget extends StatefulWidget { | |
MyStatefulWidget({Key key}) : super(key: key); | |
@override | |
_MyStatefulWidgetState createState() => _MyStatefulWidgetState(); | |
} | |
class _MyStatefulWidgetState extends State<MyStatefulWidget> { | |
var increment = 0; | |
Future<String> _myFuture = _buildAFuture(); | |
Widget build(BuildContext context) { | |
return DefaultTextStyle( | |
style: Theme.of(context).textTheme.headline2, | |
textAlign: TextAlign.center, | |
child: FutureBuilder<String>( | |
future: _myFuture, | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
List<Widget> children; | |
if (_waitingForTheResult(snapshot)) { | |
children = <Widget>[ | |
SizedBox( | |
child: LinearProgressIndicator(), | |
width: 200, | |
height: 20, | |
), | |
const Padding( | |
padding: EdgeInsets.only(top: 16), | |
child: Text('Waiting for the result...'), | |
) | |
]; | |
} else if (snapshot.hasData) { | |
children = <Widget>[ | |
Text('Result: ${snapshot.data}', style: TextStyle(color: Colors.green)), | |
]; | |
} else if (snapshot.hasError) { | |
children = <Widget>[ | |
Padding( | |
padding: const EdgeInsets.only(top: 16), | |
child: Text('Result: ${snapshot.error}', style: TextStyle(color: Colors.red)), | |
) | |
]; | |
} | |
children.add(RaisedButton( | |
child: Text("Try again"), | |
onPressed: () { | |
setState(() { | |
_calculation = _buildAFuture(increment); | |
increment++; | |
increment = increment; | |
}); | |
})); | |
return Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: children, | |
), | |
); | |
}, | |
), | |
); | |
} | |
} | |
_buildAFuture([int increment = 0]) => Future<String>.delayed( | |
Duration(seconds: 2), () => increment % 2 == 0 ? throw 'Boom!' : 'Value'); | |
_waitingForTheResult(AsyncSnapshot snapshot) => snapshot.connectionState == ConnectionState.waiting; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment