2

While using SnackBar in my flutter application, I got a context error. so I used a buildcontext ctx for that and now I'm getting this error. Any tips how to fix this?

This is the error I am getting:-

E/flutter (30109): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/material/scaffold.dart': Failed assertion: line 1452 pos 12: 'context != null': is not true.

E/flutter (30109): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39) E/flutter (30109): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5) E/flutter (30109): #2 Scaffold.of (package:flutter/src/material/scaffold.dart:1452:12) E/flutter (30109): #3 _RegistrationScreenState._trySubmit (package:flash_chat/screens/registration_screen.dart:44:18) E/flutter (30109):

- This is .dart file.

    class RegistrationScreen extends StatefulWidget {
      static const String id = 'registration_screen';
      @override
      _RegistrationScreenState createState() => _RegistrationScreenState();
    }
    
    class _RegistrationScreenState extends State<RegistrationScreen> {
      final _auth = FirebaseAuth.instance;
      bool showSpinner = false;
      String email;
      String password;
      String username;
      BuildContext ctx;
    
      final _formKey = GlobalKey<FormState>();
    
      void _trySubmit() async {
        final isValid = _formKey.currentState.validate();
        FocusScope.of(context).unfocus();
        if (isValid) {
          _formKey.currentState.save();
    
          try {
            final newUser = await _auth.createUserWithEmailAndPassword(
                email: email, password: password);
            if (newUser != null) {
              Navigator.pushNamed(context, ChatScreen.id);
            }
          } on PlatformException catch (e) {
            var message = 'An error occurred, Please check your credentials!';
    
            if (e.message != null) {
              message = e.message;
            }
    
            Scaffold.of(ctx).showSnackBar(
              SnackBar(
                content: Text(message),
                backgroundColor: Theme.of(ctx).errorColor,
              ),
            );
          } catch (e) {
            print(e);
          }
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: ModalProgressHUD(
            inAsyncCall: showSpinner,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.0),
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Flexible(
                      child: Hero(
                        tag: 'logo',
                        child: Container(
                          height: 200.0,
                          child: Image.asset('images/logo.png'),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 48.0,
                    ),
                    TextFormField(
                      validator: (value) {
                        if (value.isEmpty || !value.contains('@')) {
                          return 'Please enter a valid Email address.';
                        }
                        return null;
                      },
                      keyboardType: TextInputType.emailAddress,
                      textAlign: TextAlign.center,
                      onSaved: (value) {
                        email = value;
                      },
                      decoration:
                          kTextFieldDecoration.copyWith(hintText: 'Email Address'),
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    TextFormField(
                      validator: (value) {
                        if (value.isEmpty || value.length < 4) {
                          return 'Please enter at least 4 characters.';
                        }
                        return null;
                      },
                      textAlign: TextAlign.center,
                      onSaved: (value) {
                        username = value;
                      },
                      decoration:
                          kTextFieldDecoration.copyWith(hintText: 'Username'),
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    TextFormField(
                      validator: (value) {
                        if (value.isEmpty || value.length < 7) {
                          return 'Password must be at east 7 characters long.';
                        }
                        return null;
                      },
                      obscureText: true,
                      textAlign: TextAlign.center,
                      onSaved: (value) {
                        password = value;
                      },
                      decoration:
                          kTextFieldDecoration.copyWith(hintText: 'Password'),
                    ),
                    SizedBox(
                      height: 24.0,
                    ),
                    RoundedButton(
                      title: 'Register',
                      colour: Colors.blueAccent,
                      onPressed: _trySubmit,
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
2
  • Your ctx is null, didn't set anywhere. Why dont you just use context? you used on FocusScope.of(context).unfocus(); code Commented Aug 20, 2020 at 9:02
  • i used context then i got this error:- E/flutter (13028): No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought. E/flutter (13028): There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of(): Commented Aug 20, 2020 at 9:20

2 Answers 2

1
 First option : Wrap your body with Builder widget like : 
 => Builder : (builder : (context) => yourBody(),), 

 Second option : Create a global key for reaching your context state such as 
 => GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); 
 and Scaffold(key : _scaffoldKey) then use it whereever you want like  

 => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Scaffold key"),));

 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot. the second option worked for me. thanks once again
Failed assertion: : 'context != null': is not true. this error getting.
1

Wrap the body of the Scaffold with Builder

Scaffold(
 body:Builder(builder:(BuildContext context){
   return ModalProgressHUD(...);
  }),
)

Pass the context in your _trySubmit function

           RoundedButton(
                  title: 'Register',
                  colour: Colors.blueAccent,
                  onPressed: (){
                    _trySubmit(context);
                  },
                ),

Your trySubmit should look like this

void _trySubmit(scaffContext) async {

Then pass this scaffContext to the Scaffold.of(scaffContext). Replace ctx with scaffContext.

5 Comments

Now I'm getting this error:-- E/flutter (14138): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Scaffold.of() called with a context that does not contain a Scaffold. E/flutter (14138): No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
Wrap the body of your scaffold with Builder and pass the context from the builder to try submit
same error again . Scaffold.of() called with a context that does not contain a Scaffold.
Are you passing the context from the builder ?
yes I am, thanks anyways Above answer worked for me by creating global key.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.