How To Get Text Input Value On Button Click In Flutter App

admin_img Posted By Bajarangi soft , Posted On 30-10-2020

TextField widget in flutter has controller argument which controls the entered edited text. We have to create a TextEditingController() object which controls the controller. In flutter we cannot directly retrieve Text Input value, we have to get this using controller object. We would use StatefulWidget widget in our tutorial in order to get value from Text Input because we want to show the value in Text widget.

How To Get Text Input Value On Button Click In Flutter App

Get Text Input Value On Button Click
Complete Code For Get Text Input Value On Button Click In Flutter
main.dart

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _textInputController = TextEditingController();
  String _showText = "";

  _onPressed() {
    setState(() {
      _showText = _textInputController.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.amber[900],
          title: Text('Text Input Value'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text("Submitted Text: $_showText"),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextField(
                  controller: _textInputController,
                  autocorrect: true,
                  decoration: InputDecoration(
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        borderSide: BorderSide(color: Colors.black26),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        borderSide: BorderSide(color: Colors.grey),
                      ),
                      contentPadding: EdgeInsets.all(15),
                      hintText: 'Enter Text here',
                      hintStyle: TextStyle(color: Colors.black45, fontSize: 15),
                  ),
                ),
              ),
              RaisedButton(
                color: Colors.amber[900],
                onPressed: _onPressed,
                child: Text('Submit',style: TextStyle(color: Colors.white),),
              )
            ],
          ),
        ));
  }
}

Related Post