Reputation: 609
I have a login page with a UID and PWD TextField. UID, once provided is stored in shared preferences. Therefore, whenever the login screen si shown, the focus could be either on the UID TextField (if no UID is provided/stored) or on the PWD TextField (if UID is shown or provided and automatically populated).
The problem I have is that I am trying to set the focus to the correct TextField using:
FocusScope.of(context).requestFocus(_uidFocusNode)
FocusScope.of(context).requestFocus(_pwdFocusNode);
Where the _uidFocusNode and _pwdFocusNode are defined as FocusNodes and attached to the appropriate TextFields via the focusNode property.
Now, I cannot set the focus using the above statements in initState since the Widget has not been built yet. But when I set it in the build method, it causes a rebuild and the field with focus is blinking all the time. Is there a way to set the focus when building a Widget depending on logic? Note that autofocus does not work as expected - I need the cursor to be int he field.
Upvotes: 2
Views: 1782
Reputation: 126654
Sure! You can schedule a function to be called after the build is done using SchedulerBinding.addPostFrameCallback
.
You can simply use it in your initState
:
@override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
FocusScope.of(context).requestFocus(condition ? _pwdFocusNode : _uidFocusNode);
});
}
Make sure to add import 'package:flutter/scheduler.dart';
at the beginning of your file.
Upvotes: 3