2

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):

Table

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Lucas
  • 41
  • 4
  • 1
    I think better to load the data in initState() method. does this help? https://flutteragency.com/how-to-load-async-data-on-initstate-method/ so you can use data in multiple widgets. check this too https://stackoverflow.com/questions/51901002/is-there-a-way-to-load-async-data-on-initstate-method – rosh-dev851 Oct 02 '21 at 02:50

1 Answers1

0

Solution:

Thanks to rosh-dev's comment I was able to create a initSate to fix my problem.

This tutorial also helped: Flutter Tutorial for Beginners #25 - Asynchronous Code

The new code looks like this:

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 = [];

    void loadAsset() async {
      final myData = await rootBundle.loadString("assets/routes.csv");
      List<List<dynamic>> csvTable = const CsvToListConverter().convert(myData);
      print(csvTable);
      data = csvTable;
      setState(() {

      });
    }


  @override

  void initState() {
    super.initState();
    loadAsset();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      // floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      // floatingActionButton: FloatingActionButton(
      //     child: const Icon(Icons.refresh),
      //     onPressed: () async {
      //       await loadAsset();
      //     }),
      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(),
        ),
      ),
    );
  }
}

Thanks

Lucas
  • 41
  • 4