在Flutter中,如何在小部件外刷新ListView?

8
我有一个Flutter应用程序,其中包括一个带有滑块和选项卡视图的脚手架。
选项卡视图包括一个列表,如下图所示,在每个选项卡上显示。
  List<Widget> widgetList = <Widget>[
    Post(),
    Feed(),
    Location(),
    HomePage(),
    Feed(),
  ];

现在我想在滑块移动时刷新屏幕上的当前标签页。然而,由于类是私有的,即_HomePageState,我不知道如何访问下面片段中显示的refreshList()方法。

homepage.dart:

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var list;
  var random;

  var refreshKey = GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    random = Random();
    refreshList();
  }

  Future<Null> refreshList() async {
    refreshKey.currentState?.show(atTop: false);
    await Future.delayed(Duration(seconds: 2));

    setState(() {
      list = List.generate(random.nextInt(10), (i) => "Item $i");
    });

    return null;
  }
}

滑块不会嵌入每个列表视图小部件,即homepage.dart,因为滑块值适用于每个单独的选项卡。当移动带有滑块的外部小部件时,如何刷新内部列表视图小部件?

enter image description here

1个回答

7

有不同的方法来处理这个问题:

  1. You could pass down the PageController and the page index to your page widgets. In your page widgets can then listen to the changes (pageController.addListener(...)) and compare the currently centered page with their page index.

  2. Create one ChangeNotifier for every page that you want to refresh:

    final postRefresh = ChangeNotifier();
    final feedRefresh = ChangeNotifier();
    ...
    
    // build method of parent:
    List<Widget> widgetList = <Widget>[
      Post(refresh: postRefresh),
      Feed(refresh: feedRefresh),
      ...
    ];
    
    // initState method of parent:
    pageController.addListener(() {
      final roundedPage = pageController.page.round();
      if(roundedPage == 0) {
        postRefresh.notifyListeners();
      }
      else if(roundedPage == 1) {
        feedRefresh.notifyListeners();
      }
      // ...
    })
    
  3. You could also give your page widgets a global key (for that, their State classes must be public):

    // class body of parent:
    final postPageKey = GlobalKey<PostPageState>();
    final feedPageKey = GlobalKey<FeedPageState>();
    
    // build method of parent:
    List<Widget> widgetList = <Widget>[
      Post(key: postPageKey),
      Feed(key: feedPageKey),
      ...
    ];
    
    // initState method of parent:
    pageController.addListener(() {
      final roundedPage = pageController.page.round();
      if(roundedPage == 0) {
        postPageKey.currentState?.refresh();
      }
      else if(roundedPage == 1) {
       feedPageKey.currentState?.refresh();
      }
      // ...
    })
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接