CSV x Flutter, a true love?
Wow, wait a minute. CSV loves Flutter? Flutter loves CSV? Or I love you? (Ignore this please, I’m cringing with embarrassment myself). I don’t know, I’m using the first concept that comes into my mind while writing this. Just think about this as a clickbait, that I successfully baited you into clicking this article.
So, usually when you are working on a mobile app project using Flutter, your client may give you some CSV to visualize or work on your app. You need to understand how to read CSV in Flutter. I am going to give you some example in my project. Here’s a snapshot of the CSV I’m working on.
Bengkulu,PA. Bengkulu,"JI. Jend. Basuki Rakhmat No. 11, Telp. 21225, Bengkulu 38221",
Bengkulu,PA. Curup,"Jl. S. Sukowati No. 24, Telp. 21393",
Bengkulu,PA. Manna,"JI. Kol. Syamsul Bahrun, Telp. 21200, Manna 38515",
Jakarta,PTA. JAKARTA,"J1. Raden Inten II No.3 Duren Sawit, Telp. 86902313 - Fax. 86902314 Jakarta 13440",
Jakarta,PA. Jakarta Barat,"Jl. Plamboyan II No. 2, Telp. 55951554, Jakarta 11730"
(Disclaimer: This is NOT the only way to read CSV in Flutter. I’m just telling you one of the ways)
First, you need to read your file and assign it to a variable.
final dataPengadilan = await rootBundle.loadString("assets/csv/pengadilan.csv");
Now you have the object in Flutter of your CSV file. You may think that we should have a list of list of strings, as it should be. That’s what we are going to do! Okay, to create list of row (list of strings), you can use this code:
List<List<dynamic>> pengadilanNegeriDynamic = CsvToListConverter().convert(dataPengadilan).toList();
Well, as you can see, now it’s a list of dynamic object. Usually, I convert this object into string, so I can use several string methods like split, etc. You can use the map method and then convert every column into string using the toString() method.
pengadilanNegeri = pengadilanNegeriDynamic.map((data) => [
data.toString(), data.toString(), data.toString(),
Voila! Now you have the lists containing your data from your CSV. Hope it’s useful for you, have a nice day!