text
stringlengths
1
372
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();
}
bool get showLoadingDialog => data.isEmpty;
future<void> loadData() async {
final ReceivePort receivePort = ReceivePort();
await Isolate.spawn(dataLoader, receivePort.sendPort);
// the 'echo' isolate sends its SendPort as the first message.
final SendPort sendPort = await receivePort.first as SendPort;
final List<Map<String, dynamic>> msg = await sendReceive(
sendPort,
'https://jsonplaceholder.typicode.com/posts',
);
setState(() {
data = msg;
});
}
// the entry point for the isolate.
static future<void> dataLoader(SendPort sendPort) async {
// open the ReceivePort for incoming messages.
final ReceivePort port = ReceivePort();
// notify any other isolates what port this isolate listens to.
sendPort.send(port.sendPort);
await for (final dynamic msg in port) {
final string url = msg[0] as string;
final SendPort replyTo = msg[1] as SendPort;
final uri dataURL = uri.parse(url);
final http.Response response = await http.get(dataURL);
// lots of JSON to parse
replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
}
}
Future<List<Map<String, dynamic>>> sendReceive(SendPort port, string msg) {
final ReceivePort response = ReceivePort();
port.send(<dynamic>[msg, response.sendPort]);
return response.first as Future<List<Map<String, dynamic>>>;
}
widget getBody() {
bool showLoadingDialog = data.isEmpty;
if (showloadingdialog) {
return getProgressDialog();
} else {
return getListView();
}
}
widget getProgressDialog() {
return const center(child: CircularProgressIndicator());
}
ListView getListView() {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, position) {
return getRow(position);
},
);
}
widget getRow(int i) {
return padding(
padding: const EdgeInsets.all(10),
child: Text("Row ${data[i]["title"]}"),
);
}
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Sample app'),
),
body: getBody(),
);
}
}
<code_end>
<topic_end>
<topic_start>
making network requests
making a network call in flutter is easy when you
use the popular http package. this abstracts