Flutter 多个小部件在导航表单注册屏幕登录时使用相同的GlobalKey

Flutter 多个小部件在导航表单注册屏幕登录时使用相同的GlobalKey,flutter,authentication,dart,navigation,widget,Flutter,Authentication,Dart,Navigation,Widget,我的代码结构 登记册 -----个人信息飞镖 -----移动式飞镖 登录 成功注册用户后,我尝试从register.dart的子类personal_info.dart导航到login.dart,以便用户可以登录使用该应用程序。但我得到一个错误“多个小部件使用同一个GlobalKey”,当我尝试输入电子邮件/密码时,登录屏幕变黑 这是密码 个人信息飞镖 import 'package:shared_preferences/shared_preferences.dart'; import 'pac

我的代码结构

登记册 -----个人信息飞镖 -----移动式飞镖 登录

成功注册用户后,我尝试从register.dart的子类personal_info.dart导航到login.dart,以便用户可以登录使用该应用程序。但我得到一个错误“多个小部件使用同一个GlobalKey”,当我尝试输入电子邮件/密码时,登录屏幕变黑

这是密码 个人信息飞镖

import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:king_research/extras/constants.dart';
import 'package:king_research/extras/routes.dart';
import 'package:king_research/main_structure.dart';
import 'package:king_research/screens/login.dart';
import 'package:http/http.dart' as http;
class PersonalInfo extends StatefulWidget {
  @override
  _PersonalInfoState createState() => _PersonalInfoState();
}
String errorMessage = "";
String successMessage = "";
bool isRegistered = false;

class _PersonalInfoState extends State<PersonalInfo> {
  String email="";
  String password="";
  String name="";
  String mobile="";


  @override
  final _formKey=GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return    SingleChildScrollView(
        child: SafeArea(

          child: Padding(
            padding: EdgeInsets.fromLTRB(20, 100, 20, 20),

            child:  Form(
              key: _formKey,

              child: Material(
                color: Colors.grey[900],
                child: Column(
                  children: [
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey
                            )
                          ),
                        hintText: "Enter user Name",
                        labelText: "Full name",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color:Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,

                      ),
                      onChanged: (value){
                        name=value;
                        setState(() {});
                      },

                      validator: (value){
                        if(value.isEmpty){
                          return 'User name should not be empty';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey
                              )
                          ),
                          hintText: "userid@gmail.com",
                          labelText: "Email Id",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color:Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                      ),
                      onChanged: (value){
                        email=value;
                        setState(() {});
                      },

                      validator: (value){
                        if(value.isEmpty){
                          return 'Email id should not be empty';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey
                              )
                          ),
                          hintText: "+91-9876543210",
                          labelText: "Mobile number",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color:Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                      ),
                      onChanged: (value){
                        mobile=value;
                        setState(() {});
                      },

                      validator: (value){
                        if(value.isEmpty){
                          return 'Mobile number should not be empty';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      obscureText: true,
                      decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey
                              )
                          ),
                          hintText: "Enter password",
                          labelText: "Password",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color:Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                      ),
                      onChanged: (value){
                        password=value;
                        setState(() {});
                      },

                      validator: (value){
                        if(value.isEmpty){
                          return 'Country name should not be empty';
                        }
                        return null;
                      },
                    ),
                    SizedBox(height: 20,),

                    Container(

                        child: (errorMessage.isNotEmpty)
                            ? Text('Error Msg : ${errorMessage}',
                          style: TextStyle(
                            color: Colors.red,fontWeight: FontWeight.bold
                        ),)
                            : Text('')

                    ),
                    Container(

                        child: (successMessage.isNotEmpty)
                            ? Text('Success Msg : ${successMessage}',
                        style: TextStyle(
                          color: Colors.green[700],fontWeight: FontWeight.bold
                        ),)
                            : Text('')
                    ),
                    SizedBox(height: 20,),

                    ElevatedButton(child: Text("CONTINUE"),
                      onPressed: ()async{

                        register(name, email, mobile, password,context);



                      },
                     style: ButtonStyle(
                       backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
                     ),
                    ),



                  ],
                ),
              ),
            ),


          ),
        ),

      );





  }
}

Future<void> register (String name, String email, String mobile, String password,context) async{
  print('#########################');
  print(name);
  print(email);
  print(mobile);
  print(password);
  print('#########################');
  Constant con = Constant();
  var url = Uri.parse(con.baseURL+"/api/auth/register");
  var response = await http.post(url,body : { 'email' : email, 'password' : password, 'name': name, 'mobile': mobile });
  var res = jsonDecode(response.body);
  print(res);
  if(res['status']){
    isRegistered = true;
    print("isRegistered Value : ${isRegistered}");
    print(res);

    // Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => Structure()));
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context)=>LoginPage()),
            (Route<dynamic>route)=>false);
    successMessage = res['message'];
    print(successMessage);
  }
  else{
    isRegistered = false;
    print("isRegistered Value : ${isRegistered}");
    errorMessage = res['message'];
    print(errorMessage);
  }


}


import'package:shared_preferences/shared_preferences.dart';
进口“包装:颤振/材料.省道”;
导入“package:king_research/extras/constants.dart”;
进口“包装:king_research/extras/routes.dart”;
导入“包:king_research/main_structure.dart”;
导入“package:king_research/screens/login.dart”;
将“package:http/http.dart”导入为http;
类PersonalInfo扩展了StatefulWidget{
@凌驾
_PersonalInfoState createState()=>\u PersonalInfoState();
}
字符串errorMessage=“”;
字符串successMessage=“”;
bool isRegistered=false;
类_PersonalInfoState扩展状态{
字符串email=“”;
字符串密码=”;
字符串名称=”;
字符串mobile=“”;
@凌驾
final _formKey=GlobalKey();
@凌驾
小部件构建(构建上下文){
返回SingleChildScrollView(
儿童:安全区(
孩子:填充(
填充:来自LTRB(20,100,20,20)的边缘设置,
孩子:表格(
键:_formKey,
儿童:材料(
颜色:颜色。灰色[900],
子:列(
儿童:[
TextFormField(
样式:TextStyle(颜色:Colors.white),
装饰:输入装饰(
enabledBorder:OutlineInputBorder(
边界边(
颜色:颜色。灰色,
),
),
聚焦顺序:大纲输入边框(
边界边(
颜色:颜色。灰色
)
),
hintText:“输入用户名”,
labelText:“全名”,
fillColor:Colors.white,
标签样式:文本样式(颜色:Colors.grey),
hintStyle:TextStyle(颜色:Colors.grey),
浮动LabelBehavior:浮动LabelBehavior.always,
),
一旦更改:(值){
名称=值;
setState((){});
},
验证器:(值){
if(value.isEmpty){
返回“用户名不应为空”;
}
返回null;
},
),
大小盒子(
身高:20,
),
TextFormField(
样式:TextStyle(颜色:Colors.white),
装饰:输入装饰(
enabledBorder:OutlineInputBorder(
边界边(
颜色:颜色。灰色,
),
),
聚焦顺序:大纲输入边框(
边界边(
颜色:颜色。灰色
)
),
hintText:“userid@gmail.com",
labelText:“电子邮件Id”,
fillColor:Colors.white,
标签样式:文本样式(颜色:Colors.grey),
hintStyle:TextStyle(颜色:Colors.grey),
浮动LabelBehavior:浮动LabelBehavior.always,
),
一旦更改:(值){
电子邮件=价值;
setState((){});
},
验证器:(值){
if(value.isEmpty){
返回“电子邮件id不应为空”;
}
返回null;
},
),
大小盒子(
身高:20,
),
TextFormField(
样式:TextStyle(颜色:Colors.white),
装饰:输入装饰(
enabledBorder:OutlineInputBorder(
边界边(
颜色:颜色。灰色,
),
),
聚焦顺序:大纲输入边框(
边界边(
颜色:颜色。灰色
)
),
hintText:“+91-9876543210”,
labelText:“手机号码”,
fillColor:Colors.white,
标签样式:文本样式(颜色:Colors.grey),
hintStyle:TextStyle(颜色:Colors.grey),
浮动LabelBehavior:浮动LabelBehavior.always,
),
一旦更改:(值){
移动=价值;
setState((){});
},
验证器:(值){
if(value.isEmpty){
返回“手机号码不应为空”;
}
返回null;
}
import 'dart:convert';
import 'package:king_research/spinner.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:king_research/classesForApi/loading_screen.dart';
import 'package:king_research/extras/constants.dart';
import 'package:king_research/extras/routes.dart';
import 'package:king_research/main_structure.dart';
import 'package:shared_preferences/shared_preferences.dart';

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

String errorMessage = "";
String successMessage = "";
bool isLoggedIn = false;

class _LoginPageState extends State<LoginPage> {
  String email = "";
  String password = "";
  final _formKey = GlobalKey<FormState>();
  bool spinnerLoading=false;

  @override
  void initState(){

    checkAuth(context);
  }

  get generateRoute => null;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateRoute: generateRoute,
      navigatorKey: navigatorKey,
      home: Scaffold(
        backgroundColor: Colors.grey[900],
        appBar: AppBar(
          title: Text(
            'Sign In',
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
          backgroundColor: Colors.grey[900],
        ),
        body: SingleChildScrollView(
          child: SafeArea(
            child: Padding(
              padding: EdgeInsets.fromLTRB(20, 100, 20, 20),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.grey,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.grey)),
                        hintText: "Enter user email",
                        labelText: "email id",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color: Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                      ),
                      onChanged: (value) {
                        email = value;
                        setState(() {});
                      },
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'User email id should not be empty';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      style: TextStyle(color: Colors.white),
                      obscureText: true,
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.grey,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.grey)),
                        hintText: "Enter password",
                        labelText: "User password",
                        fillColor: Colors.white,
                        labelStyle: TextStyle(color: Colors.grey),
                        hintStyle: TextStyle(color: Colors.grey),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                      ),
                      onChanged: (value) {
                        password = value;
                        setState(() {});
                      },
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'User password should not be empty';
                        }

                        return null;
                      },
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Container(
                        color: Colors.redAccent,
                        child: (errorMessage.isNotEmpty)
                            ? Text(errorMessage)
                            : Text('')),
                    SizedBox(
                      height: 20,
                    ),
                    ElevatedButton(
                      child: Text("SIGN IN"),
                      onPressed: () {

                        login(email, password, context);


                          if (_formKey.currentState.validate()) {
                            setState(() {
                              spinnerLoading=true;
                            });
                            if (isLoggedIn == true) {
                              setState(() {
                                spinnerLoading=false;
                              });
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => Structure()),
                            );
                          }
                        }
                      },
                      style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all<Color>(Colors.blue),
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          'Forget Password?',
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Divider(
                      thickness: 1,
                      height: 1,
                      color: Colors.grey,
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    InkWell(
                      onTap: () {
                        Navigator.pushNamed(context, MyRoutes.registerRoute);
                      },
                      child: Text(
                        "Don't have an account? Sign Up",
                        style: TextStyle(color: Colors.white, fontSize: 18),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Future<void> login(String email, String password, context) async {
  Constant con = Constant();
  print('#########################');
  print(email);
  print(password);
  // email = "charulmehta24@gmail.com";
  print('#########################');
  var postBody = jsonEncode({'email': email, 'password': password});
  var url = Uri.parse(con.baseURL + "/api/auth/login");
  var response =
      await http.post(url, body: {'email': email, 'password': password});
  print('#########################');
  print(response.body);
  var res = jsonDecode(response.body);
  if (res['status']) {
    isLoggedIn = true;
    print("isLoggedIn Value : ${isLoggedIn}");
    print(res);
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context)=>Structure()),
            (Route<dynamic>route)=>false);


    await adStringToSF(res['data']['accessToken']);

    var sharedPFData = await getStringValueSF();
    print(sharedPFData);
  } else {
    isLoggedIn = false;

    print("isLoggedIn Value : ${isLoggedIn}");
    errorMessage = res['message'];
  }

  // print(response.body);
  print('#########################');
}

// To Get Shared Preference Data
Future<String> getStringValueSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String stringValue = prefs.getString('authToken');
  return stringValue;
}

// To Set Shared Perefrence Data
Future<void> adStringToSF(token) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('authToken', token);
}

void checkAuth(context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String authToken = prefs.getString('authToken');
  if(authToken != null){
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context)=>Structure()),
        (Route<dynamic>route)=>false);

  }

}

import 'package:flutter/material.dart';
import 'package:king_research/tab_screens/number_verification.dart';
import 'package:king_research/tab_screens/personal_info.dart';
class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:  DefaultTabController(
          length: 2,

          child: Scaffold(
            backgroundColor: Colors.grey[900],
            appBar: AppBar(
              title: Text(
                  "Sign Up",
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                ),
              ),
              backgroundColor: Colors.grey[900],

              bottom: TabBar(

                tabs: [
                  Text('Personal Info', style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600
                  ),),
                  Text('Number varification', style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600
                  ),)
                ],
              ),
            ),
            body: TabBarView(

              children: [
                PersonalInfo(),
                NumberVarification()
              ],
            ),
          ),
        ),
      );

  }
}

  final GlobalKey<FormState> _formKey =
      new GlobalKey<FormState>(debugLabel: '_loginFormKey');