我正在尝试做一个简单的表单验证模型,到目前为止,我无法使用 TextField() 的 onChanged 属性在 BlocBuilder() 下更新我的状态。
这是我的 BlocProvider()
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Log me in',
home: Scaffold(
body: BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
child: LoginScreen(),
),
),
);
}
}
这是需要在输入更改时更新的主文件。'$snapshot' 应该根据其'当前状态产生来自 LoginBloc 的内容,但看起来它不会在 onChanged 在线 StreamBuilder() 上重建自身
lass LoginScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final LoginBloc bloc = BlocProvider.of<LoginBloc>(context);
return BlocBuilder<LoginBloc, String>(
bloc: LoginBloc(),
builder: (context, snapshot) {
return Container(
margin: EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// emailField(bloc),
TextField(
onChanged: (_) => bloc.add(LoginEvent.username),
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: 'example@email.com',
labelText: 'Email Address',
errorText: '$snapshot',
),
),
// passwordField(bloc),
TextField(
onChanged: (_) => bloc.add(LoginEvent.password),
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
hintText: 'Password',
labelText: 'Password',
errorText: '$snapshot',
),
),
SizedBox(
height: 25,
),
// submitButton(),
],
),
);
});
}
这是我的 LoginBloc()
class LoginBloc extends Bloc<LoginEvent, String> {
get initialState => '';
Stream<String> mapEventToState(LoginEvent event) async* {
switch (event) {
case LoginEvent.username:
if (state.contains('@')) {
yield 'Approved';
} else {
yield 'Please retry';
}
break;
case LoginEvent.password:
if (state.length > 3) {
yield 'Nice password';
}
yield "Please retry";
}
}
}
谢谢