Skip to content

Instantly share code, notes, and snippets.

@jmolins
Created December 24, 2018 23:53
Show Gist options
  • Save jmolins/cd426981fa3f675aed55b035cb63d4b4 to your computer and use it in GitHub Desktop.
Save jmolins/cd426981fa3f675aed55b035cb63d4b4 to your computer and use it in GitHub Desktop.
How to block Flutter ui with an inappropriate await
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<void> doSomething() async {
await Future.delayed(Duration(seconds: 4));
}
void _incrementCounter() async {
// This blocks the ui for the duration of the async call
await doSomething();
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment