Gerard Horgan
2 min readNov 20, 2018

Getting data from GoogleSheets and displaying it elegantly using the PaginatedDataTable class in Flutter

In this blog, we’re going make an app where the data for the app originates in a googlesheet. We’re going to first convert our googlesheets file to json. Then we’re going hit an URL and download that JSON data and present it using a material design widget called PaginatedDataTable. We’re going to use data from the CSO (the central statistics office of Ireland).

First of all I copied the “table” data from the CSO and pasted it into googlesheets. I used a third party plugin for converting the data to json in googlesheets. You can check it out here (check out comments to freeze the top row!!….the column headers ). It returns an array of objects, which suits our needs.

Now over to Flutter.

Here are the methods for fetching the data and parsing the response.

Future<List<Result>> fetchResults(http.Client client) async {
final response = await client.get('https://api.myjson.com/bins/j5xau');

// Use the compute function to run parseResults in a separate isolate
return compute(parseResults, response.body);
}

// A function that will convert a response body into a List<Result>
List<Result> parseResults(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

return parsed.map<Result>((json) => Result.fromJson(json)).toList();
}

and here we implement those methods in a function called getData(). You can call this class in the build method in a class.

Future<void> getData() async {
final results = await fetchResults(http.Client());
if (!isLoaded) {
setState(() {
_resultsDataSource = ResultsDataSource(results);
isLoaded = true;
});
}
}

The Paginated class has a required field in it’s constructor called DataTableSource. And this is where the magic happens! We extend this class with ResultsDataSource and this class is used to populate the data table. Other properties of the PaginatedDataTable class include columns where we put the column names

columns: <DataColumn>[
DataColumn(
label: const Text('Sex'),
onSort: (int columnIndex, bool ascending) => _sort<String>(
(Result d) => d.sex, columnIndex, ascending)),
DataColumn(
label: const Text('Region'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<String>(
(Result d) => d.region, columnIndex, ascending)),
DataColumn(
label: const Text('Year'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>(
(Result d) => d.year, columnIndex, ascending))
etc..

Have a look at this gist