方法 'save' 在 null 上被调用。接收者:空尝试调用:save()

时间:2021-06-05 07:19:47

标签: flutter dart

当我们点击手势检测器时,我试图将表单字段的值设置为“用户名”变量。 'username' 变量中的文本正在使用 Navigator.pop() 方法从 create_account.dart 传回函数 createUserInFirestore() 到 home.dart

我也附上代码供参考

这是我的 create_account.dart 文件

class CreateAccount extends StatefulWidget {
  @override
  _CreateAccountState createState() => _CreateAccountState();
}

class _CreateAccountState extends State<CreateAccount> {
  final GlobalKey<FormState> _formkey =GlobalKey<FormState>();
  String username="";

  submit(){
    _formkey.currentState.save();
    Navigator.pop(context,username);
  }

  @override
  Widget build(BuildContext parentContext) {
    return Scaffold(
      appBar: header(context,titleText: "Set up your profile"),
      body: ListView(
        children: <Widget>[
          Container(
            child:Column(
              children:<Widget> [
                Padding(
                    padding: EdgeInsets.only(top: 25.0),
                child: Center(
                  child: Text("Create a username", style: TextStyle(fontSize: 25.0),),
                ),
                ),
                Padding(padding: EdgeInsets.all(16.0),
                child: Container(
                  child:Form(
                    key: _formkey,
                    child: TextFormField(
                      onSaved: (val)=>username=val,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: "Username",
                        labelStyle: TextStyle(fontSize: 15.0),
                        hintText: "Must be at leat 3 characterstics",
                      ),
                    ),
                  ),
                ),
                ),
                GestureDetector(
                  onTap: submit(),
                  child: Container(
                    height:50.0 ,
                    width: 350.0,
                    decoration: BoxDecoration(
                      color: Colors.deepPurpleAccent,
                      borderRadius: BorderRadius.circular(7.0),
                    ),
                    child: Center(
                      child:Text(
                      "Submit", style: TextStyle(
                      color: Colors.white,
                      fontSize: 15.0,
                      fontWeight: FontWeight.bold
                    ),
                    ),
                    ),
                  ),
                )
              ],
            ) ,
          )
        ],
      ),
    );
  }
}

还有 home.dart 文件

final GoogleSignIn googleSignIN = GoogleSignIn();
final DateTime timestamp= DateTime.now();
final userRef = FirebaseFirestore.instance.collection('users');

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool isAuth=false;
  PageController pageController;
  int pageIndex=0;


  createUserInFirestore() async{
    final GoogleSignInAccount user = googleSignIN.currentUser;
    final DocumentSnapshot doc = await userRef.doc(user.id).get();
    if(!doc.exists){
      final username = await Navigator.push(context,MaterialPageRoute(builder: context)=>CreateAccount()));

      userRef.doc(user.id).set({
        "id": user.id,
        "username":username,
        "photoUrl":user.photoUrl,
        "email":user.email,
        "displayName": user.displayName,
        "bio":"",
        "timestamp":timestamp
      });
    }
  }

  @override
  void initState(){
    super.initState();
    pageController= PageController();
    googleSignIN.onCurrentUserChanged.listen((account) {
      handleSignIn(account);
    },onError: (err){
      print('Enter signing in: $err');
    });


    googleSignIN.signInSilently(suppressErrors: false)
      .then((account){
        handleSignIn(account);
    }).catchError((err){
      print('Enter signing in: $err');
    });
  }

  handleSignIn(GoogleSignInAccount account){
    if(account!=null){
      createUserInFirestore();
      setState(() {
        isAuth=true;
      });
    }else{
      setState(() {
        isAuth=false;
      });
    }
  }



  @override
  void dispose(){
    pageController.dispose();
    super.dispose();
  }

  login(){
    googleSignIN.signIn();
  }

  logout(){
    googleSignIN.signOut();
  }

  onPageChanged(int pageIndex){
    setState(() {
      this.pageIndex=pageIndex;
    });
  }

  onTap(int pageIndex){
    pageController.animateToPage(
      pageIndex,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInCirc
    );
  }
  Scaffold buildAuthScreen(){
    return Scaffold(
      body: PageView(
        children: <Widget>[
          RaisedButton(
          child: Text('Logout'),
          onPressed: logout,
          ),
        ActivityFeed(),
        Upload(),
        Search(),
        Profile(),
        ],
        controller: pageController,
        onPageChanged: onPageChanged,
        physics: NeverScrollableScrollPhysics(),
      ),
      bottomNavigationBar: CupertinoTabBar(
        currentIndex: pageIndex,
        onTap: onTap,
        activeColor:Theme.of(context).primaryColor,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.whatshot),),
          BottomNavigationBarItem(icon: Icon(Icons.notifications_active),),
          BottomNavigationBarItem(icon: Icon(Icons.photo_camera,size: 35.0,),),
          BottomNavigationBarItem(icon: Icon(Icons.search),),
          BottomNavigationBarItem(icon: Icon(Icons.account_circle),),
        ],
      ),
    );
  }

  buildUnAuthScreen(){
    return Scaffold(
      body:Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomRight,
            colors: [
              Theme.of(context).primaryColor,
              Theme.of(context).accentColor,
            ]
          ),
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text('LS App',
            style: GoogleFonts.dellaRespira(fontSize: 50.0)
            ),
            GestureDetector(
              onTap: login,
              child: Container(
                width: 260.0,
                height: 60.0,
                decoration: BoxDecoration(
                  image:DecorationImage(
                    image: AssetImage('assets/images/google_signin_button.png'),
                    fit: BoxFit.cover
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return isAuth?buildAuthScreen():buildUnAuthScreen();
  }
}

还有日志

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building CreateAccount(dirty, dependencies: [_LocalizationsScope-[GlobalKey#f10cd], _InheritedTheme], state: _CreateAccountState#4c9d8):
The method 'save' was called on null.
Receiver: null
Tried calling: save()

The relevant error-causing widget was: 
  CreateAccount file:///C:/Users/reddy/AndroidStudioProjects/ls_app/lib/pages/home.dart:36:91
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _CreateAccountState.submit (package:ls_app/pages/create_account.dart:16:27)
#2      _CreateAccountState.build (package:ls_app/pages/create_account.dart:52:26)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
...

这是我得到的错误消息,如果您需要更多代码,请告诉我, 感谢您的帮助...!

0 个答案:

没有答案