方法“ setState”在null上被调用。 E / flutter(13218):接收者:null E / flutter(13218):尝试调用:setState(Closure:()=> Null)

时间:2019-08-09 11:12:13

标签: flutter dart

我的目标是在Firebase中建立注册。但是,当我按下包含注册功能的按钮时,什么也没有发生,并且收到此错误:

E/flutter (13218): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'setState' was called on null.
E/flutter (13218): Receiver: null
E/flutter (13218): Tried calling: setState(Closure: () => Null)

与firebase的集成正在运行,可能问题出在无法获取数据的textformfield上...

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cruke_app/main.dart';
import 'package:cruke_app/ui/login.dart';

class CrukeRegister extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Register(),
    );
  }
}

class Register extends StatefulWidget {
  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  String _email, _password, _passwordConfirm, _displayName;
  final formKey = new GlobalKey<FormState>();
  bool _autoValidate = false;
  final FirebaseAuth auth = FirebaseAuth.instance;
  bool _loading = false;
  PersistentBottomSheetController _sheetController;
  final scaffoldKey = new GlobalKey<ScaffoldState>();

  /* @override
  void initState() {
    super.initState();
  } */

  Widget buildTextField(double width, String text, IconData icon, bool obscureText, String isEmpty, String _saved, bool _autoValidate){

    return Container(
      margin: EdgeInsets.only(bottom: 15),
      width: width * 0.9,
      child: TextFormField(
        validator: (input) => input.isEmpty ? isEmpty : null,
        onSaved: (input) => _saved = input,
        autovalidate: _autoValidate,
        obscureText: obscureText,
        decoration: InputDecoration(
          suffixIcon: Padding(
            padding: EdgeInsetsDirectional.only(end: 12.0),
            child: Icon(icon, color: Colors.red),
          ), 
          hintText: text,
          hintStyle: TextStyle(color: Colors.redAccent, fontSize: 15.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(30.0),
            borderSide: BorderSide(
              width: 5.0,
              color: Colors.redAccent,
            ),
          ), 
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return Scaffold(
      key: scaffoldKey,
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Center(
              child: Container(
                margin: EdgeInsets.only(top: height * 0.025),
                child: Image.asset("images/logo_vertical.png", width: width * 0.5),
              ),
            ),
            Form(
              key: formKey,
              autovalidate: _autoValidate,
              child: Column(
                children: <Widget>[
                  buildTextField(width, "Digite seu nome", Icons.person, false, "Por favor, digite seu nome!", _displayName, _autoValidate),
                  buildTextField(width, "Digite seu e-mail", Icons.email, false, "Por favor, digite seu e-mail!", _email, _autoValidate),
                  buildTextField(width, "Digite sua senha", Icons.lock, true, "Por favor, digite sua senha!", _password, _autoValidate),
                  buildTextField(width, "Confirme sua senha", Icons.lock, true, "Por favor, confirme sua senha!", _passwordConfirm, _autoValidate),
                  Container(
                    height: height * 0.09,
                    width: width * 0.9,
                    padding: EdgeInsets.only(top: 10.0),
                    child: RaisedButton.icon(   
                      onPressed:
                        _validateSubmitRegister,
                        //Navigator.push(
                          //context,
                          //MaterialPageRoute(builder: (context) => Home()),
                        //);

                      label: Text(
                        'Registrar',
                        style: TextStyle(fontSize: 15, color: Colors.white),               
                      ),
                      color: Colors.red,
                      icon: Icon(Icons.account_circle, color: Colors.white),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),

                    ),
                  ),
                ],
              ),
            ),

            Container(
              margin: EdgeInsets.only(top: 15),
              child: Material(
                child: InkWell(
                  onTap: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context) => CrukeLogin()));
                  },
                  child: Text("Já tem uma conta? Faça Login!", style: TextStyle(fontSize: 15, color: Colors.red),),
                ),

              ),

            ),
          ],
        ),
      ),

    );
  }


  void _validateSubmitRegister() async{
    final form = formKey.currentState;
    if (formKey.currentState.validate()) {
      form.save();
      _sheetController.setState(() {
        _loading = true;
      });
      AuthResult result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email, password: _password);
      FirebaseUser user = result.user;
    }

  }
}

1 个答案:

答案 0 :(得分:1)

正如我在您的代码中所看到的,<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="card"> <div class="card-body" id="192.168.1.209:8983_solr"> </div> </div>没有初始化。因此为空。 用_sheetController方法初始化