Get Textfield Text Input Value On Button Onclick Using Flutter

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

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.

Get Textfield Text Input Value On Button Onclick Using Flutter

Get Text Input Value On Button OnClick 
Complete Code For Get Textfield Text Input Value On Button Onclick 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: Scaffold(
          appBar: AppBar(
            backgroundColor: Color(0xFFFFC107),
            title: Text('Get Text Field Text Value'),
            centerTitle: true,
          ),
            body: GetTextFieldValue()
        )
    );
  }
}

class GetTextFieldValue extends StatefulWidget {
  _TextFieldValueState createState() => _TextFieldValueState();
}

class _TextFieldValueState extends State<GetTextFieldValue> {
  final textFieldValueHolder = TextEditingController();
  String result = '';
  getTextInputData(){
    setState(() {
      result = textFieldValueHolder.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                  width: 280,
                  padding: EdgeInsets.all(10.0),
                  child: TextField(
                    controller: textFieldValueHolder,
                    autocorrect: true,
                    decoration: InputDecoration(hintText: 'Enter Some Text'),
                  )
              ),

              RaisedButton(
                onPressed: getTextInputData,
                color: Color(0xFFFFC107),
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('Get Text Field Entered Data'),
              ),

              Padding(
                  padding: EdgeInsets.all(8.0),
                  child :
                  Text("Entered Text is = $result", style: TextStyle(fontSize: 20))
              )

            ],
          ),
        ));
  }
}

Related Post