Flutter DataTable - Tap on row

前端 未结 4 1521
小鲜肉
小鲜肉 2020-12-16 06:25

I am using Flutter DataTables to display list of items in cart. Now I want to edit the quantity of any selected row. Is there a way to get the information of the row user ha

4条回答
  •  长情又很酷
    2020-12-16 07:18

    You can get it done by using a closure , a function object that has access to variables in its lexical scope and basically 'remembers' them.

    Change the 'onTap' property of your DataCell to :

    onTap: (){_getSelectedRowInfo(itemRow.itemName,itemRow.itemPrice);},
    

    and modify the _getSelectedRowInfo function to accommodate the following changes:

    void _getSelectedRowInfo(dynamic name,dynamic price) {
        print('Name:$name  price: $price');
      }
    

    Here's how the entire thing should look like:

    class _DataTableSampleState extends State {
    
      void _getSelectedRowInfo(dynamic name,dynamic price) {
        print('Name:$name  price: $price');
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('DataTable Sample'),
          ),
          body: Container(
            child: DataTable(
              onSelectAll: (b) {},
              sortAscending: true,
              columns: [
                DataColumn(
                  label: Text('Item'),
                ),
                DataColumn(
                  label: Text('Price'),
                ),
              ],
              rows: items
                  .map(
                    (itemRow) => DataRow(
                  cells: [
                    DataCell(
                      Text(itemRow.itemName),
                      showEditIcon: false,
                      placeholder: false,
                    ),
                    DataCell(
                      Text(itemRow.itemPrice),
                      showEditIcon: true,
                      placeholder: false,
                      onTap: (){_getSelectedRowInfo(itemRow.itemName,itemRow.itemPrice);},
                    ),
                  ],
                ),
              )
                  .toList(),
            ),
          ),
        );
      }
    }
    
    class ItemInfo {
      String itemName;
      String itemPrice;
    
      ItemInfo({
        this.itemName,
        this.itemPrice,
      });
    }
    
    var items = [
      ItemInfo(
        itemName: 'Item A',
        itemPrice: '250',
      ),
      ItemInfo(
        itemName: 'Item B',
        itemPrice: '100',
      ),
      ItemInfo(
        itemName: 'Item C',
        itemPrice: '150',
      ),
    ];
    

提交回复
热议问题