Flutter TextFormField上的重建问题

dgjrabp2  于 2023-08-07  发布在  Flutter
关注(0)|答案(1)|浏览(194)

当我对textformfield进行更改时,从该类生成的所有textform字段都将重新生成。
你好,我正在开发一个flutter项目。我创建了一个自定义的textformfield小部件。我从外部获取一个bool值。如果这个bool变量为true,我想设置相关自定义textformfield的晦涩文本。但问题是:我有5自定义textformfields在我的屏幕上。当我从这些自定义textformfields中单击bool值true时,屏幕上的所有自定义textformfields都将重新构建,即使我为它们提供了不同的键值。这对我来说是个大问题。我该如何解决这个问题?简而言之,我如何确保我创建的其他TextFormField不会处理这种更改(而不是重新构建)

nkcskrwz

nkcskrwz1#

小工具:

import 'package:flutter/material.dart';
import 'package:oneloc_widgets/core/constants/icons.dart';
import 'package:oneloc_widgets/core/functions/valid_controll.dart';

enum CustomTextFFEnum { password, phone, digit, username, email }

mixin CustomTextFFType {
  static const username = CustomTextFFEnum.username;
  static const email = CustomTextFFEnum.email;
  static const password = CustomTextFFEnum.password;
  static const phone = CustomTextFFEnum.phone;
  static const digit = CustomTextFFEnum.digit;
}

class CustomTextFF extends StatefulWidget {
  bool isSecure;
  final GlobalKey formKey;
  bool _isFocused = false;
  bool isValid = true;
  bool validateError;
  bool validateFinish;
  TextEditingController? controller;
  String? hintText;
  CustomTextFFEnum? customTextFFType;
  CustomTextFF({
    super.key,
    this.isSecure = false,
    required this.formKey,
    this.validateFinish = false,
    this.validateError = false,
    this.customTextFFType,
    this.hintText,
    this.controller,
  });

  @override
  State<CustomTextFF> createState() => CustomTextFFState();
}


class CustomTextFFState extends State<CustomTextFF> {
  final FocusNode _textFieldFocus = FocusNode();

  Widget? Function({String? val, required BuildContext context})? validFunction;

  @override
  void initState() {
    super.initState();
    _textFieldFocus.addListener(() {
      setState(() {
        widget._isFocused = _textFieldFocus.hasFocus;
      });
    });

    switch (widget.customTextFFType) {
      case CustomTextFFEnum.username:
        validFunction = usernameControll;
        break;
      case CustomTextFFEnum.email:
        validFunction = emailControll;
        break;
      case CustomTextFFEnum.password:
        validFunction = passwordControll;
        break;
      case CustomTextFFEnum.phone:
        validFunction = phoneControll;
        break;
      default:
    }
  }

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

  @override
  Widget build(BuildContext context) {
    print("Build");
    return Padding(
      padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
      child: Column(children: [
        TextFormField(
          autovalidateMode: AutovalidateMode.onUserInteraction,
          key: widget.formKey,
          obscureText: widget.isSecure ? true : false,
          controller: widget.controller,
          validator: (value) {
            return validatorFunction(value, context);
          },
          onChanged: onChangedFuction,
          decoration: customInputDecoration(context),
          focusNode: _textFieldFocus,
        ),
        if (!widget.isValid)
          validFunction!(context: context, val: widget.controller!.text) ??
              Container()
      ]),
    );
  }

  InputDecoration customInputDecoration(BuildContext context) {
    return InputDecoration(
            fillColor: widget.validateError == true
          ? Colors.transparent
          : widget.validateFinish
              ? Colors.blue
              : Colors.red,
      filled: true,
      enabled: true,
    );
  }

  void onChangedFuction(value) {
    setState(() {
      widget.isValid = validFunction == null;
      widget.validateError =
          validFunction!(context: context, val: value) != null;
      !widget.validateError ? widget.validateFinish = true : null;
      
    });
  }

  String? validatorFunction(String? val, BuildContext context) {
    if (val != null) {
      return validFunction!(context: context, val: val) == null
          ? null
          : "error";
    } else {
      return null;
    }
  }

  void changeLoading() {
    setState(() {
      widget.isSecure = !widget.isSecure;
    });
  }
}

字符串
浏览:

import 'package:flutter/material.dart';
import 'package:oneloc_widgets/core/widgets/custom_text_form_field.dart';

class TestPage extends StatefulWidget {
  const TestPage({super.key});

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  final List<GlobalKey<CustomTextFFState>> _formKeys = [];
  @override
  void initState() {
    super.initState();

    _formKeys.add(GlobalKey<CustomTextFFState>());
    _formKeys.add(GlobalKey<CustomTextFFState>());
    _formKeys.add(GlobalKey<CustomTextFFState>());
    _formKeys.add(GlobalKey<CustomTextFFState>());
  }

  final TextEditingController _emailController = TextEditingController();

  final TextEditingController _usernameControler = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

//test
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: Center(
          child: SingleChildScrollView(
        child: Column(
          children: [
            Form(
                child: Column(
              children: [
                CustomTextFF(
                  formKey: _formKeys[0],
                  customTextFFType: CustomTextFFType.email,
                  controller: _emailController,
                  hintText: "Email",
                ),
                CustomTextFF(
                  formKey: _formKeys[2],
                  customTextFFType: CustomTextFFType.username,
                  controller: _usernameControler,
                  hintText: "Username",
                ),
                const FloatingActionButton(onPressed: null),
                CustomTextFF(
                  isSecure: true,
                  formKey: _formKeys[3],
                  customTextFFType: CustomTextFFType.password,
                  controller: _passwordController,
                  hintText: "Password",
                ),
              ],
            )),
          ],
        ),
      )),
    );
  }
}


我的问题是,当我点击底部的textformfield,我的textformfields与填充颜色黄色的顶部变成默认颜色(蓝色)。

相关问题