Get Selection of TextFormField in Flutter

Viewed 338

My goal is to get the selected text of the TextFormField, but each time the button is pressed, the TextFormField loses its focus, and the print in the console shows only a selection between -1 and -1.

It did work a few weeks ago, did the behavior change in the latest release? I am on the stable Flutter channel. (Flutter Channel stable, 2.5.0)

This is my test example:

import 'package:flutter/material.dart';

class Play extends StatefulWidget {
  const Play({Key? key}) : super(key: key);

  @override
  _PlayState createState() => _PlayState();
}

class _PlayState extends State<Play> {
  TextEditingController _controller = TextEditingController();
  FocusNode _node = FocusNode();

  void _onPressed() {
    TextSelection selection = _controller.selection;

    print("selection.start: ${selection.start}");
    print("selection.end: ${selection.end}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextFormField(
            focusNode: _node,
            controller: _controller,
          ),
          ElevatedButton(
            onPressed: _onPressed,
            child: Text("do something"),
          ),
        ],
      ),
    );
  }
}
1 Answers

Since it works fine on mobile, I'd say it's a bug in Flutter, but fear not! Welcome to the world of workarounds and temporary solutionsTM; replace your entire _onPressed method by this:

  int start = -1;
  int end = -1;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() async {
      TextSelection selection = _controller.selection;
      if (selection.start > -1) start = selection.start;
      if (selection.end > -1) end = selection.end;
    });
  }

  void _onPressed() {
    print(start);
    print(end);
  }

Let me know if something is not very clear and I'll be happy to edit the answer with further explanations.

DartPad example

The Flutter community would love you to file a bug report (if it doesn't exist already)! :D

Related