Laggy animation

Q. *_*ude 9 dart flutter

Does anyone have experienced laggy transition between screens when using a TabBar, or am I using it wrong ? Basically I am using it as following by building page in other widgets

home: DefaultTabController(
    initialIndex: 0,
    length: 5,
    child: Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          isScrollable: true,
          labelStyle: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold),
          tabs: [
            Tab(text: 'HOME'),
            Tab(text: 'SCHEDULE'),
            Tab(text: 'ANALYTICS'),
            Tab(text: 'TEMP'),
            Tab(text: 'SETTINGS'),
          ],
        ),
        title: Text('${widget.title}'),
      ),
      body: TabBarView(
        children: [
          TheGridView().build(),
          SchedulePage(),
          ChartPage(),
          TempPage(),
          SettingsPage(),
        ],
      ),
    ),
  ),
Run Code Online (Sandbox Code Playgroud)

cam*_*492 5

TabBarView不保存在它的小部件的状态。每次重新出现在屏幕上时,它们都会被重建。您可以通过为其中一个小部件添加一条print()语句来检查这一点initState()。要解决此问题,您可以使用AutomaticKeepAliveClientMixin

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) : super(key: key);

  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> with AutomaticKeepAliveClientMixin { //<-- AutomaticKeepAliveClientMixin

  @override
  bool get wantKeepAlive => true; //Set to true

  @override
  Widget build(BuildContext context) {
    super.build(context); //You must add this
    return Container(); //A screen here
  }
}
Run Code Online (Sandbox Code Playgroud)

有了这个小小的改变,小部件每次被带回屏幕时都不会重建


小智 0

您还没有使用过 TabsController 也许它可以帮助您提高选项卡的性能。

TabController controller;
Run Code Online (Sandbox Code Playgroud)

并在 initState() 中

controller = new TabController(length: 5, vsync: this);
Run Code Online (Sandbox Code Playgroud)

就像这里https://api.flutter.dev/flutter/material/TabController-class.html