0

我想将变量名作为函数参数传递,但它似乎不起作用:我的变量的内容保持不变。

  Widget Field(String changedValue, String label, bool isTextObscured) {
    return TextFormField(
      decoration: InputDecoration(labelText: label),
      validator: checkFieldEmpty,
      onChanged: (value) {
        setState(() {
          changedValue = value;
        });
      },
      obscureText: isTextObscured,
    );
  }

在这里,我想更改名称为“changedValue”的变量的值。当我直接使用变量名时,它可以工作,但是当我尝试使用参数时,什么也没有发生。这是我使用它的一个例子:

  Widget LoginFields() {
    return Column(
      children: [
        Field(email, Strings.emailLabel, false),
        Field(password, Strings.passwordLabel, true),
        ValidationButton(),
      ],
    );
  }

提前致谢!

4

2 回答 2

0

我认为您需要像 dart's Map这样的键值解决方案

于 2021-06-16T10:23:22.243 回答
0

这里有很多事情需要澄清,比如:

  • setState()是一种方法,必须在StatefullWidget中调用。
  • 如果您创建一个函数,请将其命名为 lowerCamelCase (有效的 dart)。
  • 对于返回一个小部件,更喜欢扩展一个小部件,特别是如果你需要一个状态。
  • TextField如果您在 Flutter 中寻求指南,请在此处此处查看食谱。

在这里你可以如何设置它:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: Center(
          child: Column(
            children: [
              FieldWidget(changedValueInitial: 'email', label: 'labelConstOne'),
              FieldWidget(changedValueInitial: 'password', label: 'labelConstTwo', isTextObscured: true),
              // ValidationButton(),
            ],
          ),
        ),
      ),
    );
  }
}

class FieldWidget extends StatefulWidget {
  String changedValueInitial;
  String label;
  bool isTextObscured;
  FieldWidget({
    Key? key,
    required this.changedValueInitial,
    required this.label,
    this.isTextObscured = false,
  }) : super(key: key);

  @override
  _FieldWidgetState createState() => _FieldWidgetState();
}

class _FieldWidgetState extends State<FieldWidget> {
  late String _changedValue;

  @override
  void initState() {
    super.initState();
    _changedValue = widget.changedValueInitial;
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(labelText: widget.label),
      // validator: yourValidator,
      initialValue: _changedValue,
      onChanged: (value) {
        setState(() {
          _changedValue = value;
        });
      },
      obscureText: widget.isTextObscured,
    );
  }
}

如果这是你需要的..

在此处输入图像描述

于 2021-06-16T10:25:57.870 回答