Reputation: 2613
Hi I was wondering if it was possible in flutter to programatically open up the keyboard as well as have the cursor and the textfield ready type straight away.
I already know how to pull up the keyboard
FocusScope.of(context).requestFocus(FocusNode());
But I also need to know how to make the textfield ready to type without the users having to tap the textfield. as in
Lets say I have a textfield:
TextField(
controller: textEditingController,
);
I would like to use code to the effect below so that the user dons't have to tap the textfield
textEditingController.openTextField()//Pseudo code
: Edit -----------------------------------
Bit bad of me but I forgot to add the focus node as a parameter on the textfield
Within your class add
final FocusNode _focusNode = FocusNode();
then add to textfield
TextField(
...
focusNode:_focusNode,
...
);
then call it by running
_focusNode.requestFocus();
Upvotes: 9
Views: 5944
Reputation:
full code below, this code make TextField
focused and opens the keyboard
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(home: HomeScreen());
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final TextEditingController _controller = TextEditingController();
final FocusNode _focusNode = FocusNode();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNode.requestFocus();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: TextField(
focusNode: _focusNode,
controller: _controller,
),
);
}
@override
void dispose() {
_focusNode.dispose();
_controller.dispose();
super.dispose();
}
}
Upvotes: 2
Reputation: 34180
StatefulWidget
will come to rescue. WidgetsBinding
have addPostFrameCallback()
method that will be called once Widget Build()
is peformed. so inside initState()
we can do magic with it
With nextFocus:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
FocusScope.of(context).nextFocus();
});
}
TextField Code:
Scaffold(
appBar: AppBar(),
body: TextField(),
),
With FocusNode :
FocusNode focusNode = FocusNode();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(focusNode);
});
}
Use:
Scaffold(
appBar: AppBar(),
body: TextField(
focusNode: focusNode,
),
),
Output:
Upvotes: 0
Reputation: 2519
First, you need to define FocusNode variable and assign it to your TextField like this :
//in header class
FocusNode focusNode = FocusNode ();
//in build method
TextField(focusNode: focusNode,)
Then use this code:
FocusScope.of(context).requestFocus(focusNode);
Upvotes: 7