Keep the TextField focused (or unfocused) when its key changes

Viewed 67

I have a TextField, and sometimes its key must be changed. When the key is changed, I observe that the soft keyboard is removed even if it originally was appeared and the TextField was focused.

The problem is, if the TextField was focused, I hope it is still focused after the key is changed. How can I do this?

Thanks for any suggestions!

Minimal reproducible code:

import 'dart:async';

import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var textFieldKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 3), (_) {
      setState(() => textFieldKey = GlobalKey());
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Column(
          children: [
            Text('current textFieldKey=$textFieldKey'),
            TextField(
              key: textFieldKey,
            ),
          ],
        ),
      ),
    );
  }
}
1 Answers
 final FocusNode _field1Focus = FocusNode();

TextFormField(
                      style: MediumStyle,
                      keyboardType: TextInputType.emailAddress,
                      focusNode: _field1Focus,
                      decoration: InputDecoration(
                          labelText: "Field1",
                          labelStyle: MediumBoldStyle),
                      validator: (val) => null,
                      onSaved: (value) => this._field1 = value,
                      onFieldSubmitted: (term) {
                        _fieldFocusChange(
                            context, _field1Focus, _field2Focus);
                      },
                    ),

  _fieldFocusChange(
      BuildContext context, FocusNode currentFocus, FocusNode nextFocus) {
    currentFocus.unfocus();
    FocusScope.of(context).requestFocus(nextFocus);
  }
Related