How can add dynamic row to dynamic column in flutter?

To add dynamic rows to dynamic columns in Flutter, you can use nested ListView.builder widgets.

Here’s a basic example demonstrating how you can achieve this:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Dynamic Rows and Columns Example'),
        ),
        body: DynamicTable(),
      ),
    );
  }
}

class DynamicTable extends StatefulWidget {
  @override
  _DynamicTableState createState() => _DynamicTableState();
}

class _DynamicTableState extends State<DynamicTable> {
  List<List<String>> _data = [
    ['Row 1, Column 1', 'Row 1, Column 2', 'Row 1, Column 3'],
    ['Row 2, Column 1', 'Row 2, Column 2', 'Row 2, Column 3'],
  ];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _data.length,
      itemBuilder: (context, index) {
        return Row(
          children: _data[index]
              .map((cellData) => Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(),
                      ),
                      padding: EdgeInsets.all(8.0),
                      child: Text(cellData),
                    ),
                  ))
              .toList(),
        );
      },
    );
  }
}

Output:

In this example:

  • We have a DynamicTable widget that is a StatefulWidget.
  • The _data list contains lists of strings, each representing a row of data.
  • In the build method of _DynamicTableState, we use a ListView.builder to build dynamic rows.
  • Inside the ListView.builder, we use a Row widget to represent each row.
  • For each row, we map over the list of strings in _data[index] to build dynamic columns using Expanded widgets.
  • Each column contains a Container with border decoration and padding, containing the text data.

This way, you can dynamically generate rows and columns based on your data. You can modify _data to hold your dynamic data, and the UI will adjust accordingly.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More