gpt4 book ai didi

flutter - TextFormField 值消失以及如何获取 textFormField 值?

转载 作者:IT王子 更新时间:2023-10-29 07:18:41 28 4
gpt4 key购买 nike

请帮助解决我的 2 个问题。

第一个问题。为什么文本值消失?[已修复] @Praneeth我添加了动图 please click

我的代码就是这样用的

在我的小部件中,我调用了 UsernameTextField 类。小部件看起来像这样,

Widget build > WillPopScope > Scaffold > Form > ListView > children> Container (below container) I added key: _scaffoldKey, and key: formKey, also.

 Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.only(top: 30.0),
child: UsernameTextField(),
),

用户名文本字段()

class UsernameTextField extends StatefulWidget{
final usernameController = TextEditingController();
@override
State<StatefulWidget> createState() {
return UsernameTextFieldState(usernameController);
}
}

class UsernameTextFieldState extends State<UsernameTextField>{
final usernameController;
UsernameTextFieldState(this.usernameController);

@override
Widget build(BuildContext context) {
return AppTextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
labelText: AppTranslations.of(context)
.text("loginpage_username"),
),
myController: usernameController,
textInputType: TextInputType.emailAddress
);
}
}

AppTextField() 类,我将这个类用于我的每个 TextField 小部件

class AppTextField extends StatelessWidget {
final InputDecoration decoration;
final myController;
final TextInputType textInputType;
AppTextField({
this.decoration,
this.myController,
this.textInputType
});

@override
Widget build(BuildContext context) {
return TextFormField(
controller: myController,
keyboardType: textInputType,
textAlign: TextAlign.left,
decoration: decoration
);}}

第二个问题。如何获取textField的值?

在我调用的按钮onPressed()方法中,我调用了validation方法,但是结果是null

usernameValidation(){
String username = UsernameTextField().usernameController.text;
print(username);
}

最佳答案

首先通过扩展为 StatefulWidget 而不是 StatelessWidget 将 UsernameTextField 类转换为 Stateful 类。然后你可以从 usernameController.text

获取值

更新

    class UsernameTextField extends StatefulWidget{
final usernameController = TextEditingController();
UsernameTextField(this.usernameController)

@override
State<StatefulWidget> createState() {
return UsernameTextFieldState(usernameController);
}
}

class UsernameTextFieldState extends State<UsernameTextField>{

@override
Widget build(BuildContext context) {
return AppTextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
labelText: AppTranslations.of(context)
.text("loginpage_username"),
),
myController: widget.usernameController,
textInputType: TextInputType.emailAddress
);
}
}

关于flutter - TextFormField 值消失以及如何获取 textFormField 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471639/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com