flutter StatefulWidget组件不刷新

问题:flutter中我们自定义组件,然后添加在页面中,当我们在页面中使用setState方法,刷新页面内容时,会发现有时候我们的自定义组件有时候并不会实时刷新

flutter中有一套他自己的缓存机制,只会在他觉得页面需要刷新的时候才会重新绘制我们的自定义组件 针对以上问题,这里提供两种解决方案

1.使用Key(推荐,实测有效)
StatefulWidget组件的刷新机制 当页面需要刷新时会调用widget组件的canUpdate,比较新老widget的key和runtype是否相同,如果不同则重新绘制,如果相同,则使用老的widget,页面也就不会刷新了,这个时候如果我们想要让页面刷新,可以给我们的组件声明一个key属性,传一个UniqueKey(),这样,就相当于主动告诉widget需要刷新啦,亲测使用这种方式能够完美解决页面不刷新的问题

AdditionView(
                                key: UniqueKey(),
                                  value: model.count ?? 0,
                                  onTap: (type, res) {
                                    model.count = num.parse(res).toInt();
                                    Provider.of<ActivityCartProvider>(context,
                                            listen: false)
                                        .add(model, _detail);
                                  },
                                )

2.把组件定义成变量,在需要使用地方reload一下(有些场合有用,某些场合会出现setSate报错的情况 提示当前组件已经被dispose)
1>在父视图中创建一个自定义的widget变量,然后在需要使用地方加载当前组件

SearchContent _searchContent = SearchContent();
_searchContent.resetKey();
  2>在组件中保存state变量 并初始化一个reload方法
class SearchContent extends StatefulWidget {
  final String keyword;
  SearchContent({
    Key key,
    this.keyword,
  }):super(key:key);

  _SearchContentState myContentState = _SearchContentState();

  @override
  _SearchContentState createState() => myContentState;

  void resetKey(String keyword) {
    myContentState.research(keyword);
  }
}

class _SearchContentState extends State<SearchContent> {
 void research(String keword) {
    _keyword = keword;
    _searchReq(keword);
  }
}
  3>在StatefulWidget内容区创建一个自定义方法reloadData用来刷新页面数据

猜你喜欢

转载自www.cnblogs.com/qqcc1388/p/12973432.html