Skip to main content
Un moderador ha trasladado los comentarios al chat
se añadieron 399 caracteres en el cuerpo
Origen Enlace
diegoveloper
  • 7.3k
  • 2
  • 11
  • 20

Para expandir todos

void _expandAll() { 
  for (int i = 0; i < _keys.length; i++) { 
      if(_keys[i].currentState != null)
        _keys[i].currentState.expand(); 
  } 
}

Para contraer todos

void _colapseAll() { 
  for (int i = 0; i < _keys.length; i++) { 
      if(_keys[i].currentState != null)
        _keys[i].currentState.collapse(); 
  } 
}

Para expandir todos

void _expandAll() { 
  for (int i = 0; i < _keys.length; i++) { 
      if(_keys[i].currentState != null)
        _keys[i].currentState.expand(); 
  } 
}

Para contraer todos

void _colapseAll() { 
  for (int i = 0; i < _keys.length; i++) { 
      if(_keys[i].currentState != null)
        _keys[i].currentState.collapse(); 
  } 
}
Origen Enlace
diegoveloper
  • 7.3k
  • 2
  • 11
  • 20

Ok, para lo que deseas hacer primero vas a tener que crear un ExpansionTile personalizado para que puedas acceder a su State ya que el actual lo tiene privado. Así también crear métodos para ocultar y/o mostrar el tile.

Luego de eso debes crear GlobalKeys y asignarlo a tu nuevo ExpansionTitle, finalmente al momento de que seleccionas uno , verificar los demás y cerrarlos.

Aquí te dejo el código completo.

AppExpansionTitle Widget

const Duration _kExpand = const Duration(milliseconds: 200);

class AppExpansionTile extends StatefulWidget {
  const AppExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.onExpansionChanged,
    this.children: const <Widget>[],
    this.trailing,
    this.initiallyExpanded: false,
  })  : assert(initiallyExpanded != null),
        super(key: key);

  final Widget leading;
  final Widget title;
  final ValueChanged<bool> onExpansionChanged;
  final List<Widget> children;
  final Color backgroundColor;
  final Widget trailing;
  final bool initiallyExpanded;

  @override
  AppExpansionTileState createState() => AppExpansionTileState();
}

class AppExpansionTileState extends State<AppExpansionTile>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  CurvedAnimation _easeOutAnimation;
  CurvedAnimation _easeInAnimation;
  ColorTween _borderColor;
  ColorTween _headerColor;
  ColorTween _iconColor;
  ColorTween _backgroundColor;
  Animation<double> _iconTurns;

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: _kExpand, vsync: this);
    _easeOutAnimation =
        CurvedAnimation(parent: _controller, curve: Curves.easeOut);
    _easeInAnimation =
        CurvedAnimation(parent: _controller, curve: Curves.easeIn);
    _borderColor = ColorTween();
    _headerColor = ColorTween();
    _iconColor = ColorTween();
    _iconTurns = Tween<double>(begin: 0.0, end: 0.5).animate(_easeInAnimation);
    _backgroundColor = ColorTween();

    _isExpanded =
        PageStorage.of(context)?.readState(context) ?? widget.initiallyExpanded;
    if (_isExpanded) _controller.value = 1.0;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void expand() {
    _setExpanded(true);
  }

  void collapse() {
    _setExpanded(false);
  }

  void toggle() {
    _setExpanded(!_isExpanded);
  }

  void _setExpanded(bool isExpanded) {
    if (_isExpanded != isExpanded) {
      setState(() {
        _isExpanded = isExpanded;
        if (_isExpanded)
          _controller.forward();
        else
          _controller.reverse().then<void>((value) {
            setState(() {
              // Rebuild without widget.children.
            });
          });
        PageStorage.of(context)?.writeState(context, _isExpanded);
      });
      if (widget.onExpansionChanged != null) {
        widget.onExpansionChanged(_isExpanded);
      }
    }
  }

  Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor =
        _borderColor.evaluate(_easeOutAnimation) ?? Colors.transparent;
    final Color titleColor = _headerColor.evaluate(_easeInAnimation);

    return Container(
      decoration: BoxDecoration(
          color: _backgroundColor.evaluate(_easeOutAnimation) ??
              Colors.transparent,
          border: Border(
            top: BorderSide(color: borderSideColor),
            bottom: BorderSide(color: borderSideColor),
          )),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          IconTheme.merge(
            data: IconThemeData(color: _iconColor.evaluate(_easeInAnimation)),
            child: ListTile(
              onTap: toggle,
              leading: widget.leading,
              title: DefaultTextStyle(
                style: Theme.of(context)
                    .textTheme
                    .subhead
                    .copyWith(color: titleColor),
                child: widget.title,
              ),
              trailing: widget.trailing ??
                  RotationTransition(
                    turns: _iconTurns,
                    child: const Icon(Icons.expand_more),
                  ),
            ),
          ),
          ClipRect(
            child: Align(
              heightFactor: _easeInAnimation.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    _borderColor.end = theme.dividerColor;
    _headerColor
      ..begin = theme.textTheme.subhead.color
      ..end = theme.accentColor;
    _iconColor
      ..begin = theme.unselectedWidgetColor
      ..end = theme.accentColor;
    _backgroundColor.end = widget.backgroundColor;

    final bool closed = !_isExpanded && _controller.isDismissed;
    return AnimatedBuilder(
      animation: _controller.view,
      builder: _buildChildren,
      child: closed ? null : Column(children: widget.children),
    );
  }
}

Sample Widget

class MySample extends StatefulWidget {
  @override
  _MySampleState createState() => _MySampleState();
}

class _MySampleState extends State<MySample> {
  List<GlobalKey<AppExpansionTileState>> _keys =
      List.generate(dataEntry.length, (_) => GlobalKey());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: dataEntry.length,
        itemBuilder: (_, index) {
          final entry = dataEntry[index];
          if (entry.children == null || entry.children.isEmpty) {
            return ListTile(
              title: Text(entry.title),
              subtitle: Text(entry.subTitle),
            );
          }
          return _buildTiles(entry, index);
        },
      ),
    );
  }

  Widget _buildTiles(Entry root, int index) {
    if (root.children.isEmpty) return ListTile(title: Text(root.title));
    return AppExpansionTile(
      key: index != -1 ? _keys[index] : null,
      onExpansionChanged: (val) {
        // Si es el parent
        if (root.idParent == -1 && val && index != -1) {
          //Cerrar los otros
          for (Entry item in dataEntry) {
            if (item.id != root.id) {
              for (int i = 0; i < _keys.length; i++) {
                if (i != index && _keys[i].currentState != null) {
                  print("i :$i .. ${_keys[i]}");
                  _keys[i].currentState.collapse();
                }
              }
            }
          }
        }
      },
      title: Text(root.title),
      children:
          root.children.map((subItem) => _buildTiles(subItem, -1)).toList(),
    );
  }
}