felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.64k stars 3.37k forks source link

Flutter bloc add event not working second time. #2554

Closed purevoidov closed 3 years ago

purevoidov commented 3 years ago

Hello,

I am currently facing an issue that bloc event called first time and not working second time. Here is the example code of application.

Below code shows the bloc event which is triggered by clicking Save button

class HerdForm extends StatelessWidget {
  final User user;
  Herd herd;

  HerdForm({this.herd, this.user});

  final _titleController = TextEditingController();
  final _descrController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final HerdBloc herdBloc = BlocProvider.of<HerdBloc>(context);

    return Scaffold(
      key: _scaffoldState,
      appBar: AppBar(
        title: Text(
          herd == null ? "Add" : "Update",
          style: TextStyle(
            color: Constant.mainOrange,
            fontSize: 14,
            fontWeight: FontWeight.w300,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            LineIcons.arrowLeft,
            color: Constant.mainOrange,
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Stack(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: BlocConsumer<HerdBloc, HerdState>(
              //bloc: herdBloc,
              listener: (context, state) {
                if (state is HttpResponse) {
                  if (state.success) {
                    popupDialog(context, state.message, state.success);
                    Navigator.of(context).pop();
                  } else {
                    popupDialog(context, state.message, state.success);
                  }
                }
              },
              builder: (context, state) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    TextField(
                      controller: _titleController,
                      keyboardType: TextInputType.text,
                      decoration: InputDecoration(
                        labelText: "Title",
                      ),
                    ),
                    TextField(
                      controller: _descrController,
                      keyboardType: TextInputType.text,
                      decoration: InputDecoration(
                        labelText: "Desc",
                      ),
                      maxLines: 3,
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 5.0),
                      child: SizedBox(
                        width: double.infinity,
                        child: MaterialButton(
                          onPressed: () {
                            String title = _titleController.text;
                            String descr = _descrController.text;

                            if (herd == null) {
                              herd = Herd(title: title, description: descr);

                              herdBloc.add(AddHerd(herd: herd));
                            } else {
                              print(herd.title);
                            }
                          },
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                            side: BorderSide(color: Constant.mainBlue),
                          ),
                          color: Constant.mainBlue,
                          textColor: Colors.white,
                          padding: const EdgeInsets.all(14.0),
                          child: Text("Save"),
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Here is main bloc code.

class HerdBloc extends Bloc<HerdEvent, HerdState> {
  final User user;
  final HerdRepository herdRepository;

  HerdBloc({@required this.user, this.herdRepository})
      : assert(user != null),
        assert(herdRepository != null),
        super(HerdInitial());

  @override
  Stream<HerdState> mapEventToState(HerdEvent event) async* {
    print("got event");
    final currentState = state;
    print("currentState -->" + currentState.toString());
    if (event is FetchHerd) {
      yield HerdLoading();
      try {
        String token = user.accessToken;
        final herdList = await herdRepository.getAllHerds("1", token);
        yield HerdSuccess(herdList: herdList);
      } catch (error) {
        print(error);
        yield HerdFailure(error: error.toString());
      }
    }

    if (event is AddHerd) {
      print("got event");
      String token = user.accessToken;

      try {
        var res = await herdRepository.createHerd(event.herd, token);
        var obj = json.decode(res);

        if (obj["success"]) {
          yield HttpResponse(message: obj["message"], success: true);
          //final herdList = await herdRepository.getAllHerds("1", token);
          //yield HerdSuccess(herdList: herdList);
        } else {
          yield HttpResponse(message: obj["message"], success: false);
        }
      } catch (err) {
        print(err);
        yield HttpResponse(message: "Server error", success: false);
      }
    }
  }
}
purevoidov commented 3 years ago

Okay, finally I solved my problem.