Flutter Listview builder Pull-to-refresh

We wrapped the ListView.builder in RefreshIndicator to implement the pull to refresh mechanism.

The UserList is a StatefulWidget because we are updating the list by pulling the data again from the API.

import 'dart:convert';
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =GlobalKey<RefreshIndicatorState>();

Widget _buildList() {
    return user.length != 0
    ? RefreshIndicator(
    child: ListView.builder(
        padding: EdgeInsets.all(8),
        itemCount: user.length,
        itemBuilder: (BuildContext context, int index) {
           return Text(Welcome);
        }
     ),
     onRefresh: _refresh,
     key: _refreshIndicatorKey,
   )
: Center(child: CircularProgressIndicator());
}

Future<void> _refresh() async {
    _refreshIndicatorKey.currentState?.show(atTop: false);
    setState(() {
        user.clear();
        user = fetchUsers();
    });
}

Leave a comment