【发布时间】: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