以 Switch 作为 Widget 的 Flutter 数据表

问题描述 投票:0回答:1

我想在 DataTable 内部使用 Switch Widget,它从另一个类获取数据。问题是我在主表中引用另一个类来获取数据,并希望在表的特定条目中使用 Switch。 例子: 第 1 行中的开关用于第 1 行中的特定条目。 第 2 行中的开关用于第 2 行中的条目。

enter image description here

但是当逻辑本身在另一个地方时,如何在数据中设置 Switch?

因此我创建了一个这样的数据表:

Stateful stuff ....
....
class MyCountriesState extends State<MyCountries> {
var test = Dummy();
....
body: SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: SizedBox(
      width: 400,
      child: ListView(
        children: [_createDataTable()],
      ),
    ),
   ),
  );
 }

DataTable _createDataTable() {
return DataTable(
  columns: _createColumns(),
  rows: _createRows(),
);
}

List<DataColumn> _createColumns() {
return [
  DataColumn(
    label: Text('Country'),
  ),
  DataColumn(label: Text('Button')),
];
}

List<DataRow> _createRows() {
return test.countries
    .map((link) => DataRow(cells: [
          DataCell(Text(link['country'])),
          DataCell((link["status"]))
        ]))
     .toList();
  }
  }

小部件从另一个 dart 文件获取数据,如下所示:

import 'package:flutter/material.dart';

class Dummy {
List<Map<String, dynamic>> _countries = [
{
  "country": "China",
  "status": Switch(
    inactiveThumbColor: Colors.white,
    activeColor: Colors.white,
    activeTrackColor: Colors.green,
    inactiveTrackColor: Colors.grey,
    value: true,
    onChanged: (value) {},
  ),
  },
  ];
  List<Map<String, dynamic>> get countries => _countries;
  }
flutter datatable switch-statement stateful
1个回答
0
投票

看起来您需要创建一个带有开关的表,这些开关在交互时会切换其状态。下面是一个示例 DataTable 实现,其中每行都包含一个 Switch 小部件。交换机通过更新其在表中的状态来对更改做出反应。 实施方法如下:

  class TableWithSwitch extends StatefulWidget {
  const TableWithSwitch({super.key});

  @override
  State<TableWithSwitch> createState() => _TableWithSwitchState();
}

class _TableWithSwitchState extends State<TableWithSwitch> {
  var countries = [
    Country(name: 'USA', status: false),
    Country(name: 'Greece', status: false),
  ];

  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: [
        DataColumn(label: Text('Country')),
        DataColumn(label: Text('Status')),
      ],
      rows: countries
          .map(
            (country) => DataRow(cells: [
              DataCell(Text(country.name)),
              DataCell(Switch(
                value: country.status,
                onChanged: (value) {
                  setState(() {
                    country.status = value;
                  });
                },
              ))
            ]),
          )
          .toList(),
    );
  }
}

您还需要一个模型来代表每个国家及其开关状态。这是乡村课程:

class Country {
  final String name;
  bool status; // The switch state (true = on, false = off)

  Country({
    required this.name,
    required this.status,
  });
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.