Suman Kumar
Suman Kumar

Reputation: 69

Flutter Error: 'context != null': is not true

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,
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }

Upvotes: 2

Views: 4158

Answers (2)

Siddharth jha
Siddharth jha

Reputation: 618

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.

Upvotes: 1

Kadir Bekar
Kadir Bekar

Reputation: 100

 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"),));

 

Upvotes: 1

Related Questions