es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿Es posible tener una fila expandible en una tabla con Flutter?

Estoy tratando de encontrar una forma de expandir las filas en una tabla, pero parece que nada funciona.

Me gustaría hacer clic en una de las filas de la tabla y hacer que se expanda para mostrar más datos sobre la FILA, y luego al presionar nuevamente se cierre y vuelva a ser una tabla.

Intenté usar el widget Expanded, pero no funcionó:

import ‘package:flutter/material.dart’;

class StagePage extends StatelessWidget {
const StagePage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container(
child: Table(
defaultColumnWidth: FixedColumnWidth(120.0),
border: TableBorder.all(
color: Colors.black,
style: BorderStyle.solid,
width: 2),
children: [
TableRow( children: [
Column(children:[Text(‘Website’, style: TextStyle(fontSize: 20.0))]),
Column(children:[Text(‘Tutorial’, style: TextStyle(fontSize: 20.0))]),
Column(children:[Text(‘Review’, style: TextStyle(fontSize: 20.0))]),
Card(
child: ExpansionTile(
title: Text(
‘Website’,
style: TextStyle(fontSize: 20.0),
),
children: [
Text(‘Acerca del sitio web’),
Text(‘Agregar más datos’),
Text(‘agregar más y más datos’),
// agregar más datos que desees de esta manera
],
),
)],
),]
)

);

}
}

Cualquier ayuda o sugerencia será genial. ¡Gracias!

Este es el resultado de mi código:
pero quiero abrir todas las filas sin las líneas y los bordes de la tabla.

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Una posible solución para lograr filas expandibles en una tabla es utilizando el widget ExpansionPanelList. Aquí tienes un ejemplo de código:

    import 'package:flutter/material.dart';
    
    class StagePage extends StatefulWidget {
      const StagePage({Key? key}) : super(key: key);
    
      @override
      _StagePageState createState() => _StagePageState();
    }
    
    class _StagePageState extends State<stagepage> {
      List<bool> _isOpenList = List.generate(10, (index) => false);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Table(
            defaultColumnWidth: FixedColumnWidth(120.0),
            border: TableBorder.all(
              color: Colors.transparent,
              style: BorderStyle.none,
              width: 0,
            ),
            children: [
              TableRow(children: [
                buildHeader('Website'),
                buildHeader('Tutorial'),
                buildHeader('Review'),
              ]),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
              buildBodyRow(),
            ],
          ),
        );
      }
    
      Widget buildHeader(String text) {
        return Column(
          children: [
            Text(
              text,
              style: TextStyle(fontSize: 20.0),
            ),
          ],
        );
      }
    
      Widget buildBodyRow() {
        int rowIndex = _isOpenList.indexWhere((isOpen) => isOpen == false);
        if (rowIndex == -1) {
          rowIndex = _isOpenList.length;
          _isOpenList.add(false);
        }
    
        return TableRow(children: [
          buildExpansionPanel(rowIndex),
          Column(children: [Text('Contenido 1')]),
          Column(children: [Text('Contenido 2')]),
        ]);
      }
    
      Widget buildExpansionPanel(int rowIndex) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 4.0),
          child: ExpansionPanelList(
            elevation: 0,
            expansionCallback: (panelIndex, isExpanded) {
              setState(() {
                _isOpenList[rowIndex] = !isExpanded;
              });
            },
            children: [
              ExpansionPanel(
                isExpanded: _isOpenList[rowIndex],
                canTapOnHeader: false,
                body: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Acerca del Sitio Web'),
                      SizedBox(height: 8.0),
                      Text('Agregar más datos'),
                      SizedBox(height: 8.0),
                      Text('Agregar más más datos'),
                    ],
                  ),
                ),
                headerBuilder: (BuildContext context, bool isExpanded) {
                  return Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    child: Text(
                      'Sitio Web',
                      style: TextStyle(fontSize: 16.0),
                    ),
                  );
                },
              ),
            ],
          ),
        );
      }
    }
    

    En este código, usamos ExpansionPanelList para crear el panel expandible. También utilizamos una lista booleana _isOpenList para mantener un registro de si cada fila está expandida o no. La función buildBodyRow ahora devuelve una TableRow con un widget buildExpansionPanel como la primera celda. La función buildExpansionPanel crea el ExpansionPanelList con un solo ExpansionPanel. Pasamos el índice de la fila a esta función y lo usamos para acceder al valor booleano correspondiente en _isOpenList. También usamos canTapOnHeader: false para desactivar la expansión/colapso del panel al hacer clic en el encabezado.

    Configuramos el borde de la Table como TableBorder.all(color: Colors.transparent, style: BorderStyle.none, width: 0,) para ocultar los bordes de la tabla.

    Ten en cuenta que esta solución asume que la tabla tiene un número fijo de filas. Si tienes una tabla generada dinámicamente, es posible que debas ajustar la lógica para manejar la naturaleza dinámica de los datos.

    ¡Espero que esto te ayude! Avísame si tienes alguna pregunta.

Comments are closed.