How can I give focus to a TextField without any text being selected in flutter?

118 Views Asked by At

When I perform requestFocus() on a TextField that has any text, the text will become selected.
What I want is to have the cursor at the end, without selecting any text.

How can I give focus to a TextField without any text being selected in flutter?
image

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  final focusNode1 = FocusNode();
  final controller1 = TextEditingController()..text = '111';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Material(
        child: Column(
          children: [
            TextButton(
              onPressed: () {
                focusNode1.requestFocus();
              },
              child: Text("SetFocus"),
            ),
            TextField(
              focusNode: focusNode1,
              controller: controller1,
            ),
          ],
        ),
      ),
    );
  }
}

I can realize the cursor to the end after it is drawn by following code.
However, for a moment I can see the text being selected.

Isn't there a better way?

                focusNode1.requestFocus();
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  controller1.selection = TextSelection.collapsed(offset: controller1.text.length);
                });
0

There are 0 best solutions below