在flutter中如果切换tabar,则initState方法会被反复重调,若想保持原有状态,切换页面时不再调用initState方法,则需使用AutomaticKeepAliveClientMixin.同Vue中的<keep-alive>使用原理一样

第一步:在State类中混入AutomaticKeepAliveClientMixin这个类

 

class _xxxxxState extends State<MilitaryPage> with AutomaticKeepAliveClientMixin{
........
}

第二步: 重写AutomaticKeepAliveClientMixin中的wantKeepAlive方法

 @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

第三步:在build中调用父类的build方法

 Widget build(BuildContext context) {
    super.build(context);
    return Center(...)
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐