Flutter: Load and display content from CSV files

Last updated on March 5, 2022 A Goodman Loading... 10 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 executing the following command:

flutter pub add csv

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(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @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 =
        const CsvToListConverter().convert(_rawData);
    setState(() {
      _data = _listData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Kindacode.com"),
      ),
      // Display the contents from the CSV file
      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: const Icon(Icons.add), onPressed: _loadCSV),
    );
  }
}

Now run your app and you will see it works as in 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:

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

Subscribe
Notify of
guest
10 Comments
Inline Feedbacks
View all comments
Texter
Texter
4 months ago

You have very useful and interesting content. I want to take this code as a basis. But I don’t know how to do the following. I need to pass certain information from a converted csv file to the widget of my application. 1. In particular, the data from the first… Read more »

Md. Mubin
Md. Mubin
1 year 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 1 year ago by Md. Mubin
Md. Mubin
Md. Mubin
1 year 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 1 year ago by Md. Mubin
Md. Mubin
Md. Mubin
1 year ago
Reply to  A Goodman

Thanks a lot

Md. Mubin
Md. Mubin
1 year ago

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

Ali
Ali
1 year ago

You saved my day man

Related Articles