text
stringlengths
1
474
},
decoration: InputDecoration(
hintText: 'This is a hint',
errorText: _errorText,
),
),
),
);
}
}<code_end>
<topic_end>
<topic_start>
Threading & asynchronicity
This section discusses concurrency in Flutter and
how it compares with UIKit.<topic_end>
<topic_start>
Writing asynchronous code
Dart has a single-threaded execution model,
with support for Isolates
(a way to run Dart code on another thread),
an event loop, and asynchronous programming.
Unless you spawn an Isolate,
your Dart code runs in the main UI thread and is
driven by an event loop. Flutter’s event loop is
equivalent to the iOS main loop—that is,
the Looper that is attached to the main thread.Dart’s single-threaded model doesn’t mean you are
required to run everything as a blocking operation
that causes the UI to freeze. Instead,
use the asynchronous facilities that the Dart language provides,
such as async/await, to perform asynchronous work.For example, you can run network code without causing the
UI to hang by using async/await and letting Dart do
the heavy lifting:
<code_start>Future<void> loadData() async {
final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final http.Response response = await http.get(dataURL);
setState(() {
data = 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 const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Map<String, dynamic>> data = <Map<String, dynamic>>[];
@override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final http.Response response = await http.get(dataURL);
setState(() {
data = jsonDecode(response.body);
});
}
Widget getRow(int index) {
return Padding(
padding: const EdgeInsets.all(10),
child: Text('Row ${data[index]['title']}'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample App'),
),
body: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return getRow(index);
},
),
);
}
}<code_end>