Futures and async/await in Flutter
When building Flutter apps, you often need to perform tasks that take time to complete, such as fetching data from the internet or reading from a database. Dart provides the Future class and the async/await keywords to make handling these asynchronous operations straightforward. In Flutter, using Future and async/await allows your app to remain responsive while waiting for operations to finish, without blocking the user interface.
main.dart
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: AsyncDemo(), ); } } class AsyncDemo extends StatefulWidget { @override _AsyncDemoState createState() => _AsyncDemoState(); } class _AsyncDemoState extends State<AsyncDemo> { String _data = "No data yet"; Future<void> fetchData() async { await Future.delayed(Duration(seconds: 2)); // Simulate network delay setState(() { _data = "Fetched data!"; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Async/Await Demo")), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_data), SizedBox(height: 20), ElevatedButton( onPressed: fetchData, child: Text("Fetch Data"), ), ], ), ), ); } }
When you use await inside an async function in a Flutter widget, you often need to update the UI once the asynchronous operation completes. You should call setState after the await to notify Flutter that the widget's state has changed, prompting a rebuild with the new data.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738394041// main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: FutureBuilderDemo(), ); } } class FutureBuilderDemo extends StatelessWidget { Future<String> fetchData() async { await Future.delayed(Duration(seconds: 2)); return "Async data loaded!"; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("FutureBuilder Example")), body: Center( child: FutureBuilder<String>( future: fetchData(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text("Error: {snapshot.error}"); } else { return Text(snapshot.data ?? "No data"); } }, ), ), ); } }
Always ensure that a Future has completed before accessing its data. In Flutter, widgets like FutureBuilder help manage this by rebuilding when the Future completes, but if you access data too early (before the await or before the snapshot is ready), you may encounter errors or display incomplete information.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Incrível!
Completion taxa melhorada para 7.14
Futures and async/await in Flutter
Deslize para mostrar o menu
When building Flutter apps, you often need to perform tasks that take time to complete, such as fetching data from the internet or reading from a database. Dart provides the Future class and the async/await keywords to make handling these asynchronous operations straightforward. In Flutter, using Future and async/await allows your app to remain responsive while waiting for operations to finish, without blocking the user interface.
main.dart
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: AsyncDemo(), ); } } class AsyncDemo extends StatefulWidget { @override _AsyncDemoState createState() => _AsyncDemoState(); } class _AsyncDemoState extends State<AsyncDemo> { String _data = "No data yet"; Future<void> fetchData() async { await Future.delayed(Duration(seconds: 2)); // Simulate network delay setState(() { _data = "Fetched data!"; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Async/Await Demo")), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_data), SizedBox(height: 20), ElevatedButton( onPressed: fetchData, child: Text("Fetch Data"), ), ], ), ), ); } }
When you use await inside an async function in a Flutter widget, you often need to update the UI once the asynchronous operation completes. You should call setState after the await to notify Flutter that the widget's state has changed, prompting a rebuild with the new data.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738394041// main.dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: FutureBuilderDemo(), ); } } class FutureBuilderDemo extends StatelessWidget { Future<String> fetchData() async { await Future.delayed(Duration(seconds: 2)); return "Async data loaded!"; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("FutureBuilder Example")), body: Center( child: FutureBuilder<String>( future: fetchData(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text("Error: {snapshot.error}"); } else { return Text(snapshot.data ?? "No data"); } }, ), ), ); } }
Always ensure that a Future has completed before accessing its data. In Flutter, widgets like FutureBuilder help manage this by rebuilding when the Future completes, but if you access data too early (before the await or before the snapshot is ready), you may encounter errors or display incomplete information.
Obrigado pelo seu feedback!