修正flutter弹出键盘挤压界面的问题

3,361 阅读1分钟

当激活键盘时,键盘会占用实际屏幕空间,导致页面被挤压出现overflowed的错误。这样页面不但会出现黄色超出告警区域,输入区域也会难以辨别。

引用自bing.com
解决该问题有如下思路:将页面内容包进一个滚动视图,使视口变得可压缩,但不影响实际内容的高度。这就需要做两件事:

  1. 弹性填充页面剩余空间的滚动视口
  2. 高度占用剩余页面空间的内容子视图

此处采用SingleChildScrollView滚动组件,同时占满屏幕剩余空间:

Expanded(child: SingleChildScrollView(child: content))

但如果只是这么做,会提示hasSize错误,即SingleChildScrollView不提供子组件尺寸。因此子组件也需要占满屏幕,尝试过用Expanded包含子组件,但失败了,原因不明;SizedBox倒是可用,不过高度不明,需要从上到下计算内容视图的可用空间,还好可行:用屏幕总高度减去内容视图上方组件的下方高度

double height = 0.0;
if (globalKey.currentContext != null) {
	RenderBox rb = globalKey.currentContext.findRenderObject();
	// 上方组件y坐标
	height += rb.localToGlobal(Offset.zero).dy;
	// 上方组件高度height
	height += rb.size.height;
}

用这个指定了高度SizedBox包含内容视图便可以安全的放在SingleChildScrollView中了。

double height = 0.0;
if (globalKey.currentContext != null) {
	RenderBox rb = globalKey.currentContext.findRenderObject();
	height += rb.localToGlobal(Offset.zero).dy;
	height += rb.size.height;
}
return Column(children: <Widget>[
	Row(mainAxisAlignment: MainAxisAlignment.center, children: _genSettingBtns()),
	Divider(key: globalKey),
	Expanded(child: SingleChildScrollView(child: SizedBox(
		height: MediaQuery.of(context).size.height - height,
		child: content
	)))
]);

MediaQuery.of(context).size.height获取的是屏幕高度

来源七牛云,可能失效
完美搞定!