Kagimura
Kagimura

Reputation: 417

Retrieving value from text field

I have a simple form with a text field and a submit button. I'm trying to retrieve the value from the text field and output it in a Text widget. I'm using TextEditingController. What am I missing in my code?

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"),
          ),
        ],
      ),
    );
  }
}

Upvotes: 0

Views: 60

Answers (1)

Oprimus
Oprimus

Reputation: 1898

You could try using a TextFormField instead and passing the value to the _showText variable:

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"),
  ),

Upvotes: 1

Related Questions