text
stringlengths
1
80
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
(in the form of static fields, for example).
the following example shows, in a simple isolate, how to share data back to
the main thread to update the UI.
<code_start>
future<void> loadData() async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(dataLoader, receivePort.sendPort);