why text change listener function called multiple time without text change

Issue

I have TextFormField with a text change listener attached to it. But listener function called even when I click on the text field and sometimes even I clicked outside the text field. I’m using flutter 2.5.2 version.

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() {
  runApp(MaterialApp(
    home: SearchView(),
  ));
}

class SearchView extends StatefulWidget {
  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> {
  final textController = TextEditingController();
  final rng = new Random();

  @override
  void initState() {
    this.textController.addListener(this._onTextChanged);
    super.initState();
  }

  void _onTextChanged() {
    print('text changed listener called ${rng.nextDouble()}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Brand'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            TextFormField(
              controller: this.textController,
            ),
          ],
        ),
      ),
    );
  }
}

Solution

This seems to be related to this issue. It’s because the listener actually is not only listening for text changes, but also for focus changes.

What you can do to prevent this and only listen for text changes is using the onChanged() method on the TextFormField like this:

TextFormField(
    onChanged: (String newText) => print('$newText'),
),

Answered By – novas1r1

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

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