Flutter错误:“上下文!= null”:不正确

时间:2020-08-20 08:46:33

标签: flutter flutter-layout

在flutter应用程序中使用SnackBar时,出现了上下文错误。所以我为此使用了一个buildcontext ctx,现在出现了这个错误。任何提示如何解决此问题?

这是我遇到的错误:-

E / flutter(30109):[错误:flutter / lib / ui / ui_dart_state.cc(157)]未处理的异常:'package:flutter / src / material / scaffold.dart':失败的断言:1452行pos 12 :'context!= null':不正确。

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(包装:flutter / src / material / scaffold.dart:1452:12) E / flutter(30109):#3 _RegistrationScreenState._trySubmit(软件包:flash_chat / screens / registration_screen.dart:44:18) E / flutter(30109):

-这是.dart文件。

    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 个答案:

答案 0 :(得分:0)

用Builder包裹脚手架的主体

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

在_trySubmit函数中传递上下文

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

您的trySubmit应该看起来像这样

void _trySubmit(scaffContext) async {

然后将这个scaffContext传递给Scaffold.of(scaffContext)。用scaffContext替换ctx。

答案 1 :(得分:0)

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