Isuru Bandara
Isuru Bandara

Reputation: 360

Why flutter UI lag while soft keyboard appearing and disappearing?

When I click text fields on the main page (main.dart) which is the default dart given by the flutter. I can see a glitch when soft keyboard appears and there is no delay when soft keyboard disappears.I have attached a gif below for this case.

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.
    );
  }
}

main.dart glich

enter image description here


Also, When I click text fields on the other page (UserChatView.dart). I can see a glitch when soft keyboard appearing and disappearing. In this dart file, That glitch happening for both actions(Keyboard opening and closing). I have attached a gif below for this case.

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

enter image description here

Upvotes: 10

Views: 8415

Answers (2)

Harshvardhan Joshi
Harshvardhan Joshi

Reputation: 3193

The reason of this so called Glitch is that the default behaviour of the flutter scaffold widget is to resize it's body when soft keyboard opens up or closes down.

While the flutter scaffold is notified of any of the above two events, it will start resizing the widgets under its body to match the new state. The speed of resizing may differ based on the comlplexity of build process of the widget on screen & processing speed of the device itself.

What you can do is add a flag called resizeToAvoidBottomInset in the scaffold widget in your app, like this:

Scaffold(
...
  resizeToAvoidBottomInset: false,
)

What this does is, It notifies the scaffole to not resize the widget under its body on keyboard up or down states.

So, unless you want to explicitely resize the content of the screen on keyboard state, this is a solution to your glitch.

On the other hand, if you want to resize the content, you can choose to modularize/breakdown the widgets that you have on screen to smallest possible combination & make the layout simpler so that the glitch portion of the resizing is taken care of by the speed of rebuild process.

Upvotes: 8

dm_tr
dm_tr

Reputation: 4763

Your keyboard is producing that effect because of the ListView.builder. Add extra properties to your ListView like this

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

Upvotes: 1

Related Questions