1

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

1 Answer 1

3

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'),
),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.