I have flutter app and created form screen to get user details. In the form screen when user tap the textfield and it gets focus then keyboard opens need to scroll the textfield user want to seen what he is typing.
To scroll to the text field when it receives focus, you need to use the Scrollable.ensureVisible method. Here is some code to show you how to use it. I hope it helps!
Regards.
class TextFieldVisibility extends StatefulWidget {
const TextFieldVisibility({Key? key}) : super(key: key);
@override
State<TextFieldVisibility> createState() => TextFieldVisibilityState();
}
class TextFieldVisibilityState extends State<TextFieldVisibility> {
final _key1 = GlobalKey<State<StatefulWidget>>();
final _key2 = GlobalKey<State<StatefulWidget>>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
Container(
color: Colors.orange,
height: 1000,
),
TextField(
key: _key1,
onTap: () {
ensureVisibleOnTextArea(textfieldKey: _key1);
},
),
TextField(
key: _key2,
onTap: () {
ensureVisibleOnTextArea(textfieldKey: _key2);
},
)
],
),
));
}
Future<void> ensureVisibleOnTextArea(
{required GlobalKey textfieldKey}) async {
final keyContext = textfieldKey.currentContext;
if (keyContext != null) {
await Future.delayed(const Duration(milliseconds: 500)).then(
(value) => Scrollable.ensureVisible(
keyContext,
duration: const Duration(milliseconds: 200),
curve: Curves.decelerate,
),
);
// Optional if doesnt work with the first
// await Future.delayed(const Duration(milliseconds: 500)).then(
// (value) => Scrollable.ensureVisible(
// keyContext,
// duration: const Duration(milliseconds: 200),
// curve: Curves.decelerate,
// ),
// );
}
}
}