text
stringlengths 1
474
|
---|
http.Response response = await http.get(dataURL); |
setState(() { |
widgets = jsonDecode(response.body); |
}); |
}<code_end> |
Once the awaited network call is done, update the UI by calling setState(), |
which triggers a rebuild of the widget subtree and updates the data.The following example loads data asynchronously and displays it in a ListView: |
<code_start>import 'dart:convert'; |
import 'package:flutter/material.dart'; |
import 'package:http/http.dart' as http; |
void main() { |
runApp(const SampleApp()); |
} |
class SampleApp extends StatelessWidget { |
const SampleApp({super.key}); |
@override |
Widget build(BuildContext context) { |
return MaterialApp( |
title: 'Sample App', |
theme: ThemeData( |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
), |
home: const SampleAppPage(), |
); |
} |
} |
class SampleAppPage extends StatefulWidget { |
const SampleAppPage({super.key}); |
@override |
State<SampleAppPage> createState() => _SampleAppPageState(); |
} |
class _SampleAppPageState extends State<SampleAppPage> { |
List widgets = []; |
@override |
void initState() { |
super.initState(); |
loadData(); |
} |
@override |
Widget build(BuildContext context) { |
return Scaffold( |
appBar: AppBar( |
title: const Text('Sample App'), |
), |
body: ListView.builder( |
itemCount: widgets.length, |
itemBuilder: (context, position) { |
return getRow(position); |
}, |
), |
); |
} |
Widget getRow(int i) { |
return Padding( |
padding: const EdgeInsets.all(10), |
child: Text("Row ${widgets[i]["title"]}"), |
); |
} |
Future<void> loadData() async { |
var dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); |
http.Response response = await http.get(dataURL); |
setState(() { |
widgets = jsonDecode(response.body); |
}); |
} |
}<code_end> |
Refer to the next section for more information on doing work in the |
background, and how Flutter differs from Android.<topic_end> |
<topic_start> |
How do you move work to a background thread? |
In Android, when you want to access a network resource you would typically |
move to a background thread and do the work, as to not block the main thread, |
and avoid ANRs. For example, you might be using an AsyncTask, a LiveData, |
an IntentService, a JobScheduler job, or an RxJava pipeline with a |
scheduler that works on background threads.Since Flutter is single threaded and runs an event loop (like Node.js), you |
don鈥檛 have to worry about thread management or spawning background threads. If |
you鈥檙e doing I/O-bound work, such as disk access or a network call, then |
you can safely use async/await and you鈥檙e all set. If, on the other |
hand, you need to do computationally intensive work that keeps the CPU busy, |
you want to move it to an Isolate to avoid blocking the event loop, like |
you would keep any sort of work out of the main thread in Android.For I/O-bound work, declare the function as an async function, |
and await on long-running tasks inside the function: |
<code_start>Future<void> loadData() async { |
var dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); |
http.Response response = await http.get(dataURL); |
setState(() { |
widgets = jsonDecode(response.body); |
}); |
}<code_end> |
This is how you would typically do network or database calls, which are both |
I/O operations.On Android, when you extend AsyncTask, you typically override 3 methods, |
onPreExecute(), doInBackground() and onPostExecute(). There is no |
equivalent in Flutter, since you await on a long-running function, and |
Dart鈥檚 event loop takes care of the rest.However, there are times when you might be processing a large amount of data and |
your UI hangs. In Flutter, use Isolates to take advantage of |
multiple CPU cores to do long-running or computationally intensive tasks.Isolates are separate execution threads that do not share any memory |
with the main execution memory heap. This means you can鈥檛 access variables from |
the main thread, or update your UI by calling setState(). |
Unlike Android threads, |
Isolates are true to their name, and cannot share memory |