Here's an adaptation of the default Flutter counter app that "counts" to 20,000 slowly, asynchronously, and only once:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(home: MyHomePage());
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<int> _computation;
void _incrementCounter() {
if (_computation != null) return;
setState(() {
_computation = Future.delayed(Duration(seconds: 2)).then((_) => 20000);
});
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return FutureBuilder<int>(
future: _computation,
initialData: 0,
builder: (_, snapshot) => Scaffold(
appBar: AppBar(title: Text('Count a lot')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'${snapshot.data}',
style: theme.textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (_computation == null ? _incrementCounter : null),
tooltip: 'Increment',
backgroundColor:
(_computation == null ? theme.accentColor : Colors.grey),
child: Icon(Icons.add),
),
),
);
}
}