【问题标题】:Rebuild whole widget tree when a keyboard appears出现键盘时重建整个小部件树
【发布时间】:2021-07-03 03:14:13
【问题描述】:

当键盘出现抖动时如何解决重新渲染整个小部件树?在我的应用程序中,每当键盘出现和消失时,整个小部件树都会重新构建?有什么办法可以避免这种情况?

【问题讨论】:

  • 设置脚手架resizeToAvoidBottomInset为false

标签: flutter keyboard widget mobile-application rerender


【解决方案1】:

有多种方法可以解决这个问题,这是我过去使用过的一些解决方案。

Scaffold 的resizeToAvoidBottomInset 参数

将此设置为false,您的屏幕将不会调整大小,这样做的缺点是键盘将出现在您的 UI 顶部

例子:

class SampleScreen extends StatelessWidget {
  const SampleScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Align(
        alignment: Alignment.bottomCenter,
        child: SafeArea(
          minimum: const EdgeInsets.all(20),
          child: TextField(
            decoration: new InputDecoration(
              enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Colors.black, width: 1.0),
              ),
              hintText: 'Mobile Number',
            ),
          ),
        ),
      ),
    );
  }
}

将 Scaffold 的主体包裹在 ScrollView 中

通过将你的整个身体放在一个 ScrollView 中,你现在可能有一个冗长的表单,唯一需要注意的是你将无法使用 SpacerExpanded 小部件

例子

class SampleScreen extends StatelessWidget {
  const SampleScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        minimum: const EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(children: [
            Container(
              padding: EdgeInsets.all(20),
              margin: EdgeInsets.all(10),
              color: Colors.red,
              height: MediaQuery.of(context).size.height - 165,
            ),
            TextField(
              decoration: new InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.black, width: 1.0),
                ),
                hintText: 'Mobile Number',
              ),
            ),
          ]),
        ),
      ),
    );
  }
}

保存您当前的状态

使用有状态小部件并将应用的当前数据保存在某处。

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2020-08-22
    • 2015-08-21
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多