flutter - 更改BottomNavigationBar中的页面时,强制Flutter不会丢失数据

标签 flutter dart state

我的flutter应用程序有一个bottomNavigationBar小部件,它实际上可以正常工作,所以...
问题是我将页面更改为另一页面后,我从API调用中丢失了数据,然后当我回来时,我必须再次对所有内容进行re-fetch!
避免这种情况的最佳方法是什么?
编码


// ...Some code...

class _HomeState extends State<Home> {
  List<wp.Post> posts = [];
  int _pageNumber = 1;

  Future<String> getPosts() async {
    var res = await fetchPosts(_pageNumber);
    setState(() {
      posts = res;
    });
    return "Success!";
  }

  // Get posts when app loads;
  @override
  void initState() {
    super.initState();
      this.getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: posts == null ? 0 : posts.length,
      itemBuilder: (BuildContext context, int index) {
        return buildPost(context, posts, index); //Building the posts list view
      },
    );
  }
}

最佳答案

您可以使用`AutomaticKeepAliveClientMixin”来保持页面状态。

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin { //<== add mixin
  List<wp.Post> posts = [];
  int _pageNumber = 1;

  @override
  bool get wantKeepAlive => true; //<== add this line 

  Future<String> getPosts() async {
    var res = await fetchPosts(_pageNumber);
    setState(() {
      posts = res;
    });
    return "Success!";
  }

  // Get posts when app loads;
  @override
  void initState() {
    super.initState();
      this.getPosts();
  }

  @override
  Widget build(BuildContext context) {

    super.build(context); // <== add this line
    return ListView.builder(
      itemCount: posts == null ? 0 : posts.length,
      itemBuilder: (BuildContext context, int index) {
        return buildPost(context, posts, index); //Building the posts list view
      },
    );
  }
}

关于flutter - 更改BottomNavigationBar中的页面时,强制Flutter不会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63885181/

相关文章:

swift - Flutter 中的 BLE 支持

android - Flutter HTTP 服务器 - 在另一个应用程序中提供 Flutter Web 服务

dart - 如何在 Dart 中解析时区 ID?

state - AutoHotKey - 创建与状态相关的热键

flutter - 如何使小部件填充列中的剩余空间

ios - 真实 iOS 设备上的 flutter 错误 : "module ' fluttertoast' not found"

flutter - 我们应该以什么方式将带有 oneof 的原始消息映射到带有干净代码的数据类

android - java.lang.IllegalStateException : Trying to create a platform view of unregistered type: com. pichillilorenzo/flutter_inappwebview 问题

javascript - 如何更改 Recharts 中每个条的颜色?

javascript - 如何在更改 React 路由时隐藏子组件