如何在颤振中使用 KeepAliveNotification?

Chr*_*son 5 dart flutter

我在 SliverList 中有一些小部件,我不想在滚动屏幕外时丢失状态。根据文档,“...懒惰列表中的孩子被包裹在 AutomaticKeepAlive 小部件中,以便孩子们可以使用 KeepAliveNotifications 来保存他们的状态,否则他们会在屏幕外被垃圾收集。”,我的问题是,我如何发送保持活动通知?我未能理解文档,也无法找到任何使用示例。

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

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(),
        ),
      ),
    ]));   
  }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rev 1

正如这里提到的,您必须添加AutomaticKeepAliveClientMixin到您的条子列表委托子级的 State 类中,您想要保留该状态。在你的例子中是_TrendingArticlesState

记得调用super.build(context);build_TrendingArticlesState类的方法。