I am working on the project where pressing edit button enables Textfield. Now, I want that user will now that textfield is enabled by showing a blinking cursor. Is there anyway to do that?
CodePudding user response:
To focus a TextField
you can give it a FocusNode
and request focus on that. An example:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
bool textFieldEnabled = false;
late FocusNode myFocusNode;
@override
void initState() {
super.initState();
myFocusNode = FocusNode();
}
@override
void dispose() {
myFocusNode.dispose();
super.dispose();
}
void setTextFieldEnabled() {
setState(() {
textFieldEnabled = true;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
myFocusNode.requestFocus();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
TextButton(onPressed: setTextFieldEnabled, child: const Text('enable')),
TextField(enabled: textFieldEnabled, focusNode: myFocusNode)
]));
}
}
Note, at first I though you could just call myFocusNode.requestFocus();
after changing textFieldEnabled
, but that didn't seem to work. Putting it in a WidgetsBinding.instance.addPostFrameCallback
seemed to solve that.