i have textField and triger the focus by button, but when i dismis the keyboard and i try to click the button for second time the keyboard is does not showing up, because the textfield still focused
onTap: () {
FocusScope.of(context).requestFocus(controller.textFieldFocus);
},
CodePudding user response:
I think I found a working solution, (currently only tested on android emulator).
This is a small working example:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late FocusNode node;
@override
void initState() {
super.initState();
node = FocusNode();
}
@override
void dispose() {
node.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Focus Demo'),
actions: [
TextButton(
onPressed: () {
node.unfocus();
WidgetsBinding.instance?.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(node);
});
},
child: Text(
'Focus',
style: Theme.of(context).primaryTextTheme.bodyText1,
),
),
],
),
body: TextField(
focusNode: node,
),
),
);
}
}
I was able to get it working by adding a delay between the unfocusing and refocusing using WidgetsBinding.instance?.addPostFrameCallback
.
In your case that should translate to something like this:
onTap: () {
controller.textFieldFocus.unfocus();
WidgetsBinding.instance?.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(controller.textFieldFocus);
});
},