微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么在软键盘出现和消失时会出现 UI 延迟?

如何解决为什么在软键盘出现和消失时会出现 UI 延迟?

当我单击主页 (main.dart) 上的文本字段时,这是 Flutter 给出的认 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 故障

enter image description here


此外,当我单击其他页面 (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",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

enter image description here

解决方法

由于 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 */
          // ...
        );
      },),);
}
,

这个所谓的 Glitch 的原因是 flutter scaffold 小部件的默认行为是在软键盘打开或关闭时调整其主体的大小。

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

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

Scaffold(
...
  resizeToAvoidBottomInset: false,)

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

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

另一方面,如果您想调整内容的大小,您可以选择modularize/breakdown 屏幕上的小部件to smallest possible combination & make the layout simpler 以便调整大小的 glitch 部分由重建过程的速度处理。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。