多个小部件使用相同的全局键,而导航表单注册屏幕登录

问题描述

我的代码结构

注册 -----personal_info.dart -----mobile_verfiction.dart 登录

我尝试在用户成功注册后从 register.dart 的子类 Personal_info.dart 导航到 login.dart,以便此人可以登录以使用该应用程序。但是我收到错误消息“多个小部件使用了相同的 GlobalKey”,并且当我尝试输入电子邮件/密码时登录屏幕变黑。

enter image description here

这里是代码 个人信息.dart

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",onChanged: (value){
                        email=value;
                        setState(() {});
                      },validator: (value){
                        if(value.isEmpty){
                          return 'Email id should not be empty';
                        }
                        return null;
                      },hintText: "+91-9876543210",labelText: "Mobile number",onChanged: (value){
                        mobile=value;
                        setState(() {});
                      },validator: (value){
                        if(value.isEmpty){
                          return 'Mobile number should not be empty';
                        }
                        return null;
                      },obscureText: true,hintText: "Enter password",labelText: "Password",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],)
                            : Text('')
                    ),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);
  }


}


登录.dart

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,child: Form(
                key: _formKey,decoration: Inputdecoration(
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.grey,focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.grey)),hintText: "Enter user email",labelText: "email id",hintStyle: TextStyle(color: Colors.grey),onChanged: (value) {
                        email = value;
                        setState(() {});
                      },validator: (value) {
                        if (value.isEmpty) {
                          return 'User email id should not be empty';
                        }
                        return null;
                      },labelText: "User password",onChanged: (value) {
                        password = value;
                        setState(() {});
                      },validator: (value) {
                        if (value.isEmpty) {
                          return 'User password should not be empty';
                        }

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

                        login(email,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),Row(
                      mainAxisAlignment: MainAxisAlignment.end,children: [
                        Text(
                          'Forget Password?',fontSize: 12),SizedBox(
                      height: 10,Divider(
                      thickness: 1,height: 1,color: Colors.grey,InkWell(
                      onTap: () {
                        Navigator.pushNamed(context,MyRoutes.registerRoute);
                      },child: Text(
                        "Don't have an account? Sign Up",fontSize: 18),)
                  ],);
  }
}

Future<void> login(String email,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);

  }

}

注册.dart

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
                ),bottom: TabBar(

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

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

  }
}

解决方法

您可以尝试为每个 From 定义不同的键:

static const yourKeyName = const ValueKey('yourKeyName')

或者您可以为每个不同的实例添加调试标签:

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