Flutter Tutorial – How to listen to onChange in TextField? (Android and iOS)

By | December 23, 2018

TextField is a common component in our applications.

In this simple example we will see two ways you can listen to the text changes in a Flutter TextField.

Watch Video Tutorial

1. Using OnChange Event

This one is simple. Just supply the onChange event of the TextField with a onChange callback.

Example

TextField(
   onChanged: (text) {
      print("text $text");
   },
)

2. Using TextEditingController

This is also very simple. Here you have to declare a controller of instance TextEditingController.

final myController = TextEditingController();

// add Listener in InitState()

@override
void initState() {
   super.initState();
   // Start listening to changes
   myController.addListener(textListener);
}

// Use the controller in TextField

TextField(
    controller: myController,
)

Complete Example

import 'package:flutter/material.dart';

class TFChange extends StatefulWidget {

  final String title = "TextField Demo";

  @override
  _TFChangeChange createState() => _TFChangeChange();

}

class _TFChangeChange extends State<TFChange> {

  final myController = TextEditingController();

  textListener() {
    print("Current Text is ${myController.text}");
  }

  @override
  void dispose() {
    super.dispose();
    myController.dispose();
  }

  @override
  void initState() {
    super.initState();
    myController.addListener(textListener);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              onChanged: (text) {
                print("Text $text");
              },
            ),
            TextField(
              controller: myController,
            )
          ],
        ),
      ),
    );
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *