首页 > 解决方案 > 当在真实设备上的 BottomSheet 聚焦时,TextField 留在键盘后面,但在模拟器上工作

问题描述

我看到了一些解决方案并实施了它们。在模拟器上看起来不错,但在真实设备上不起作用(见屏幕)。因此,当我单击文本字段时,键盘会根据焦点文本字段向上移动,并且我可以滚动,但在真实设备中不会发生。在此先感谢您的时间。

在 FloatinActionButton 启动的 BottomSheet

showModalBottomSheet(
                isScrollControlled: true,
                backgroundColor: Colors.transparent,
                context: context,
                builder: (context) => SingleChildScrollView(
                  child: Container(
                      child: PostAd(),
                      padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context).viewInsets.bottom,
                      )),
                ),
              );

PostAD 方法在 Container 中显示多个页面(取决于用户选择的索引)

return Center(
      child: Container(
        height: MediaQuery.of(context).size.height / 1.5,
       
        child: Center(
          child: Container(
           child: Column(
              children: [
                Center(child: radioButtonCreate()), // Radio Buttons to select Page Index
                Expanded(child: kadFormList[formIndex]), //Pages i.e forms that has text field
              ],
            ),
          ),
        ),

在此处输入图像描述

标签: flutterflutter-layoutflutter-showmodalbottomsheetflutter-design

解决方案


import 'package:flutter/material.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';

main() => runApp(MaterialApp(
  home: Scaffold(
    body: MyForm(),
  ),
));

class MyForm extends StatefulWidget {
  MyForm() : super();

  @override
  State<StatefulWidget> createState() => MyFormState();
}

class MyFormState extends State<MyForm> {
  bool isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();

    KeyboardVisibilityNotification().addNewListener(
      onChange: (bool visible) {
        if (!visible) {
          setState(() {
            FocusScope.of(context).unfocus();
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20.0, 20, 20, 0),
      child: SingleChildScrollView(
        reverse: isKeyboardVisible ? true : false,
        child: Padding(
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 100),
          child: Column(
            children: <Widget>[
              for (int i=0; i<100; i++) TextField()
            ],
          ),
        ),
      ),
    );
  }
}

推荐阅读