为啥在软键盘出现和消失时抖动 UI 滞后?

Posted

技术标签:

【中文标题】为啥在软键盘出现和消失时抖动 UI 滞后?【英文标题】:Why flutter UI lag while soft keyboard appearing and disappearing?为什么在软键盘出现和消失时抖动 UI 滞后? 【发布时间】:2021-04-05 05:10:13 【问题描述】:

当我单击主页 (main.dart) 上的文本字段时,这是颤振给出的默认 dart。我可以看到软键盘出现时出现故障,并且软键盘消失时没有延迟。我在下面附上了这个案例的 gif。

void main() 
 SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
 statusBarColor: primaryColor, //blue
   statusBarIconBrightness: Brightness.dark,
));
 runApp(MyApp());

class MyApp extends StatelessWidget 
@override


Widget build(BuildContext context) 

return MaterialApp(

  theme: ThemeData(
    // This is the theme of your application.
    //
    // Try running your application with "flutter run". You'll see the
    // application has a blue toolbar. Then, without quitting the app, try
    // changing the primarySwatch below to Colors.green and then invoke
    // "hot reload" (press "r" in the console where you ran "flutter run",
    // or simply save your changes to "hot reload" in a Flutter IDE).
    // Notice that the counter didn't reset back to zero; the application
    // is not restarted.
    primarySwatch: Colors.pink,
    primaryColor: primaryColor,
    primaryColorBrightness: Brightness.dark,

  ),
  home: MyHomePage(title: 'Flutter Demo Home Page'),
);
  
class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;

  void _incrementCounter() 
    // setState(() 
    //   // This call to setState tells the Flutter framework that something has
    //   // changed in this State, which causes it to rerun the build method below
    //   // so that the display can reflect the updated values. If we changed
    //   // _counter without calling setState(), then the build method would not be
    //   // called again, and so nothing would appear to happen.
    //   _counter++;
    // );
    setState(() 
      Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => PhoneAuth()));

    );
  

  @override
  Widget build(BuildContext context) 
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      backgroundColor: Colors.red,

      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text('hell0000000'),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Container(
          color: Colors.white,
          child: ListView(
            children: [
              Column(

                children: <Widget>[
                  Text(
                    'You have pushed the button this many times:',
                  ),


                  Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.headline4,
                  ),

                  SizedBox(
                    height: 200,
                  ),

                  Align(
                    alignment: Alignment.bottomCenter,
                    child: new Container(
                      child: TextField(
                        decoration: new InputDecoration(
                          hintText: 'Chat message',
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],

          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  

ma​​in.dart 故障


另外,当我单击另一页 (UserChatView.dart) 上的文本字段时。当软键盘出现和消失时,我可以看到一个小故障。在这个 dart 文件中,两个动作(键盘打开和关闭)都发生了故障。我在下面附上了这个案例的 gif。

class UserChatView extends StatelessWidget



  @override
  Widget build(BuildContext context) 
      return UserChatViewPage();

  




class UserChatViewPage extends StatefulWidget 
  UserChatViewPage(Key key) : super(key: key);
  @override

  _UserChatViewPageState createState() =>  _UserChatViewPageState();


class _UserChatViewPageState extends State<UserChatViewPage> 
  final TextEditingController _textController = new TextEditingController();

  @override
  Widget build(BuildContext context) 
    final focus = FocusNode();

    return new Scaffold(

      backgroundColor: Colors.red, // Scaffold background Color
      appBar: new AppBar(
        title: Row(
          children: <Widget>[
            // new Container(
            //     child: CircleAvatar(
            //       backgroundImage: AssetImage("assets/male_icon.png"),
            //     )
            // ),

            new SizedBox(
              width: 5.00,
            ),

            new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget> [
                new Container(

                  child: new Text("Alex Marko",
                    style: TextStyle(color: Colors.white,
                        fontFamily: 'Roboto_Bold',
                        letterSpacing: 1.00

                    ),
                  ),
                ),
                new Container(
                  child: new Text("Online",
                    style: TextStyle(color: Colors.white,
                      fontFamily: 'Roboto_Medium',
                      letterSpacing: 1.00,
                      fontSize: 12.00,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),

        centerTitle: false,
        titleSpacing: 0.0,
        backgroundColor: primaryColor,
        elevation: 0.0,
        bottomOpacity: 0.0,
        actions: <Widget>[

          IconButton(
            icon: Icon(
              Icons.expand_more_rounded,
              color: Colors.white,
            ),
            onPressed: () 
              // do something
            ,
          ),
        ],

      ),

    body:  Center(
        child: new Container(
          color: Colors.grey,

          child: new Column(
                     children: <Widget>[
          
                            new Expanded(
                               child: _PageListView(),
                                       ),

                               new Container(

                                 color: Colors.yellow,
                                               padding: new EdgeInsets.all(10.0),

                                      child: _buildTextComposer(),
                                                ),
                                          ],
                                       ),

                                     ),
                                    ),

                                  );

Widget _buildTextComposer() 
    return new Container(
      color: Colors.yellow,//modified
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        child: new Row(
          children: <Widget>[
            new Flexible(
              child: new TextField(
                controller: _textController,
                onSubmitted: _handleSubmitted,
                decoration: new InputDecoration.collapsed(
                    hintText: "Send a message"),
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 4.0),
              child: new IconButton(
                  icon: new Icon(Icons.send),
                  onPressed: () => _handleSubmitted(_textController.text)),
            ),
          ],
        ),
      );                                                            

  
 Widget _PageListView()
    return new Container(

    child: ListView.builder(
      reverse: true,
      itemCount: 20,
      itemBuilder: (context, position) 
        return Card(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(position.toString(), style: TextStyle(fontSize: 22.0),),
          ),
        );
      ,
    ),
    );
  

UserChatView.dart Glich

【问题讨论】:

发布_PageListView内容 @dm_tr 我添加了_PageListView 查看下面的答案 【参考方案1】:

由于ListView.builder,您的键盘会产生这种效果。像这样向您的ListView 添加额外的属性

Widget _PageListView()
  return new Container(

    child: ListView.builder(
      addAutomaticKeepAlives: true, // Add this property
      cacheExtent: double.infinity, // And this one
      
      reverse: true,
      itemCount: 20,
      itemBuilder: (context, position) 
        return Card( /* It's better to have here a separated StatefulWidget with AutomaticKeepAliveClientMixin */
          // ...
        );
      ,
    ),
  );

【讨论】:

仍然出现同样的故障。你知道为什么这个故障发生在其他活动上,而不是第一个活动(main.dart)上。即使键盘已经打开(第二个 GIF),文本字段的焦点也会有延迟。当我使用 java 开发一个 android 应用程序时,这不是问题。 当我使用 java 构建应用程序时,它的大小调整得非常快,但是在颤振中,这个故障发生在每个活动中,但在第一个活动中,故障不像其他活动那样通知。 不,不是。就像我说的。它发生在用户注册活动中的文本字段(例如 - 列中的 4 个文本字段全部用于该活动):(【参考方案2】:

之所以称为Glitch,是因为flutter scaffold 小部件的默认行为是在软键盘打开或关闭时调整其主体。

当 Flutter 脚手架收到上述两个事件中的任何一个时,它将开始调整其 body 下的小部件的大小以匹配新状态。调整大小的速度可能会因屏幕上小部件构建过程的复杂性和设备本身的处理速度而异。

您可以在应用的脚手架小部件中添加一个名为 resizeToAvoidBottomInset 的标志,如下所示:

Scaffold(
...
  resizeToAvoidBottomInset: false,
)

它的作用是,它通知脚手架不要在键盘向上或向下状态下调整其body 下的小部件。

因此,除非您想在键盘状态下显式调整屏幕内容的大小,否则这是您的故障的解决方案。

另一方面,如果你想调整内容的大小,你可以选择modularize/breakdown屏幕上的小部件to smallest possible combinationmake the layout simpler,这样glitch部分调整大小取决于重建过程的速度。

【讨论】:

以上是关于为啥在软键盘出现和消失时抖动 UI 滞后?的主要内容,如果未能解决你的问题,请参考以下文章

Android - 如何在软键盘出现时调整弹出窗口

PRD学习笔记:一些需要注意的说明

当文本字段获得焦点时,如何使底部工具栏浮在软键盘上方

在软键盘打开/关闭之前,RecyclerView 不会更新并显示在屏幕上

Xamarin.Forms.UWP 数字键盘仅在软键盘上

Android view显示在软键盘上方