我想传递一个变量名作为函数参数,但它似乎不起作用:我的变量的内容保持不变。
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(),
],
);
}
提前致谢!
答案 0 :(得分:0)
我认为您需要像 dart 的 Map
这样的键值解决方案答案 1 :(得分:0)
这里有很多事情需要澄清,例如:
TextField
的指南,请查看食谱here 和 here。您可以在此处进行设置:
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,
);
}
}
如果这就是你所需要的..