Home > OS >  Flutter using useEffect to get data from server and getting return type error
Flutter using useEffect to get data from server and getting return type error

Time:05-09

After implementing a simple riverpod library to send request and getting response from server, when i try to use useEffect for that i get this error:

Error: A value of type 'Future<NetworkRequestState<Posts>>' 
can't be returned from a function with return type 'void Function()?'.

Riverpod repository implementation:

final getPostProvider = Provider((ref) => PostRepository(ref.read));
final postProvider =
    StateNotifierProvider<PostNotifier, NetworkRequestState<Posts>>(
  (ref) => PostNotifier(
    ref.watch(getPostProvider),
  ),
);

class PostRepository {
  final Reader _reader;

  PostRepository(this._reader);

  Future<Posts> requestGetPosts() async {
    try {
      const r = RetryOptions(maxAttempts: 3);
      final response = await r.retry(
        () => _reader(dioProvider)
            .get(Server.$posts,
                options: Options(
                  headers: {'Content-Type': 'application/json'},
                ))
            .timeout(const Duration(seconds: 30)),
        retryIf: (e) => e is SocketException || e is TimeoutException,
      );

      return Posts.fromJson(response.data as Map<String, dynamic>);
    } on DioError catch (e) {
      throw e.error as Object;
    }
  }
}

class PostNotifier extends RequestStateNotifier<Posts> {
  final PostRepository _postRepository;

  PostNotifier(this._postRepository);

  Future<NetworkRequestState<Posts>> getPosts() =>
      makeRequest(() =>
          _postRepository.requestGetPosts());
}

and HookWidget class:

class Home extends HookWidget {
  @override
  Widget build(BuildContext context) {
    useEffect(() => useProvider(postProvider.notifier).getPosts());

    //...
}

full error:

lib/src/home/home.dart:20:56: Error: A value of type 'Future<NetworkRequestState<Posts>>' can't be returned from a function with return type 'void Function()?'.
 - 'Future' is from 'dart:async'.
 - 'NetworkRequestState' is from 'package:xxxxxxxxxx/service/freezed/network_request_state.dart' ('lib/service/freezed/network_request_state.dart').
 - 'Posts' is from 'package:xxxxxxxxxx/src/home/model/posts.dart' ('lib/src/home/model/posts.dart').
    useEffect(() => useProvider(postProvider.notifier).getPosts());
                                                       ^

CodePudding user response:

useProvider doesn't return a void Function()? and useEffect expects a void Function()? to be returned.

Do this:

useEffect((){
  useProvider(postProvider.notifier).getPosts();
  return (){};
});

Or you can choose to not return anything at all like so:

useEffect((){
  useProvider(postProvider.notifier).getPosts();
});

Note: Consider moving to the new version of hooks_riverpod as useProvider is already deprecated.

Fix for: Cannot listen to inherited widgets inside HookState.initState. Use HookState.build instead

Since useProvider is a hook, you don't have to put it in useEffect

Just do:

 Widget build(BuildContext context) {
    useProvider(postProvider.notifier).getPosts();
  • Related