skip to Main Content

I want to add row list. First click add button it working fine.. Refer this image

enter image description here

And second click add button it row become double.. refer this bellow image

enter image description here

Pic #1 is what it is
enter image description here

pic #2 is what I need
enter image description here

how to fix just to allow one row per table

reference code

 Container(
        width: 650,
        margin: EdgeInsets.only(top: 10, bottom: 15),
        child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Table(
                defaultColumnWidth:
                FixedColumnWidth(data.size.width * 0.1 * 8),
                // border:
                //     TableBorder.all(width: 1.0, color: Colors.grey[500]),
                children: [
                    ...this.rowList.map((row) {
                        return TableRow(children: [
                            Container(
                                child: Column(children: [
                                    Container(
                                        width: 150.0,
                                        height: 40.0,
                                        child: Text(
                                            "Serial Number",
                                            textAlign: TextAlign.left,
                                            style: TextStyle(color: Colors.black),
                                        ),
                                    ),
                                    Container(
                                        width: 400.0,
                                        height: 30.0,
                                        margin: EdgeInsets.only(bottom: 15),
                                        decoration: BoxDecoration(
                                            color: Colors.grey[200],
                                            borderRadius:
                                            new BorderRadius.circular(2.0)),
                                        child: Padding(
                                            padding: EdgeInsets.only(
                                                left: 15,
                                                right: 5,
                                                top: 2,
                                                bottom: 2),
                                            child: TextFormField(
                                                initialValue: row['serialNo'],
                                                onChanged: (value) {
                                                    row['serialNo'] = value;
                                                    print(row['serialNo']);
                                                    updateDetails();
                                                },
                                                decoration: const InputDecoration(
                                                    border: InputBorder.none,
                                                ),
                                            )),
                                    ),
                                    Container(
                                        width: 600.0,
                                        margin: EdgeInsets.only(top: 1),
                                        child: Scrollbar(
                                            isAlwaysShown: true,
                                            child: SingleChildScrollView(
                                                scrollDirection: Axis.horizontal,
                                                child: Row(children: [
                                                    Column(children: [
                                                        Container(
                                                            child: Center(
                                                                child: Text('1',
                                                                    style: TextStyle(
                                                                        color: Colors
                                                                        .white))),
                                                            height: 40,
                                                            width: 240.0,
                                                            decoration: BoxDecoration(
                                                                border: Border.all(
                                                                    width: 1.0,
                                                                    color: Colors.grey),
                                                                color:
                                                                Colors.grey[600])),
                                                        Table(
                                                            defaultColumnWidth:
                                                            FixedColumnWidth(
                                                                data.size.width *
                                                                0.1),
                                                            border: TableBorder.all(
                                                                width: 1.0,
                                                                color:
                                                                Colors.grey[500]),
                                                            children: [
                                                                TableRow(
                                                                    children: [
                                                                        "A",
                                                                        "B",
                                                                        "C",
                                                                        "D"
                                                                    ]
                                                                    .map((label) =>
                                                                        Container(
                                                                            height:
                                                                            40,
                                                                            color: Colors
                                                                            .black,
                                                                            padding: EdgeInsets.symmetric(
                                                                                vertical:
                                                                                4),
                                                                            child: Center(
                                                                                child: Text(
                                                                                    label,
                                                                                    textAlign:
                                                                                    TextAlign.center,
                                                                                    style: TextStyle(
                                                                                        color:
                                                                                        Colors.white),
                                                                                ))))
                                                                    .toList()),
                                                                ...this
                                                                .rowList
                                                                .map((row) {
                                                                    return TableRow(
                                                                        children: [
                                                                            'valueA',
                                                                            'valueB',
                                                                            'valueC',
                                                                            'valueD'
                                                                        ]
                                                                        .map((label) => Container(
                                                                            decoration: BoxDecoration(color: Colors.white),
                                                                            padding: EdgeInsets.symmetric(vertical: 4),
                                                                            child: TextFormField(
                                                                                initialValue: row['1'][label],
                                                                                onChanged: (value) {
                                                                                    row['1'][label] =
                                                                                        value;
                                                                                    print(
                                                                                        row);
                                                                                    print(
                                                                                        row['1']);
                                                                                    updateDetails();
                                                                                },
                                                                                cursorColor: Colors.grey,
                                                                                keyboardType: TextInputType.text,
                                                                                decoration: new InputDecoration(
                                                                                    border:
                                                                                    InputBorder.none,
                                                                                    focusedBorder:
                                                                                    InputBorder.none,
                                                                                    enabledBorder:
                                                                                    InputBorder.none,
                                                                                    errorBorder:
                                                                                    InputBorder.none,
                                                                                    disabledBorder:
                                                                                    InputBorder.none,
                                                                                    isDense:
                                                                                    true,
                                                                                    contentPadding: EdgeInsets.symmetric(
                                                                                        horizontal: 4,
                                                                                        vertical: 4),
                                                                                ),
                                                                                style: TextStyle(fontSize: data.size.width * 0.016))))
                                                                        .toList());
                                                                }).toList()
                                                            ])
                                                    ]),
                                                ])
                                                //row
                                                // ])
                                            ))),
                                ]),
                                // ]),
                            ), //add here
                        ]);
                    }).toList()
                ]))),
Container(
    // add button
    margin: EdgeInsets.only(top: 10),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(2.0),
        color: Colors.grey[200],
        border: Border.all(color: Colors.grey[500], width: 1.5)),
    height: data.size.width * 0.039,
    child: FlatButton(
        onPressed: () {
            setState(() {
                Map < String, dynamic > rowValue = Map < String, dynamic > ();
                rowValue['serialNo'] = '';
                rowValue['1'] = Map < String, String > ();
                rowValue['1']['valueA'] = '';
                rowValue['1']['valueB'] = '';
                rowValue['1']['valueC'] = '';
                rowValue['1']['valueD'] = '';


                this.rowList.add(rowValue);
            });
        },
        child: Text('+ Add Box',
            style: TextStyle(
                color: Colors.grey[900],
                fontWeight: FontWeight.bold,
                fontSize: data.size.width * 0.019))),
),

Hopefully somebody can teach me how to fix it..

Thanks in advance.

2

Answers


  1. In your code you repeat some times the same tables when uses map and are little harder to read, so i made you a version using PaginatedDataTable that you can customize

    Here the code

    import 'package:flutter/material.dart';
    
    class TablePage extends StatefulWidget {
      const TablePage({Key? key}) : super(key: key);
    
      @override
      State<TablePage> createState() => _TablePageState();
    }
    
    class _TablePageState extends State<TablePage> {
      int rowsPerPage = 0;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            backgroundColor: Colors.white,
            body: SizedBox(
              height: MediaQuery.of(context).size.height,
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Visibility(
                        visible: rowsPerPage > 0,
                        child: _CustomTableWithPaginator(
                          rowsPerPage: rowsPerPage,
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(24.0),
                      child: ElevatedButton(
                        onPressed: () {
                          setState(() {
                            rowsPerPage += 1;
                          });
                        },
                        child: const Text('Add'),
                      ),
                    ),
                  ],
                ),
              ),
            ));
      }
    }
    
    // Table
    class _CustomTableWithPaginator extends StatelessWidget {
      final int rowsPerPage;
      const _CustomTableWithPaginator({Key? key, required this.rowsPerPage}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        DataTableSource data = MyData(context);
        final size = MediaQuery.of(context).size;
    
        return Theme(
          data: Theme.of(context).copyWith(cardColor: Colors.black),
          child: PaginatedDataTable(
            source: data,
            columns: [
              DataColumn(
                  label: Expanded(
                flex: 1,
                child: Container(
                    decoration: const BoxDecoration(
                      border: Border(right: BorderSide(color: Colors.grey)),
                    ),
                    alignment: Alignment.center,
                    child: const Text('A')),
              )),
              DataColumn(
                  label: Expanded(
                flex: 1,
                child: Container(
                    decoration: const BoxDecoration(
                      border: Border(right: BorderSide(color: Colors.grey)),
                    ),
                    alignment: Alignment.center,
                    child: const Text('B')),
              )),
              // DataColumn(label: Text('Name')),
              DataColumn(
                label: Expanded(
                  flex: 1,
                  child: Container(
                    decoration: const BoxDecoration(
                      border: Border(right: BorderSide(color: Colors.grey)),
                    ),
                    alignment: Alignment.center,
                    child: const Text('C'),
                  ),
                ),
              ),
              DataColumn(
                label: Expanded(
                  flex: 1,
                  child: Container(
                    decoration: const BoxDecoration(
                      border: Border(right: BorderSide(color: Colors.grey)),
                    ),
                    alignment: Alignment.center,
                    child: const Text('D'),
                  ),
                ),
              )
            ],
            columnSpacing: size.width * 0.1,
            horizontalMargin: 10,
            rowsPerPage: rowsPerPage,
            showCheckboxColumn: false,
          ),
        );
      }
    }
    
    // The "soruce" of the table
    class MyData extends DataTableSource {
      // Generate some made-up data
      final BuildContext context;
    
      late final List<int> _data;
    
      MyData(this.context) {
        _data = listGeenerate();
      }
    
      @override
      bool get isRowCountApproximate => false;
      @override
      int get rowCount => _data.length;
      @override
      int get selectedRowCount => 0;
      @override
      DataRow getRow(int index) {
        return DataRow(
            color: MaterialStateColor.resolveWith(
                (states) => index % 2 == 0 ? const Color(0xFFF7F3F3) : const Color(0xFFeaeaea)),
            cells: [
              DataCell(Container(
                  decoration: const BoxDecoration(
                    border: Border(right: BorderSide(color: Colors.grey)),
                  ),
                  alignment: Alignment.centerRight,
                  child: const Text(''))),
              DataCell(Container(
                  decoration: const BoxDecoration(
                    border: Border(right: BorderSide(color: Colors.grey)),
                  ),
                  alignment: Alignment.centerRight,
                  child: const Text(''))),
              DataCell(Container(
                  decoration: const BoxDecoration(
                    border: Border(right: BorderSide(color: Colors.grey)),
                  ),
                  alignment: Alignment.centerRight,
                  child: const Text(''))),
              DataCell(Container(
                  decoration: const BoxDecoration(
                    border: Border(right: BorderSide(color: Colors.grey)),
                  ),
                  alignment: Alignment.centerRight,
                  child: const Text(''))),
            ]);
      }
    
      List<int> listGeenerate() {
        List<int> data = [];
    
        for (var i = 0; i < 100; i++) {
          data.add(i);
        }
    
        return data;
      }
    }
    
    

    Here you can see it in action
    https://dartpad.dev/?id=063d4bfd08e7d364652485db4076e398

    Login or Signup to reply.
  2. To dynamically add items to a Row in Flutter, you can manage a list of widgets and update it whenever you need to add an item. Here’s a simple example using a StatefulWidget:

    class DynamicRowExample extends StatefulWidget {
      @override
      _DynamicRowExampleState createState() => _DynamicRowExampleState();
    }
    
    class _DynamicRowExampleState extends State<DynamicRowExample> {
      List<Widget> rowItems = []; // List to hold your Row items
    
      void addItemToRow(Widget item) {
        setState(() {
          rowItems.add(item); // Add item to the list
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Row(
          children: rowItems, // Build the Row with items from the list
        );
      }
    }
    

    To add an item to the Row, call addItemToRow() with the widget you want to include. For example:

    addItemToRow(Text('New item'));
    

    Remember to place your Row within a horizontally scrollable widget, like ScrollView, if it may exceed screen width.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search