How to get data from API with freezed and bloc in Flutter

Issue

I am trying to work with flutter_bloc and freezed package. I have written simple request to API to get data from that, also generated JSON responce with freezed package, and now trying to put data to UI, so I wrote cod like this:

This is my state and event bloc:

@freezed
class UsersState with _$UsersState {
  const factory UsersState.loading() = _UsersStateLoading;
  const factory UsersState.data(List<Users> usersList) = _UsersDataState;
  const factory UsersState.error() = _UsersErrorState;
}

@freezed
class UsersEvent with _$UsersEvent {
  const factory UsersEvent.getUsers() = UsersAllEventUser;
}

and UsersBloc where I made my requests to API:

class UsersBloc extends Bloc<UsersEvent, UsersState> {
  final Repository repository;

  UsersBloc(this.repository) : super(const UsersState.loading()) {
    on<UsersEvent>(
      (event, emit) async {
        if (event is UsersAllEventUser) {
          const UsersState.loading();
          try {
            final List<Users>? users = await repository.getUsers();
            UsersState.data(users ?? []);
            print(UsersState.data(users ?? []));
          } catch (e) {
            const UsersState.error();
          }
        }
      },
    );
  }
}

My UI code:

 return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: BlocBuilder<UsersBloc, UsersState>(
          builder: (context, state) {
            return state.when(
                loading: () {
                  return const CircularProgressIndicator();
                },
                data: (List<Users> usersList) {
                  return ListView.builder(
                      itemCount: usersList.length,
                      itemBuilder: (context, index) {
                        return CircleAvatar(
                          child: Text(usersList[index].name ?? ''),
                        );
                      });
                },
                error: () => const Text('error is occured'));
          },
        ),
      ),
    );

print(UsersState.data(users ?? [])); return me the pile of nedeed data in logs and it looks like everything works fine, but I can’t pull it into my UI and it returns nothing.

UsersState.data(usersList: [Users(id: 1, name: Leanne Graham, username: Bret, email: Sincere@april.biz, address: Instance of 'Address', phone: 1-770-736-8031 x56442, website: hildegard.org, company: Instance of 'Company'), Users(id: 2, name: Ervin Howell, username: Antonette, email: Shanna@melissa.tv, address: Instance of 'Address', phone: 010-692-6593 x09125, website: anastasia.net, company: Instance of 'Company')

Solution

I think you miss emit at line:

UsersState.data(users ?? []); 

change it to

emit(UsersState.data(users ?? []));

Answered By – manhtuan21

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *