Flutter select all text on focus

Flutter: Select All Text on Focus

To select all text in a Flutter text input field upon gaining focus, you can make use of the following approach:

    
import 'package:flutter/material.dart';

class MyTextField extends StatefulWidget {
  @override
  _MyTextFieldState createState() => _MyTextFieldState();
}

class _MyTextFieldState extends State<MyTextField> {
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      onTap: () {
        Future.delayed(Duration.zero, () {
          _controller.selection = TextSelection(
            baseOffset: 0,
            extentOffset: _controller.text.length,
          );
        });
      },
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: MyTextField(),
      ),
    ),
  ));
}
    
  

In this example, a custom text field widget (MyTextField) is created. It extends the StatefulWidget class and contains a TextEditingController to manage the text input field.

The onTap property of the TextField is set to a function that uses a Future.delayed to make sure the selection logic runs in the next frame. Then, the TextSelection is set using the _controller to select all text from the beginning (baseOffset: 0) to the end (extentOffset: _controller.text.length).

Finally, the MyTextField widget is displayed within a Scaffold of a MaterialApp in the main function.

Leave a comment