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