'Add row Dynamically in Flutter
I have this table using DataTable in Flutter and I want to make a button that adds new row under the 2 initial lines .
How can I achieve this ?
DataTable(
columns: <DataColumn>[
DataColumn(
label: Flexible(
child: Text("",
maxLines: 5,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold)),
)),
DataColumn(
label: Expanded(
flex: 4,
child: Text("Nom de l'article",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold)),
)),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)), DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)),
],
),
DataRow(
cells: <DataCell>[
DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)),
],
)
],
),
Solution 1:[1]
Create a variable and store data there. Next build rows of the variable content.
If you wish to edit the data use Statefull Widget or state management.
After converting to Statefull Widget:
ElevatedButton(
onPressed: () => setState(
() => rowData.add({'id': '103', 'title': 'NewItem', 'author': 'You'}),
),
child: Text('Add new item'),
)
Read on Flutter documentation its really nicely written: here
also datatable article
import 'package:flutter/material.dart';
class TestWidget extends StatelessWidget {
TestWidget({Key? key}) : super(key: key);
final rowData = [
{'id': '100', 'title': 'Flutter Basics', 'author': 'David John'},
{'id': '102', 'title': 'Git and GitHub', 'author': 'Merlin Nick'},
];
@override
Widget build(BuildContext context) {
return DataTable(
columns: <DataColumn>[
DataColumn(
label: Flexible(
child: Text("",
maxLines: 5,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold)),
)),
DataColumn(
label: Expanded(
flex: 4,
child: Text("Nom de l'article",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold)),
)),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)),
DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)),
],
),
DataRow(
cells: <DataCell>[
DataCell(TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
)),
],
),
...rowData
.map((item) => DataRow(cells: [
DataCell(Text('#' + item['id'].toString())),
DataCell(Text(item['title'] ?? '')),
DataCell(Text(item['author'] ?? '')),
DataCell(FlutterLogo())
]))
.toList()
],
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jan-Stepien |
