flutter riverpod how to return multiple types from one provider

156 views Asked by At

I am using riverpod , I created a StateNotifierProvider like this:

final mainUserProvider = StateNotifierProvider.autoDispose<
    MainUserController, AsyncValue<dynamic>>((ref) {
  return MainUserController(ref);
});

and this is my controller :

class MainUserController extends StateNotifier<AsyncValue<dynamic>> {
  MainUserController(this.ref)
      : super(const AsyncValue.loading());

  final Ref ref;

  Future<void> getAllUsers() async {
    // state = const UIState.loading();
    final result = get all users;

    state = AsyncValue.data(result);
  }
}

Now In ui I am using like this:

class UserExploreScreen extends ConsumerStatefulWidget {

 var mainUserState = ref.watch(mainUserProvider);
....
            mainUserState.whenOrNull(
              data: (mainProductCategories) {
                return GridView(
                  gridDelegate: ResponsiveGridDelegate(
                       ....
                  ),
                  primary: false,
                  padding: const EdgeInsets.all(20),
                  shrinkWrap: true,
                  children: mainProductCategories.map(
                    (user) {
                      return UsersCard(
                        isSelected: false,
                        title: user.name,
                        imageUrl: user. Icon ?? "",
                         .....
                          );
                        },
                      );
                    },
                  ).toList(),
                );
              },
              loading: () => Container(),
            )!,

but I am getting this error :

Expected a value of type 'List<Widget>', but got one of type 'List<dynamic>'

I guess because in provider I did not mention the type, and I dont want mention, because I need to return other type of object, Now list of user and later other type like Production .

How can I solve this issue?

1

There are 1 answers

1
Dhafin Rayhan On BEST ANSWER

By using dynamic it means you're disabling static checking. If you want to have an object that serve more than one type, consider using the Object type instead.

Take the following example:

dynamic firstList = [2,4];
List<Object> secondList = [2,4];
final a = firstList.map((e) => Container()).toList();
final b = secondList.map((e) => Container()).toList();

a is a dynamic, while b is a List<Container> (which is expected).


These should be a good read: