【问题标题】:The error shows : Multiple widgets used the same GlobalKey错误显示:多个小部件使用相同的 GlobalKey
【发布时间】:2021-07-06 05:34:32
【问题描述】:

我猜错误是我从同一个函数中调用密码和用户名字段! 这是我的整个代码: 我试图修复自己,因为我是一个初学者,它似乎对我不起作用,除了我在这里看到类似的问题,但没有一个是使用函数来分配这些键,所以我无法从中找出我的问题..有没有人能拦住??

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:medic_admin/config/palette.dart';

class loginSignupScreen extends StatefulWidget {
  const loginSignupScreen({Key? key}) : super(key: key);
  @override
  _loginSignupScreenState createState() => _loginSignupScreenState();
}

class _loginSignupScreenState extends State<loginSignupScreen> {
  @override
  bool isMale = true;
  bool isSignupScreen = true;
  bool isRememberMe = false;
  var formKey = new GlobalKey<FormState>();

  void validateAndSave() {
    var form = formKey.currentState;
    if (form!.validate()) {
      print("Form is valid");
    } else {
      print("Form is not valid !");
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Palette.backgroundColor,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              height: 250,
              decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("assets/images/hospitalroom.jpg"),
                    fit: BoxFit.fill),
              ),
              child: Container(
                padding: EdgeInsets.only(top: 90, left: 10),
                color: Color(0xFF3B5999).withOpacity(.60),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    RichText(
                      text: TextSpan(
                        text: " Welcome to ",
                        style: TextStyle(
                          fontSize: 25,
                          letterSpacing: 2,
                          color: Colors.orange[600],
                        ),
                        children: [
                          TextSpan(
                            text: "MeDIC ",
                            style: TextStyle(
                              fontSize: 25,
                              fontWeight: FontWeight.bold,
                              letterSpacing: 2,
                              color: Colors.orange[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      isSignupScreen
                          ? "  Sign up to continue"
                          : "  Log in to continue",
                      style: TextStyle(
                        fontSize: 15,
                        letterSpacing: 1,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          //############ Main container for login and signup field ############
          Positioned(
            top: 200,
            bottom: 100,
            child: AnimatedContainer(
              duration: Duration(milliseconds: 700),
              padding: EdgeInsets.all(10),
              height: 380,
              width: MediaQuery.of(context).size.width - 40,
              margin: EdgeInsets.symmetric(horizontal: 20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(25),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 15,
                    spreadRadius: 5,
                  ),
                ],
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            isSignupScreen = false;
                          });
                        },
                        child: Column(
                          children: [
                            Text(
                              " LOGIN ",
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: !isSignupScreen
                                    ? Palette.activeColor
                                    : Palette.textColor1,
                              ),
                            ),
                            if (!isSignupScreen)
                              Container(
                                margin: EdgeInsets.only(top: 3),
                                height: 2,
                                width: 55,
                                color: Colors.orange,
                              ),
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            isSignupScreen = true;
                          });
                        },
                        child: Column(
                          children: [
                            Text(
                              " SIGN UP ",
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: isSignupScreen
                                    ? Palette.activeColor
                                    : Palette.textColor1,
                              ),
                            ),
                            if (isSignupScreen)
                              Container(
                                margin: EdgeInsets.only(top: 3),
                                height: 2,
                                width: 55,
                                color: Colors.orange,
                              ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  if (isSignupScreen) buildSignupScreen(),
                  if (!isSignupScreen) buildLoginScreen(),
                ],
              ),
            ),
          ),

          //########### Submit button ############
          Positioned(
            top: 480,
            left: 0,
            right: 0,
            child: Center(
              child: Container(
                alignment: Alignment.center,
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(50),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 5,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Center(
                  child: FloatingActionButton(
                    onPressed: validateAndSave,
                    backgroundColor: Colors.orange,
                    splashColor: Colors.white,
                    child: Text("OK"),
                  ),
                ),
              ),
            ),
          ),

          //########### Logo blooray ###########
          Positioned(
            top: MediaQuery.of(context).size.height - 75,
            left: 5,
            right: 0,
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                children: [
                  Center(
                    child: Image(
                      image: AssetImage("assets/images/blooraylogo1.png"),
                      width: 500,
                      height: 50,
                    ),
                  ),
                ],`enter code here`
              ),
            ),
          ),
        ],
      ),
    );
  }

  //############# Login Window ############
  Container buildLoginScreen() {
    return Container(
      margin: EdgeInsets.only(top: 50),
      child: Column(
        children: [
          buildTextField(
            MdiIcons.phone,
            "Phone",
            false,
            true,
          ),
          buildTextField(
            MdiIcons.lock,
            "Password",
            true,
            false,
          ),
        ],
      ),
    );
  }

  //############# Sign Up Window ############
  Container buildSignupScreen() {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: [
          buildTextField(
            MdiIcons.account,
            "User Name",
            false,
            false,
          ),
          buildTextField(
            MdiIcons.phone,
            "Phone",
            false,
            true,
          ),
          buildTextField(
            MdiIcons.lock,
            "Password",
            true,
            false,
          ),
        ],
      ),
    );
  }

  //##########TextField##########

  Widget buildTextField(
      IconData icon, String hintText, bool isPassword, bool isFon) {
    return Padding(
      padding: const EdgeInsets.only(top: 10.0),
      child: new Form(
        key: formKey,
        child: TextFormField(
          validator: (value) =>
              value!.isEmpty ? "Field cannot be empty !" : null,
          obscureText: isPassword,
          keyboardType: isFon ? TextInputType.number : TextInputType.text,
          decoration: InputDecoration(
            prefixIcon: new Icon(
              icon,
              color: Palette.iconColor,
            ),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Palette.textColor1),
              borderRadius: BorderRadius.circular(35),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Palette.textColor1),
              borderRadius: BorderRadius.circular(35),
            ),
            contentPadding: EdgeInsets.all(10),
            hintText: hintText,
            hintStyle: TextStyle(
              fontSize: 14,
              color: Palette.textColor1,
            ),
          ),
        ),
      ),
    );
  }
}

我猜错误是我从同一个函数中调用密码和用户名字段!!!

【问题讨论】:

  • 总是尝试分享MVE,你为什么恐慌?

标签: flutter dart


【解决方案1】:

我有你的问题..你犯了一个小错误。您在 buildTextField 函数中添加了一个“表单”小部件。所以你调用你的函数 3 次,每次它都会用相同的键创建一个新的 Form 实例。

解决方案:从 buildtextField 函数中删除“表单”小部件并将其包装在外部容器中,如下所示:

  1. 从 buldTextField 中移除

    Widget buildTextField(
      IconData icon, String hintText, bool isPassword, bool isFon) {
        return Padding(
          padding: const EdgeInsets.only(top: 10.0),
            child: TextFormField(
              validator: (value) =>
                  value!.isEmpty ? "Field cannot be empty !" : null,
              obscureText: isPassword,
              keyboardType: isFon ? TextInputType.number : TextInputType.text,
              decoration: InputDecoration(
                prefixIcon: new Icon(
                  icon,
                  color: Palette.iconColor,
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Palette.textColor1),
                  borderRadius: BorderRadius.circular(35),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Palette.textColor1),
                  borderRadius: BorderRadius.circular(35),
                ),
                contentPadding: EdgeInsets.all(10),
                hintText: hintText,
                hintStyle: TextStyle(
                  fontSize: 14,
                  color: Palette.textColor1,
                ),
              ),
            ),
        );
      }
    }
    
  2. 把它包在外面的容器里

      Form buildSignupScreen() {
        return Form(
         key_ _formKey
          child: Container(
    margin: EdgeInsets.only(top: 10),
        child : Column(
            children: [
              buildTextField(
                MdiIcons.account,
                "User Name",
                false,
                false,
              ),
              buildTextField(
                MdiIcons.phone,
                "Phone",
                false,
                true,
              ),
              buildTextField(
                MdiIcons.lock,
                "Password",
                true,
                false,
              ),
            ],
          ),
         )
        );
      }
    

Forms in flutter的使用示例 有什么问题请告诉我

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 2018-09-26
    • 1970-01-01
    • 2019-06-07
    • 2020-10-01
    • 1970-01-01
    • 2021-10-13
    • 2021-08-26
    • 2023-03-04
    相关资源
    最近更新 更多