如何在扑动中使用KeepAliveNotification?

时间:2018-01-06 16:20:35

标签: dart flutter

我在SliverList中有一些小部件,当我滚动屏幕时,我不想丢失状态。根据文档," ...懒惰列表中的子项包含在AutomaticKeepAlive小部件中,以便孩子们可以使用KeepAliveNotifications来保存他们的状态,否则他们将在屏幕外收集垃圾。"和我的问题是,我如何发送KeepAliveNotification?我没有理解文档,也找不到任何使用它的例子。

我从哪里获得或创建可听的?在我的应用程序中,当用户点击节标题时,它会展开并更改从水平到垂直的对齐方式。当用户向下滚动页面时,状态将丢失。下面的代码示例(删除了一些与减少混乱的问题无关的代码)。

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new DefaultTabController(
        length: choices.length,
        child: new Scaffold(
          body: new CustomScrollView(slivers: <Widget>[
            new SliverAppBar(
            title: new Container(
              child: new TabBar(
                tabs: choices.map((Choice choice) {
                  return new Tab(
                    text: choice.title,
                    icon: new Image.asset(choice.icon, height:22.0),
                  );
                }).toList(),
              )),
            ),
            new SliverList(delegate:new SliverChildListDelegate([
              // Widget that I want to KeepAlive
              new TrendingArticles(),
              //Other widgets                                                     
            ])),
          ]),
        ),
      ),
    );
  }
}
//Widget that I want to KeepAlive
class TrendingArticles extends StatefulWidget{
  const TrendingArticles({ Key key }) : super(key: key, );

  @override
  _TrendingArticlesState createState() => new _TrendingArticlesState();
}

class _TrendingArticlesState extends State<TrendingArticles> {
  List<Article> articles = [];
  _getArticles() async {
    //Code for getting articles
  } 
  @override
  initState(){
    super.initState();
    _getArticles();   
  }
  void _handleSize(){
    //Handles changing orientation and size of widget
  }
  @override
  Widget build(BuildContext context) {
    return new Container(
      height:sectionHeight,
      child: new Column(children: <Widget>[
      new SectionHeader(title: "Articles", onTap:_handleSize,alignment:headerAlignment),
      new Container(
        height:sectionHeight - 55,
        child: new ListView(
          scrollDirection: scrollDirection,
          children: articles.map((Article article) {
            return new ArticleCard(
              height: cardHeight,
              article: article,
              onBannerTap: (Article article) {
                setState(() {
                  article.isFavorite = !article.isFavorite;
                });
              }
            );
          }).toList(),
        ),
      ),
    ]));   
  }
}

1 个答案:

答案 0 :(得分:0)

here所述,您必须将AutomaticKeepAliveClientMixin添加到您的银条列表委托子项的State类中,您要保持该状态。在您的示例中为_TrendingArticlesState

记住要在super.build(context);类的build方法中调用_TrendingArticlesState