从文本字段检索值

时间:2019-10-06 00:45:20

标签: flutter dart

我有一个带有文本字段和提交按钮的简单表单。我正在尝试从文本字段中检索值并将其输出到“文本”小部件中。我正在使用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"),
          ),
        ],
      ),
    );
  }
}

1 个答案:

答案 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"),
  ),
相关问题