Flutter解决键盘弹出时固定在底部的内容被顶上去

999 阅读1分钟

尝试resizeToAvoidBottomInset属性,但是没有达到预期效果。

@override
Widget build(BuildContext context) {
  return Scaffold(
    resizeToAvoidBottomInset: false,
  );
}

实现思路

  1. 给布局指定一个明确的高度,不要使用double.infinity
  2. 外层使用SingleChildScrollView嵌套
  3. 使用Stack配合Positioned将底部按钮固定
  4. 主体内容再使用SingleChildScrollView嵌套,使得内容可支持滚动
@override
Widget build(BuildContext context) {
  double height = MediaQuery.of(context).size.height -
      appBarHeight -
      MediaQuery.of(context).padding.top -
      MediaQuery.of(context).padding.bottom;
  return Scaffold(
    body: Container(
      width: MediaQuery.of(context).size.width,
      height: height,
      alignment: Alignment.topLeft,
      child: SingleChildScrollView(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: height,
          child: Stack(
            children: [
              Stack(
                children: [
                  SingleChildScrollView(
                    child: Column(
                      children: [
                        // 可以滚动的内容
                        Text('测试内容开始...'),
                        TextField(
                          decoration: InputDecoration(
                            hintText: '测试内容',
                          ),
                        ),
                        SizedBox(height: 1500),
                        Text('测试内容结束...'),
                        // 该高度为"固定在底部的内容"的高度
                        SizedBox(height: 100),
                      ],
                    ),
                  )
                ],
              ),

              // 固定在底部的内容,不希望因为点击输入框而被键盘弹出给顶上去,固定在底部即可
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 100,
                  color: Colors.blue,
                ),
              ),
            ],
          ),
        ),
      ),
    ),
  );
}