Implementing Infinite Loading in Flutter
CREATED: 2023 / 02 / 19 Sun
UPDATED: 2023 / 08 / 04 Sun
First, Set Up a StatefulWidget
class InfiniteLoading extends StatefulWidget {
const InfiniteLoading({super.key});
@override
State<InfiniteLoading> createState() => _InfiniteLoadingState();
}
class _InfiniteLoadingState extends State<InfiniteLoading> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan,
appBar: AppBar(
backgroundColor: Colors.redAccent,
),
);
}
}
I added some colors and built a simple screen. We’ll start from here.
Setting Up the API
First, we need data to load. I’ll use PokeAPI for this.
Sending a GET request to the following endpoint retrieves a list of Pokémon starting from Charmander.
https://pokeapi.co/api/v2/pokemon
The response looks like this, returning 20 entries at a time.
{
"count": 1279,
"next": "https://pokeapi.co/api/v2/pokemon?offset=20&limit=20",
"previous": null,
"results": [
{
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
},
.
.
.
{
"name": "raticate",
"url": "https://pokeapi.co/api/v2/pokemon/20/"
}
]
}
The next field contains the endpoint for the next page, which we’ll use to keep fetching more data.
Fetching Data with http
Add http to pubspec.yml and fetch data in Flutter.
dependencies:
flutter:
sdk: flutter
http: ^0.13.5
void _fetchPokemon() async {
http.Response _res = await http.get(
Uri.https('pokeapi.co', '/api/v2/pokemon'),
);
print(_res.body);
print(_res.statusCode);
}
// Add an ElevatedButton to the Scaffold body
Container(
width: double.infinity,
height: 100.0,
child: ElevatedButton(
onPressed: () {
_fetchPokemon();
},
child: Text('GET POKEMON'),
),
)
Tapping the ElevatedButton displays the Pokémon list as follows.
flutter: {"count":1279,"next":"https://pokeapi.co/api/v2/pokemon?offset=20&limit=20","previous":null,"results":[{"name":"bulbasaur","url":"https://pokeapi.co/api/v2/pokemon/1/"},{"name":"ivysaur","url":"https://pokeapi.co/api/v2/pokemon/2/"},{"name":"venusaur","url":"https://pokeapi.co/api/v2/pokemon/3/"},{"name":"charmander","url":"https://pokeapi.co/api/v2/pokemon/4/"},{"name":"charmeleon","url":"https://pokeapi.co/api/v2/pokemon/5/"},{"name":"charizard","url":"https://pokeapi.co/api/v2/pokemon/6/"},{"name":"squirtle","url":"https://pokeapi.co/api/v2/pokemon/7/"},{"name":"wartortle","url":"https://pokeapi.co/api/v2/pokemon/8/"},{"name":"blastoise","url":"https://pokeapi.co/api/v2/pokemon/9/"},{"name":"caterpie","url":"https://pokeapi.co/api/v2/pokemon/10/"},{"name":"metapod","url":"https://pokeapi.co/api/v2/pokemon/11/"},{"name":"butterfree","url":"https://pokeapi.co/api/v2/pokemon/12/"},{"name":"weedle","url":"https://pokeapi.co/api/v2/pokemon/13/"},{"name":"kakuna","url":"https://pokeapi.co<…>
flutter: 200
As-is this is just a plain string, so we can’t use it as a list in a widget. Let’s map it to a Pokemon model.
Creating the Data Model
The model looks like this.
class Pokemon {
String name;
Pokemon(this.name);
factory Pokemon.fromJson(Map<String, dynamic> json) {
final pokemon = Pokemon(json['name']);
return pokemon;
}
}
Using this model to set up the initial state, the code roughly looks like this.
The _fetchPokemon method takes a uri argument so it can also handle next-page requests.
class _InfiniteLoadingState extends State<InfiniteLoading> {
List<Pokemon> _pokemons = [];
String? _nextPageLink;
void _fetchPokemon(Uri uri) async {
http.Response _res = await http.get(uri);
Map<String, dynamic> data = jsonDecode(_res.body);
List<dynamic> dd =
data['results'].map((item) => Pokemon.fromJson(item)).toList();
setState(() {
_pokemons.addAll(dd.map((item) => item as Pokemon).toList());
_nextPageLink = data['next'];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan,
appBar: AppBar(
backgroundColor: Colors.redAccent,
),
body: Container(
width: double.infinity,
height: 100.0,
child: ElevatedButton(
onPressed: () {
_fetchPokemon(Uri.https('pokeapi.co', '/api/v2/pokemon'));
},
child: Text('GET POKEMON'),
),
),
);
}
}
Tapping GET POKEMON on this screen will accumulate Pokemon model data in the _pokemons variable!
We also keep the link for the next page in _nextPageLink.
Adding Load Functionality on Swipe with RefreshIndicator
Next, we prepare a ListView to display the data and wrap it with a RefreshIndicator.
When _pokemons is empty, a GET POKEMON button is shown as the initial load button.
Once it has data, RefreshIndicator enables pull-to-refresh loading.
Scaffold(
body: _pokemons.isEmpty // Check if _pokemons is empty
? Container(
width: double.infinity,
height: 100.0,
child: ElevatedButton(
onPressed: () {
_fetchPokemon(Uri.https('pokeapi.co', '/api/v2/pokemon'));
},
child: Text('GET POKEMON'),
),
)
: RefreshIndicator(
onRefresh: () async {
// Use _nextPageLink if available
if (_nextPageLink != null) {
_fetchPokemon(Uri.parse(_nextPageLink!));
} else {
_fetchPokemon(Uri.https('pokeapi.co', '/api/v2/pokemon'));
}
},
child: ListView.builder(
itemCount: _pokemons.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_pokemons[index].name),
tileColor: Colors.greenAccent,
);
},
),
),
)
Swiping down from the top of the screen now appends data at the bottom. However, it would be nicer if new data appeared near where you swiped.
Adding Data to the Top of the Screen
Adding data to the top is simple — just set reverse: true on ListView.builder.
ListView.builder(
reverse: true,
itemCount: _pokemons.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_pokemons[index].name),
tileColor: Colors.greenAccent,
);
},
)
This makes data appear at the top, like a Twitter timeline.
So how do we add data to the bottom?
Adding Data to the Bottom of the Screen
Implement it as follows. Adjust the details to your liking.
class _InfiniteLoadingState extends State<InfiniteLoading> {
final ScrollController _controller = ScrollController(); // Initialize a controller for the ListView
bool _isLoading = false;
List<Pokemon> _pokemons = [];
String? _nextPageLink;
@override
void initState() {
// Fetch initial data to skip the initial load button
_fetchPokemon(Uri.https('pokeapi.co', '/api/v2/pokemon'));
_controller.addListener(() {
if (_controller.position.maxScrollExtent == _controller.offset) {
// This is called every time the ListView scroll reaches the bottom
_add();
}
});
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _add() {
// We only reach here when scroll hits the bottom, so _nextPageLink is required
if (_nextPageLink != null) {
_fetchPokemon(Uri.parse(_nextPageLink!));
}
}
void _fetchPokemon(Uri uri) async {
// Track loading state before and after the API request
setState(() {
_isLoading = true;
});
http.Response _res = await http.get(uri);
Map<String, dynamic> data = jsonDecode(_res.body);
List<dynamic> dd =
data['results'].map((item) => Pokemon.fromJson(item)).toList();
setState(() {
_pokemons.addAll(dd.map((item) => item as Pokemon).toList());
_nextPageLink = data['next'];
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan,
appBar: AppBar(
backgroundColor: Colors.redAccent,
),
body: ListView.builder(
controller: _controller,
itemCount: _pokemons.length + 1, // Reserve space for the indicator at the bottom
itemBuilder: (context, index) {
if (index + 1 == _pokemons.length + 1) { // Show indicator after all list items
return Padding(
padding: EdgeInsets.all(40.0),
child: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: Container(),
);
}
return ListTile(
title: Text('${_pokemons[index].name}'),
tileColor: Colors.greenAccent,
);
},
),
);
}
}
With this implementation, when the ListView scroll reaches the bottom and an API request begins, an indicator briefly appears, and new data is appended at the bottom once retrieved.
Appendix
That’s about it — infinite loading implementation done!
The source code is also available in this repository.
Switch the home in main.dart to try each variant.
home: const DefaultInfiniteLoading(), // Scroll screen where data is added at the bottom on swipe down
home: const AscendingInfiniteLoading(), // Scroll screen where data is added at the top
home: const DescendingInfiniteLoading(), // Scroll screen where data is added at the bottom