Dart 在内存中持久化颤振小部件
我在颤振中创建了自己的简单底部导航条实现。当按下选项卡时,颤振当前正在重新创建小部件(Dart 在内存中持久化颤振小部件,dart,flutter,flutter-layout,Dart,Flutter,Flutter Layout,我在颤振中创建了自己的简单底部导航条实现。当按下选项卡时,颤振当前正在重新创建小部件(initState()每次都被调用),这是不可取的 我希望这些小部件能够持久保存在内存中,这样,如果它们已经创建好了,就可以直接弹出 主部件 class\u MainRootScreenState扩展状态{ int _selectedIndex=0; 列表屏幕; @凌驾 void initState(){ //加载页面 _屏幕=[ 第一页(), 第二页(), 第三页() ]; super.initState()
initState()
每次都被调用),这是不可取的
我希望这些小部件能够持久保存在内存中,这样,如果它们已经创建好了,就可以直接弹出
主部件
class\u MainRootScreenState扩展状态{
int _selectedIndex=0;
列表屏幕;
@凌驾
void initState(){
//加载页面
_屏幕=[
第一页(),
第二页(),
第三页()
];
super.initState();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:_屏幕[_selectedIndex],
bottomNavigationBar:_buildBottomTabBar(上下文)
);
}
}
因此,当\u selectedIndex
更新时,所选页面将被重新创建
我在页面上尝试过使用
AutomaticEpaLiveClientMixin
,但运气不佳。如果您希望在单击tab按钮时不重建小部件/页面。您只需要遵循以下代码
只需使用AutomaticEpaLiveClientMixin将状态添加到State类中即可。在此之后,您需要重写名为wantKeepAlive
的方法,并将wantKeepAlive
设为true,就是这样
默认情况下,wantKeepAlive
为false,因为它可以节省内存
第一页
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;
}
class PageOne扩展StatefulWidget{
@凌驾
_PageOneState createState();
}
类_PageOneState使用AutomaticEpaLiveClientMixin扩展状态{
//你的密码在这里
@凌驾
bool get wantKeepAlive=>true;
}
从第二页和第三页执行同样的操作,也就是说,AutomaticePageAliveClientMixin仅在可滚动的范围内工作。你没有遗传基因,你有没有找到解决办法?不幸的是,你尝试了这个,但没有成功@rémi rousselet在上面提到,这只适用于可滚动的
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;
}