[英]Flutter: blocprovider.of() called with a context that does not contain a Bloc of type
I am new to flutter and i wanted to implement a simple Login screen using BLoc.我是 flutter 的新手,我想使用 BLoc 实现一个简单的登录屏幕。 There is no build error but in runtime the following error is received
没有构建错误,但在运行时收到以下错误
"blocprovider.of() called with a context that does not contain a Bloc of type LoginBloc" “使用不包含 LoginBloc 类型的 Bloc 的上下文调用 blocprovider.of()”
My Code我的代码
class LoginForm extends StatefulWidget {
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
_onLoginButtonPressed() {
BlocProvider.of<LoginBloc>(context).add(
LoginButtonPressed(
username: _usernameController.text,
password: _passwordController.text,
),
);
}
return BlocBuilder<LoginBloc, LoginState>(
builder: (context, state) {
return Form(
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'username'),
controller: _usernameController,
),
TextFormField(
decoration: InputDecoration(labelText: 'password'),
controller: _passwordController,
obscureText: true,
),
RaisedButton(
onPressed:
state is! LoginInProgress ? _onLoginButtonPressed : null,
child: Text('Login'),
),
Container(
child: state is LoginInProgress
? CircularProgressIndicator()
: null,
),
],
),
);
},
);
}
}
Did you "provide" the LoginBloc
in a widget above LoginForm
?您是否在
LoginForm
上方的小部件中“提供”了LoginBloc
?
This error means that there is no parent widget referencing a created LoginBloc
.此错误意味着没有父小部件引用创建的
LoginBloc
。
If you don't you'll need to have:如果不这样做,您将需要:
BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
builder: (context, state) {
// LoginForm can now use `BlocProvider.of<LoginBloc>(context)`
}
)
Make sure that LoginForm
is under LoginBloc
widget tree from dev tools.确保
LoginForm
位于开发工具的LoginBloc
小部件树下。 May be you are using Navigator.push()
from the AuthPage
to open new login form.可能您正在使用
AuthPage
中的Navigator.push()
打开新的登录表单。 If you are doing like this, then loginForm
will be rendered as a new page again without LoginPage
as a parent.如果您这样做,那么
loginForm
将再次呈现为新页面,而没有LoginPage
作为父页面。 So try to keep LoginForm
under LoginScreen
.因此,请尝试将
LoginForm
保留在LoginScreen
下。
Your Widget tree should look like below:您的 Widget 树应如下所示:
--LoginScreen
--LoginBloc
--LoginForm
And also make sure that you created LogicBloc as @jack said in first comment:并确保您按照@jack 在第一条评论中所说的那样创建了 LogicBloc:
BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
builder: (context, state) {
// LoginForm can now use `BlocProvider.of<LoginBloc>(context)`
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.