Skip to content

Instantly share code, notes, and snippets.

@nsmirosh
Last active August 19, 2020 10:07
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 nsmirosh/f8d6f0d2173dfd34dd2800ef55c91832 to your computer and use it in GitHub Desktop.
Save nsmirosh/f8d6f0d2173dfd34dd2800ef55c91832 to your computer and use it in GitHub Desktop.
FutureBuilder example
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