[英]How to insert a Data Row in the first line in a DataTable?
我有一個 DataTable,我想在其中添加行。 代碼有效,但數據行被添加到最后一個數據行下方。 我想在頂部添加一行。 我使用了 list.insert(0, element) 但它沒有用。
到目前為止,這是我的代碼:
class _TabelleState extends State<Tabelle> {
List<DataRow> _rowList = [
DataRow(
cells: <DataCell>[
DataCell(Datum()),
DataCell(UebungWidget()),
DataCell(UebungWidget()),
DataCell(UebungWidget()),
]),
];
void _addRow() {
setState(() {
_rowList.insert(0, (DataRow(
cells: <DataCell>[
DataCell(Datum()),
DataCell(UebungWidget()),
DataCell(UebungWidget()),
DataCell(UebungWidget()),
])));
});
}
一般來說,您使用的方法應該按預期工作。 不過,如果您使用TextField
填充DataCell
,在這種情況下,您必須向每個TextField
添加一個GlobalKey
,以便Flutter知道每個DataCell
所屬的位置。
有關Keys
的更多信息,請觀看此 Flutter 迷你教程。
請嘗試以下完整的運行示例
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Tabelle();
}
}
class Tabelle extends StatefulWidget {
@override
_TabelleState createState() => _TabelleState();
}
class _TabelleState extends State<Tabelle> {
List<DataRow> _rowList = [
DataRow(
cells: <DataCell>[
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
]),
];
void _addRow() {
setState(() {
_rowList.insert(0, (DataRow(
cells: <DataCell>[
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
])));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Plan'), actions: [
TextButton(
onPressed: _addRow,
child: Text(
'Neues Training',
style: TextStyle(color: Colors.white),
),
),
]),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
dataRowHeight: 200,
headingRowColor:
MaterialStateColor.resolveWith((states) => Colors.black26),
dataRowColor:
MaterialStateColor.resolveWith((states) => Colors.black26),
columnSpacing: 20,
columns: [
DataColumn(label: Text('seconds', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
], rows: _rowList),
)),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.