Flutter ListView Loading Indicator
In Flutter, you can use a ListView to display a list of items. Sometimes, when the list is loading or fetching data from an API, it’s good to show a loading indicator to let the user know that the data is being fetched. Here’s an example of how to implement a ListView with a loading indicator in Flutter.
1. Create a StatefulWidget
First, create a StatefulWidget that will hold the state of the ListView and the loading status. This will allow us to update the loading status and the data when needed.
class MyListView extends StatefulWidget {
@override
_MyListViewState createState() => _MyListViewState();
}
class _MyListViewState extends State {
bool isLoading = true; // To track the loading status
List items = []; // List of items to display in the ListView
@override
void initState() {
super.initState();
fetchData(); // Call a method to fetch the data (e.g., from an API)
}
void fetchData() async {
// Simulate a delay to show the loading indicator
await Future.delayed(Duration(seconds: 2));
// Fetch the data (e.g., from an API)
List data = ['Item 1', 'Item 2', 'Item 3'];
setState(() {
items = data; // Set the fetched data to the items list
isLoading = false; // Set the loading status to false
});
}
@override
Widget build(BuildContext context) {
return isLoading ? CircularProgressIndicator() : ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
);
}
}
2. Use the MyListView widget
Now, you can use the MyListView widget inside your app to display the ListView with the loading indicator.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('ListView with Loading Indicator'),
),
body: Center(
child: MyListView(),
),
),
);
}
}
In the example above, the MyListView widget fetches the data in the initState()
method using fetchData()
. It sets the loading status to true initially and updates it to false after the data is fetched. During the loading state, a CircularProgressIndicator is shown, and when the data is fetched, the ListView is displayed with the fetched items.
Make sure to import the necessary dependencies and widgets:
import 'package:flutter/material.dart';