Flutter: Load and display content from CSV files

Last updated on January 25, 2021 A Goodman Loading... 9 comments

CSV stands for Comma-Separated Values, is a file type widely used to store tabular data (numbers and text) in the plain text where each line will have the same number of fields. In this article, we will explore how to read content from a CSV file in Flutter and display that content on the screen.

Below is the CSV file used in the following example. Just download it before diving into the code:

https://www.kindacode.com/wp-content/uploads/2021/01/kindacode.csv

The content inside this file is simple as below:

Id,Name,Age
1,John Doe,40
2,Kindacode,41
3,Voldermort,71
4,Joe Biden,80
5,Ryo Hanamura,35

The Complete Example

Preivew

This example has a floating button. When this button is pressed, the data from the CSV file will be loaded and displayed in a ListView:

The steps

1. Copy the CSV file to the assets folder (create one if it doesn’t exist) in the root directory of your project. Don’t forget to declare this assets folder in the pubspec.yaml:

# The following section is specific to Flutter.
flutter:
  assets:
    - assets/

2. Install the csv package by adding the following to pubspec.yaml:

dependencies:
  csv: ^4.1.0

Then run:

flutter pub get

3. Add the following to your main.dart:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

import 'package:csv/csv.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<List<dynamic>> _data = [];

  // This function is triggered when the floating button is pressed
  void _loadCSV() async {
    final _rawData = await rootBundle.loadString("assets/kindacode.csv");
    List<List<dynamic>> _listData = CsvToListConverter().convert(_rawData);
    setState(() {
      _data = _listData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Kindacode.com"),
      ),
      body: ListView.builder(
        itemCount: _data.length,
        itemBuilder: (_, index) {
          return Card(
            margin: const EdgeInsets.all(3),
            color: index == 0 ? Colors.amber : Colors.white,
            child: ListTile(
              leading: Text(_data[index][0].toString()),
              title: Text(_data[index][1]),
              trailing: Text(_data[index][2].toString()),
            ),
          );
        },
      ),
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.add), onPressed: _loadCSV),
    );
  }
}

Now run your app and you will see it works as the video above.

If you prefer to implement a Table instead of a ListView, check this guide: Working with Table in Flutter.

Conclusion

In this article, we went over a complete example of reading content from a CSV file and showing that content to the user. If you would like to learn more about Flutter, take a look at the following articles: Set an image Background for the entire screen, 3 Ways to create Random Colors in Flutter, Flutter Transform examples – Making fancy effects.

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
9 Comments
Inline Feedbacks
View all comments
Md. Mubin
Md. Mubin
6 months ago

After getting listview from CSV document if I want to add search option, how should I approach for this code? That means I give a input if it matches with any item in the list (which we got from CSV), it shows that item from the list. Here, data comes… Read more »

Last edited 6 months ago by Md. Mubin
Md. Mubin
Md. Mubin
6 months ago

instead of writing “void _loadCSV() async{ …” I have written only “_loadCSV() async{ …”. That means, I removed void from that line.And In body: I added FutureBuilder in the code attached in the image.

Now, CSV document doesn’t appear. Only circular indicator appears. What should I do?

Last edited 6 months ago by Md. Mubin
Md. Mubin
Md. Mubin
6 months ago
Reply to  A Goodman

Thanks a lot

Md. Mubin
Md. Mubin
6 months ago

What will be the code, if we directly show the list instead of clicking button with search option?

Ali
Ali
9 months ago

You saved my day man

Related Articles