flutter - The argument type 'Future<List<User>>' can't be assigned to the parameter type 'Future<void> Function()' in onRefresh when using RefreshIndicator - TagMerge
2The argument type 'Future<List<User>>' can't be assigned to the parameter type 'Future<void> Function()' in onRefresh when using RefreshIndicatorThe argument type 'Future<List<User>>' can't be assigned to the parameter type 'Future<void> Function()' in onRefresh when using RefreshIndicator

The argument type 'Future<List<User>>' can't be assigned to the parameter type 'Future<void> Function()' in onRefresh when using RefreshIndicator

Asked 1 years ago
1
2 answers

Instead of calling _fetchUsersListUsingLoop you should use setState to cause a rebuild so that FutureBuilder fetches the data again.

onRefresh: () => setState(() {})

That being said it's best to store your future in initState and update this future when needed by calling setState. This is from documentation:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

Future<List<User>>? _usersFuture;

@override
  void initState() {
    super.initState();
    _usersFuture = _fetchUsersListUsingLoop();
}

Then:

onRefresh: () {
    setState(() {
      _usersFuture = _fetchUsersListUsingLoop();
    });
  }

Source: link

1

When you do this

onRefresh: _fetchUsersListUsingLoop(),

You are telling dart to call _fetchUsersListUsingLoop and expect it to return a function, then to call said function, what you want to do instead is tell it to just call _fetchUsersListUsingLoop:

onRefresh: _fetchUserListUsingLoop,

or ìf that doesn't work:

onRefresh: () async => _fetchUserListUsingLoop(),

But the problem is that this will not actually work, why? Because the future builder is already completed and nothing will change that, to fix your issue; you can reassign the future like this:

You need to declare a future:

late Future<List<User>> _user;
        child: FutureBuilder(
            future: _users,
            builder: (context, asyncSnapshot) {
              ...
                    onRefresh: _updateUsersFuture,
              ...

Then somewhere in your class you do:

Future<void> _updateUsersFuture() async {
  final newUsers = await _fetchUserListUsingLoop();
  setState(() => _users = newUsers);
}

and on initstate:

@override
void initState() {
  _users = _fetchUsersListUsingLoop();
  super.initState();
}

Source: link

Recent Questions on flutter

    Programming Languages