简体   繁体   中英

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. 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"

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 ?

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)`
  }
)

Make sure that LoginForm is under LoginBloc widget tree from dev tools. May be you are using Navigator.push() from the AuthPage to open new login form. If you are doing like this, then loginForm will be rendered as a new page again without LoginPage as a parent. So try to keep LoginForm under LoginScreen .

Your Widget tree should look like below:

--LoginScreen
   --LoginBloc
     --LoginForm

And also make sure that you created LogicBloc as @jack said in first comment:

BlocProvider<LoginBloc>(
  create: (context) => LoginBloc(),
  builder: (context, state) {
    // LoginForm can now use `BlocProvider.of<LoginBloc>(context)`
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM