[英]Flutter Error:(Webview) Media Query.of() called with a context that does not contain a media query
[英]Flutter: blocprovider.of() called with a context that does not contain a Bloc of type
我是 flutter 的新手,我想使用 BLoc 实现一个简单的登录屏幕。 没有构建错误,但在运行时收到以下错误
“使用不包含 LoginBloc 类型的 Bloc 的上下文调用 blocprovider.of()”
我的代码
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,
),
],
),
);
},
);
}
}
您是否在LoginForm
上方的小部件中“提供”了LoginBloc
?
此错误意味着没有父小部件引用创建的LoginBloc
。
如果不这样做,您将需要:
BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
builder: (context, state) {
// LoginForm can now use `BlocProvider.of<LoginBloc>(context)`
}
)
确保LoginForm
位于开发工具的LoginBloc
小部件树下。 可能您正在使用AuthPage
中的Navigator.push()
打开新的登录表单。 如果您这样做,那么loginForm
将再次呈现为新页面,而没有LoginPage
作为父页面。 因此,请尝试将LoginForm
保留在LoginScreen
下。
您的 Widget 树应如下所示:
--LoginScreen
--LoginBloc
--LoginForm
并确保您按照@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.