Flutter 从文本字段中检索值
我有一个带有文本字段和提交按钮的简单表单。我试图从文本字段中检索值,并将其输出到文本小部件中。我正在使用Flutter 从文本字段中检索值,flutter,dart,Flutter,Dart,我有一个带有文本字段和提交按钮的简单表单。我试图从文本字段中检索值,并将其输出到文本小部件中。我正在使用文本编辑控制器。我的代码中缺少了什么 import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Mate
文本编辑控制器
。我的代码中缺少了什么
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
class MyCustomForm extends StatefulWidget {
@override
_MyCustomFormState createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
String _showText = " ";
final _textInputController = TextEditingController();
_onPressed() {
setState(() {
_showText = _textInputController.text;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: Column(
children: <Widget>[
Text("Submitted Text: $_showText"),
// Expanded(
// child: GridView.count(
// crossAxisCount: 4,
// children: getList(),
// ),
// ),
TextField(
controller: _textInputController,
decoration: new InputDecoration(labelText: "Enter a text"),
),
RaisedButton(
onPressed: () => _onPressed,
child: Text("show value"),
),
],
),
);
}
}
导入“包装:颤振/材料.省道”;
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“检索文本输入”,
主页:MyCustomForm(),
);
}
}
类MyCustomForm扩展了StatefulWidget{
@凌驾
_MyCustomFormState createState()=>\u MyCustomFormState();
}
类_MyCustomFormState扩展了状态{
字符串_showText=“”;
final _textInputController=TextEditingController();
_onPressed(){
设置状态(){
_showText=\u textInputController.text;
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“检索文本输入”),
),
正文:专栏(
儿童:[
文本(“提交文本:$\u showText”),
//扩大(
//子项:GridView.count(
//交叉轴计数:4,
//子项:getList(),
// ),
// ),
文本字段(
控制器:_textInputController,
装饰:新输入装饰(labelText:“输入文本”),
),
升起的按钮(
onPressed:()=>\u onPressed,
子项:文本(“显示值”),
),
],
),
);
}
}
您可以尝试改用TextFormField
并将值
传递给_showText变量:
String _showText;
什么是
\u formKey
@Oprimus?这里它是globalkey
的一个变量(但您可以使用任何key
)。是在小部件中保持/保留[State]
的一种方法,如果需要,它将用于在文本字段中进行验证。我假设您想要,因为您的onPressed()
函数正在设置状态。如果您的小部件是无状态的,则不需要它。
_onPressed() {
final form = _formKey.currentState;
setState(() {
form.save() ;
});
}
TextFormField(
decoration: InputDecoration(
labelText: 'Enter a text',
),
onSaved: (value) => _showText,
),
RaisedButton(
onPressed: () => _onPressed,
child: Text("show value"),
),