I am trying to create a table from an imported CSV file, that I can latter call upon for data. I followed this tutorial here as a starting point.
So far I have managed to create the table, but it only generates once you press a button. What I would like to do is for the table to be loaded as soon as the app starts.
My code is almost identical to the one in the tutorial, but either way, here it is:
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'package:flutter/services.dart' show rootBundle;
class TableLayout extends StatefulWidget {
const TableLayout({Key key}) : super(key: key);
@override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/routes.csv");
List<List<dynamic>> csvTable = const CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: const Text("Bus Routes"),
),
body: SingleChildScrollView(
child: Table(
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color: Colors.blueGrey,
child: Padding(
padding: const EdgeInsets.all(1.0),
child: Text(
row.toString(),
style: const TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
With this code, the following screen is generated (once you push the button):
I'm not worried about the look of the table as the user wont actually be seeing it in the end. Instead it will be used to retrieve data for use in other screens of my app. I understand that it is only generated on the button press because of this line:
onPressed: () async {
await loadAsset();
I am unsure on how to run this when the app starts rather than when the button is pressed.