如何动态地向表中添加项目?

Sar*_*ler 3 dart flutter

有人知道如何在Flutter中动态地将更多行添加到DataTable中。如您所见,我的代码非常“硬编码” [行:11-31]。
应该有一种方法可以摆脱编写越来越多的DataRows的麻烦。

码:

class DataTableWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: [
        DataColumn(label: Text('Patch')),
        DataColumn(label: Text('Version')),
        DataColumn(label: Text('Ready')),
      ],
      rows: <DataRow>[
        DataRow(
          cells: <DataCell>[
            DataCell(Text('AAAAAA')),
            DataCell(Text('1')),
            DataCell(Text('Yes')),
          ],
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('BBBBBB')),
            DataCell(Text('2')),
            DataCell(Text('No')),
          ],
        ),
        DataRow(
          cells: <DataCell>[
            DataCell(Text('CCCCCC')),
            DataCell(Text('3')),
            DataCell(Text('Yes')),
          ],
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

dsh*_*tjr 11

你可以这样做:**

class DataTableWidget extends StatelessWidget {

      List results=[] ;
       intState((){
         super.iniState();
            this.getSale();
 })
Future<String> getData () async {

var response = await http.get(
  "$saleUrl/?format=json",

);
setState(() {
  var dataConvertedToJson = 
json.decode(utf8.decode(response.bodyBytes));
  results = dataConvertedToJson['results'];
});
 print('${results.length}');
  return "successful";
 }
  DataRow _getDataRow(result) {
    return DataRow(
      cells: <DataCell>[
        DataCell(Text(data["text1"])),
        DataCell(Text(data["text2"])),
        DataCell(Text(data["text3"])),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: [
        DataColumn(label: Text('Patch')),
        DataColumn(label: Text('Version')),
        DataColumn(label: Text('Ready')),
      ],
      rows: List.generate(
          results.length, (index) => _getDataRow(results[index])),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


guy*_*guy 9

您可以使用

listOfColumns.map(((element) => DataRow(...))).toList()
Run Code Online (Sandbox Code Playgroud)

这是使用此方法的代码。

class DataTableWidget extends StatelessWidget {
  final List<Map<String, String>> listOfColumns = [
    {"Name": "AAAAAA", "Number": "1", "State": "Yes"},
    {"Name": "BBBBBB", "Number": "2", "State": "no"},
    {"Name": "CCCCCC", "Number": "3", "State": "Yes"}
  ];
//  DataTableWidget(this.listOfColumns);     // Getting the data from outside, on initialization
  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: [
        DataColumn(label: Text('Patch')),
        DataColumn(label: Text('Version')),
        DataColumn(label: Text('Ready')),
      ],
      rows:
          listOfColumns // Loops through dataColumnText, each iteration assigning the value to element
              .map(
                ((element) => DataRow(
                      cells: <DataCell>[
                        DataCell(Text(element["Name"])), //Extracting from Map element the value
                        DataCell(Text(element["Number"])),
                        DataCell(Text(element["State"])),
                      ],
                    )),
              )
              .toList(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


srk*_*ing 5

底层数据结构(可能是列表)是您需要担心更改的内容。像表格这样的 UI 元素只需观察即可。setState() 函数会通知 UI 在您更新列表后重新查看。

这是一个从 flutter 文档示例中破解的工作示例。单击按钮添加行。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Add Rows',
      home: MyHomePage(title: 'Add Rows'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<DataRow> _rowList = [
    DataRow(cells: <DataCell>[
      DataCell(Text('AAAAAA')),
      DataCell(Text('1')),
      DataCell(Text('Yes')),
    ]),
  ];

  void _addRow() {
    // Built in Flutter Method.
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below.
      _rowList.add(DataRow(cells: <DataCell>[
        DataCell(Text('BBBBBB')),
        DataCell(Text('2')),
        DataCell(Text('No')),
      ]));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DataTable(columns: [
          DataColumn(label: Text('Patch')),
          DataColumn(label: Text('Version')),
          DataColumn(label: Text('Ready')),
        ], rows: _rowList),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _addRow,
        label: Text('Add Row'),
        backgroundColor: Colors.green,
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这为我构建了

flutter build web
Run Code Online (Sandbox Code Playgroud)

然后运行

flutter run -d chrome
Run Code Online (Sandbox Code Playgroud)