A Spinner While Loading
Part of the Data and the Network section of Coddy's Flutter journey. Lesson 5 of 27.
Two seconds is a long time to stare at a screen that does not move. A spinning circle tells the person the app is working on it. In Flutter it is CircularProgressIndicator.
const CircularProgressIndicator()It needs nothing to work: put it on the screen and it spins. The job is to show it only while the data is on its way. A bool in your state does that:
bool loading = false;
// before the await: loading = true
// after the await: loading = false
loading ? const CircularProgressIndicator() : Text(message)Set loading to true in a setState before you await, and back to false in the setState that shows the answer.
Challenge
EasyReplace the Loading... text with a spinner:
- add
bool loading = false;to the state - set it to
truebefore thefetchand back tofalsewhen the message arrives - while
loadingis true, show aCircularProgressIndicatorin place of the message
Try it yourself
import 'package:flutter/material.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MessageScreen(),
);
}
}
class MessageScreen extends StatefulWidget {
const MessageScreen({super.key});
@override
State<MessageScreen> createState() => _MessageScreenState();
}
class _MessageScreenState extends State<MessageScreen> {
String message = 'No message yet';
Future<void> loadMessage() async {
setState(() {
message = 'Loading...';
});
final text = await fetch('/message');
setState(() {
message = text;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 24),
ElevatedButton(onPressed: loadMessage, child: const Text('Load message')),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and the Network
2Loading Screens
A Spinner While LoadingMeet FutureBuilderFetch Once in initStateReload Data With a ButtonPull to RefreshPractice on your own: Online Flutter compiler