dart 如何滚动屏幕与文本字段获得焦点当键盘打开

yc0p9oo0  于 2023-03-10  发布在  其他
关注(0)|答案(2)|浏览(142)

我有flutter应用程序,并创建了表单屏幕来获取用户详细信息。在表单屏幕中,当用户点击文本字段时,它会获得焦点,然后键盘打开,需要滚动文本字段,用户想要看到他正在键入什么。

6xfqseft

6xfqseft1#

要在文本字段获得焦点时滚动到该字段,您需要使用Scrollable.ensureVisible方法。下面是一些代码,向您展示如何使用该方法。希望对您有所帮助!
问候。

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,
      //   ),
      // );
    }
  }
}
7vux5j2d

7vux5j2d2#

使用SingleChildScrollView Package 列小部件
示例:

Scaffold(
        body: SingleChildScrollView(
          child: Column(
            children:[
              TextField(),
              TextField()
          ],
        ),
      )
    ),

相关问题