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