Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Futures and async/await in Flutter | Asynchronous Dart in Flutter
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Dart for Flutter Developers

bookFutures 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

main.dart

copy
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

main.dart

copy
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"); } }, ), ), ); } }
Note
Note

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.

question mark

Which statement about using async/await and Future in Flutter is correct?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

bookFutures and async/await in Flutter

Swipe um das Menü anzuzeigen

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

main.dart

copy
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

main.dart

copy
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"); } }, ), ), ); } }
Note
Note

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.

question mark

Which statement about using async/await and Future in Flutter is correct?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1
some-alt