Flutter:使用不包含Bloc类型的上下文调用blocprovider.of() [英] Flutter: blocprovider.of() called with a context that does not contain a Bloc of type

查看:80
本文介绍了Flutter:使用不包含Bloc类型的上下文调用blocprovider.of()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是扑朔迷离的新手,我想使用BLoc实现一个简单的Login屏幕.没有构建错误,但在运行时收到以下错误

I am new to flutter and i wanted to implement a simple Login screen using BLoc. There is no build error but in runtime the following error is received

用不包含LoginBloc类型的Bloc的上下文调用的blocprovider.of()""

"blocprovider.of() called with a context that does not contain a Bloc of type LoginBloc"

我的代码

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 ?

Did you "provide" the LoginBloc in a widget above LoginForm?

此错误意味着没有父窗口小部件引用创建的 LoginBloc .

This error means that there is no parent widget referencing a created 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)`
  }
)

这篇关于Flutter:使用不包含Bloc类型的上下文调用blocprovider.of()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆