我有一个带有文本字段和提交按钮的简单表单。我正在尝试从文本字段中检索值并将其输出到“文本”小部件中。我正在使用TextEditingController
。我的代码中缺少什么?
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"),
),
],
),
);
}
}
答案 0 :(得分:1)
您可以尝试使用TextFormField
代替,并将value
传递给_showText变量:
String _showText;
...
_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"),
),