ExpansionTile不保持状态

ExpansionTile不保持状态

本文介绍了ExpansionTile不保持状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问题:
我有一个 ExpansionTiles 效果很好。我面临的唯一问题是,从视图中滚动出来的扩展ExpansionTile在再次滚动到视图中后将不再扩展。

following problem:I have a list of ExpansionTiles which works very well. The only problem I'm facing is that a expanded ExpansionTile which is scrolled out of view will, after scrolling it into view again, no longer be expanded. This leads to undesired user experience and also a kind of "jumpy" scrolling.

文档指出以下内容:

与ListView之类的滚动小部件一起使用时,必须指定一个唯一键,以使ExpansionTile在滚动到视图中和从视图中退出时能够保存和恢复其展开状态。

但这不起作用。到目前为止,我还没有找到使之可行的方法。

这是到目前为止的代码:

This doesn't work though. So far I have found no way to make this work.
Here is the code so far:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'ExpansionTile Test',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> _getChildren() {
    List<Widget> elements = [];
    for (int i = 0; i < 20; i++) {
      elements.add(new ListChild());
    }
    return elements;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('ExpansionTile Test'),
      ),
      body: new ListView(
        children: _getChildren(),
      ),
    );
  }
}

class ListChild extends StatefulWidget {
  @override
  State createState() => new ListChildState();
}

class ListChildState extends State<ListChild> {
  GlobalKey<ListChildState> _key = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return new ExpansionTile(
      key: _key,
      title: const Text('Test Tile'),
      children: <Widget>[
        const Text('body'),
      ],
    );
  }
}


推荐答案

使用 PageStorageKey 代替 GlobalKey

这篇关于ExpansionTile不保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!