【问题标题】:Flutter BLoC is not updating the state or notifying the changes in the screen or widgetFlutter BLoC 未更新状态或通知屏幕或小部件中的更改
【发布时间】:2021-11-29 16:43:54
【问题描述】:

我正在使用 Flutter 构建一个移动应用程序。我正在使用 BLoC 进行状态管理。我正在使用这个库,https://pub.dev/packages/flutter_bloc。我的应用程序正在将事件发送到 Bloc 类。但状态不会在屏幕或小部件中更新。

这是我的 LoginBloc 类:

class LoginBloc extends Bloc<LoginEvent, LoginState> {

  LoginBloc() : super(LoginState.initial()) {
    on<LoginEvent>((event, emit) async {
      // yield the state here. check the event and then process the event and yield the state based on the result.
      if (event is Login) {
        var response = await ApiService.post(ApiEndpoints.login, {
          'email': event.email,
          'password': event.password
        });

        try {
          if (response.statusCode == 200) {
            // TODO: provide implementation
            var responseJson = jsonDecode(response.body);
            MeData meData = MeData.fromJson(responseJson['data']);
          } else {
            ApiError apiError = Utilities.parseApiError(response.body);
            emit(LoginState(event.email, event.password, false, apiError));
          }
        } catch (e) {
            var apiError = ApiError();
            apiError.setGenericErrorMessage("Something went wrong!");
            emit(LoginState(event.email, event.password, false, apiError));
        }
      }
    });
  }
}

这是我的 login_event.dart 文件。

abstract class LoginEvent {
  const LoginEvent();
}

// fields are the parameters to be passed to the service class in the bloc class.
class Login extends LoginEvent {
  final String email;
  final String password;

  const Login(this.email, this.password);
}

这是我的 login_state.dart 文件

class LoginState {
  String email = "";
  String password = "";
  bool isLoading = false;
  ApiError error = ApiError();
  String genericFormError = "";

  LoginState(String emailParam, String passwordParam, bool isLoadingParam, ApiError errorParam) {
    email = emailParam;
    password = passwordParam;
    isLoading = isLoadingParam;
    error = errorParam;
    genericFormError = error.getGenericErrorMessage();
  }

  static LoginState initial()
  {
    return LoginState("", "", false, ApiError());
  }
}

这是我的登录屏幕或小部件

class _LoginPage extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String? _email;
  String? _password;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
          title: Text(widget.title)
      ),
      body: BlocListener<LoginBloc, LoginState>(
        listener: (context, state) {

        },
        child: BlocBuilder<LoginBloc, LoginState>(
            builder: (context, state) {
              return Center(
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        GenericFormError(errorMessage: state.genericFormError),
                        Padding(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            decoration: InputDecoration(
                                labelText: "Email",
                                border: const OutlineInputBorder(),
                                errorText: state.error.getFieldError("email")
                            ),
                            onChanged: (value) => setState(() {
                              _email = value;
                            }),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "Please enter email";
                              }
                              return null;
                            },
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            obscureText: true,
                            enableSuggestions: false,
                            autocorrect: false,
                            decoration: InputDecoration(
                                labelText: "Password",
                                border: const OutlineInputBorder(),
                                errorText: state.error.getFieldError("password")
                            ),
                            onChanged: (value) => setState(() {
                              _password = value;
                            }),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "Please enter password";
                              }
                              return null;
                            },
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10),
                          child: SizedBox(
                            width: double.infinity,
                            height: 50,
                            child: ElevatedButton(
                              onPressed: () {
                                var isValid = _formKey.currentState!.validate();
                                if (isValid) {
                                  context.read<LoginBloc>().add(Login(_email.toString(), _password.toString()));
                                }
                              },
                              child: const Text('Login'),
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
              );
            }
        ),
      ),
    );
  }
}

正如您在登录屏幕/小部件中单击登录按钮时看到的那样,它正在触发登录事件。

LoginBloc 中的这一行已被执行。

var apiError = ApiError();
            apiError.setGenericErrorMessage("Something went wrong!");
            emit(LoginState(event.email, event.password, false, apiError));

但登录屏幕或小部件中的状态未更新。

bloc 侦听器方法也在运行中。我该如何解决?

【问题讨论】:

    标签: flutter dart flutter-bloc


    【解决方案1】:

    如果响应代码为 200,您当前不会发出任何状态,因此即使您没有收到错误,也不会发生任何事情。

    你应该有一个LoginState 的抽象类,然后定义至少 3 个类,即。 NotLoggedIn、LoginSuccess 和 LoginError 的初始状态,扩展 LoginState。

    您的集团应根据每个潜在响应发出相应的状态,BlocBuilder 应相应地响应每个状态。

    【讨论】:

    • 这并不完全正确。当您发出此状态的新实例时,您只能拥有一个状态并仍然触发 UI 的重建。请参阅:bloclibrary.dev/#/faqs?id=when-to-use-equatable。您的其余答案仍然有效。
    • 感谢@puelo 的更正。注意到未来,我更新了我的回复。
    猜你喜欢
    • 2021-03-19
    • 2020-10-10
    • 2021-06-17
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2020-04-17
    • 2020-08-03
    • 2021-01-06
    相关资源
    最近更新 更多