簡體   English   中英

如何在顫動中禁用按鈕

[英]how to make a button disable in flutter

我正在嘗試創建個人資料表單。 我想根據驗證禁用或啟用按鈕。 我試圖檢查表單的當前狀態是否已驗證。 它工作正常,但是當我在其中一個 textFormField 上鍵入時,我在所有 textFormField 上都收到錯誤消息。 這是我正在工作的代碼。

import 'dart:html';

import 'package:flutter/material.dart';




class ProfileForm extends StatefulWidget {
  const ProfileForm({Key? key}) : super(key: key);

  @override
  State<ProfileForm> createState() => _ProfileFormState();
}

class _ProfileFormState extends State<ProfileForm> {
  final _formKey = GlobalKey<FormState>();

  DateTime selectedDate = DateTime.now();
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _dobController = TextEditingController();
  final _currentLocationController = TextEditingController();
  final _locationIndiaController = TextEditingController();
  bool btndisable = false;

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

  @override
  Widget build(BuildContext context) {
    RegExp emailValidator = RegExp(
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');

    return Scaffold(

      body: SingleChildScrollView(
          child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(

          key: _formKey,
          onChanged: () {
            notdisbled();
           
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Let’s create a profile for you",
                style: AppTextStyleSecondary.headline2sec,
              ),
              const SizedBox(
                height: 12,
              ),
              Padding(
                padding: const EdgeInsets.only(right: 100.0),
                child: Text(
                  "Please enter your personal details",
                  
                ),
              ),
              const SizedBox(
                height: 16,
              ),
              Text("Your name"),
              TextFormField(
                autovalidateMode: AutovalidateMode.onUserInteraction,
                onChanged: (val) {
                 
                },
                validator: (val) {
                  if (val.toString().length < 2) {
                    return "Please enter your name";
                  }
                  return null;
                },
                controller: _nameController,
                decoration: const InputDecoration(
                    isDense: true,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
              ),

              Text(labelText: "Date of Birth"),
              InkWell(
                child: TextFormField(

                  onTap: () {
                    _selectDate(context);
                  },
                  validator: (val) {
                    if (val.toString().isEmpty) {
                      return "This field is required";
                    } else {
                      return null;
                    }
                  },
                  readOnly: true,
                  controller: _dobController,
          
                ),
              ),
          
              Text("Email address"),
              TextFormField(
    
                controller: _emailController,
                onChanged: (val) {},
                autovalidateMode: AutovalidateMode.onUserInteraction,
                validator: (val) {
                  String email = val!.trim();
                  if (emailValidator.hasMatch(email)) {
                    return null;
                  } else {
                    return "Enter valid email address";
                  }
                },
                decoration: const InputDecoration(
                    isDense: true,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
              ),

              Text(labelText: "Your location where you currently live"),
              TextFormField(
               autovalidateMode: AutovalidateMode.onUserInteraction,
                validator: (val) {
                  if (val.toString().isEmpty) {
                    return "This field is required";
                  } else {
                    return null;
                  }
                },
                onChanged: (val) {
         
                },

                controller: _currentLocationController,
            
              ),
              Text("Your location in India"),
              TextFormField(
                autovalidateMode: AutovalidateMode.onUserInteraction,
                validator: (val) {
                  if (val.toString().isEmpty) {
                    return "This field is required";
                  } else {
   

                    return null;
                  }
                },
                onChanged: (val) {},

                controller: _locationIndiaController,
                
              ),
              const SizedBox(
                height: 25,
              ),
              Container(
                width: double.infinity,
                height: 45,
                decoration: BoxDecoration(
                  color: btndisable ? Colors.blue : Colors.red,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: TextButton(
                  onPressed: (){
                    if(_formKey.currentState!.validate()){
                      Navigator.of(context).pushNamedAndRemoveUntil(
                              'HomeScreen', (Route<dynamic> route) => false);
                    }
                  }
                  child: Text("Continue"),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
            ],
          ),
        ),
      )),
    );
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(1970),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
        _dobController.text =
            "${selectedDate.day}/${selectedDate.month}/${selectedDate.year}";
      });
    }
  }

  void notdisbled() {
    if (_formKey.currentState!.validate() == false) {
      setState(() {
        btndisable = false;
      });
    } else {
      setState(() {
        btndisable = true;
      });
    }
  }
}

禁用按鈕更改為:

child: TextButton(
                  onPressed: _formKey.currentState != null && _formKey.currentState.validate() ? () {
                    Navigator.of(context).pushNamedAndRemoveUntil(
                          'HomeScreen', (Route<dynamic> route) => false);
                  }: null,
                  child: AppText(
                      text: "Continue",
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: AppColor.white),
                ),

但是當你使用

formKey.currentState!.validate()

當您鍵入任何內容時,顫振嘗試每次都調用它,以便您的表單小部件在其所有文本字段中運行所有驗證器函數。 所以所有文本字段都會收到錯誤消息是很自然的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM