I am using flutter datatable.
I am using List<DataColumn> and List<DataRow>
.
After I click a button, I need to see the table populated.
I am getting the error during runtime: 'columns.isNotEmpty' is not true
I cannot find the source of the error.
Please advise how to fix the error.
Thank You,
This is my code:
class MyHomePageState extends State<MyHomePage> {
List<DataColumn> myDataColumnList = [];
List<DataRow> myDataRowList = [];
int i = 0;
@override
void initState() {
super.initState();
}
addToList(){
setState(() {
myDataColumnList.add(DataColumn(label: Text('Column Label: '+i.toString())));
myDataRowList.add(DataRow(cells: <DataCell>[DataCell(placeholder: true,Text('x1: '+i.toString())),DataCell(placeholder: true,Text('x2: '+i.toString()))]));
i = i + 1;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(resizeToAvoidBottomInset: true,
body: LayoutBuilder(
builder: (BuildContext ctx, BoxConstraints constraints) {
return Container(child: SingleChildScrollView(child: Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly,mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextButton(onPressed: addToList, child: const Text('addToList')),
Table(children: [TableRow(children: <Widget>[ListView.builder(shrinkWrap: true,itemBuilder: (BuildContext context, int index) {
return DataTable(columns: myDataColumnList, rows: myDataRowList);
},)])]),],),),);
})));
}
}
2
Answers
Remove updating
myDataColumnList
in setState method,Instead, you can initialize your
myDataColumnList
in initstateTry something like:
Add this condition to avoid the error the first time you run the app.