【问题标题】:Persist Flutter widget in memory在内存中持久化 Flutter 小部件
【发布时间】:2018-11-25 16:21:10
【问题描述】:

我在 Flutter 中创建了自己的简单底部导航栏实现。当按下选项卡时,Flutter 当前正在重新创建小部件(initState() 每次都会被调用),这是不可取的。

我希望小部件持久保存在内存中,因此如果它们已经创建,它们会直接弹出。

主小部件

class _MainRootScreenState extends State<MainRootScreen> {

  int _selectedIndex = 0;

  List<Widget> _screens;

  @override
  void initState() {

    // load pages
    _screens = [
      PageOne(),
      PageTwo(),
      PageThree()
    ];

    super.initState();
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: _screens[_selectedIndex],
      bottomNavigationBar: _buildBottomTabBar(context)
    );
  }
}

所以当_selectedIndex 更新时,所选页面将重新创建。

我尝试在页面上使用AutomaticKeepAliveClientMixin,但没有成功。

【问题讨论】:

  • AutomaticKeepAliveClientMixin 仅适用于 Scrollable。你这里没有
  • 您找到解决方案了吗?

标签: dart flutter flutter-layout


【解决方案1】:

如果您希望在单击选项卡按钮时不重建小部件/页面。您只需要遵循此代码

只需将State&lt;PageOne&gt; with AutomaticKeepAliveClientMixin&lt;PageOne&gt; 添加到您的状态类。在此之后,您需要重写一个名为 wantKeepAlive 的方法并将 wantKeepAlive 设为 true 就是这样。

默认wantKeepAlive是假的,因为它节省了我们的记忆。

PageOne

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}
class _PageOneState extends State<PageOne> with AutomaticKeepAliveClientMixin<PageOne> {

  // Your code are here

  @override
  bool get wantKeepAlive => true;
}

pageTwoPageThree 做同样的事情,就是这样

【讨论】:

  • 不幸的是没有运气。 @rémi-rousselet 上面提到这仅适用于 Scrollable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 2014-08-04
  • 2019-03-06
  • 2021-05-06
  • 2015-03-25
相关资源
最近更新 更多