Create CSV File in Flutter App
In this article, we are going to create csv file from our static data, store in local storage and display in our app. You can also check out flutter storage related articles at HERE.
CSV means comma separated values. To create csv file in flutter app, we are using csv flutter package. In this flutter example, we are generating csv file from our soccer player data. We are also using file_picker package to pick csv file from our local storage.
We are accessing all csv files of our local storage using path_provider package and displaying them in flutter list view. So user can tap on any file row and that csv file data is shown to user in our flutter app.
Add required dependencies in pubspec.yaml file
file_picker: ^4.1.4
path_provider: ^2.0.4
Home Screen UI
appBar: AppBar(title: Text(‘Flutter Create CSV Sample’)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
child:
Text(“Display Created CSV”, style: TextStyle(fontSize: 22)),
style: ElevatedButton.styleFrom(
primary: Colors.pinkAccent,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
),
onPressed: () {
generateCSVFile();
},
),
SizedBox(height: 25),
ElevatedButton(
child: Text(“Display CSV list from Local Storage”,
style: TextStyle(fontSize: 22)),
style: ElevatedButton.styleFrom(
primary: Colors.orangeAccent,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => MyCSVFilesListScreen()));
},
),
SizedBox(height: 25),
ElevatedButton(
child: Text(“Pick CSV from Local Storage”,
style: TextStyle(fontSize: 22)),
style: ElevatedButton.styleFrom(
primary: Colors.deepOrangeAccent,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15)),
onPressed: () {
loadCSVFromStorage();
},
),
],
),
),
);

Generate CSV file from our static data
First we store data in our array so we can generate csv file from that data using ListToCsvConverter class.
List<List<String>> data = [
[“Name”, “Position”, “Club Name”, “Country”],
[“Ronaldo”, “Forward”, “Manchester United”, “Portugal”],
[“Lionel Messi”, “Forward”, “Paris Saint-Germain”, “Argentina”],
[“Neymar Jr.”, “Forward”, “Paris Saint-Germain”, “Brazil”]
];
String csvData = ListToCsvConverter().convert(data);
String directory = (await getApplicationSupportDirectory()).path;
String filePath = “$directory/csv-${DateTime.now()}.csv”;
File file = File(filePath);
await file.writeAsString(csvData);
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) {
return MyCSVDisplayScreen(csvFilePath: filePath);
},
),
);
}
Pick CSV File from Local Storage
We can also pick csv file from our local storage using file_picker package.
FilePickerResult filePickerResult = await FilePicker.platform.pickFiles(
allowedExtensions: [‘csv’],
type: FileType.custom,
);
String filePath = filePickerResult.files.first.path;
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) {
return MyCSVDisplayScreen(csvFilePath: filePath);
},
),
);
}

Display CSV Files of Local Storage in List
path_provider package provides access to directories in our local storage, so we can display them in list view.
appBar: AppBar(title: Text(‘CSV Files List’)),
body: Container(
padding: EdgeInsets.only(top: 10),
color: Colors.grey,
child: FutureBuilder(
future: getAllCSVFilesFromStorage(),
builder: (context, AsyncSnapshot<List<FileSystemEntity>> snapshot) {
if (!snapshot.hasData || snapshot.data.isEmpty) {
return Text(“empty”);
}
print(‘${snapshot.data.length} ${snapshot.data}’);
if (snapshot.data.length == 0) {
return Center(
child: Text(‘No CSV File found from Local Storage.’),
);
}
return ListView.builder(
itemBuilder: (context, index) => Card(
child: ListTile(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) =>
MyCSVDisplayScreen(csvFilePath: snapshot.data[index].path),
),
);
},
title: Text(
snapshot.data[index].path,
style: TextStyle(fontWeight: FontWeight.bold),
)),
),
itemCount: snapshot.data.length,
);
},
),
),
);
String localDirectory = (await getApplicationSupportDirectory()).path;
String directoryPath = “$localDirectory/”;
Directory myDirectory = Directory(directoryPath);
List<FileSystemEntity> listCSVFiles = myDirectory.listSync(recursive: true, followLinks: false);
listCSVFiles.sort((a, b) {
return b.path.compareTo(a.path);
});
return listCSVFiles;
}

Display CSV File Data
Here first we read csv data from file and then convert it in list using CsvToListConverter class. So we can display csv file data in rows.
appBar: AppBar(
title: Text(“CSV File Data”),
),
body: FutureBuilder(
future: displayCSVData(csvFilePath),
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
print(snapshot.data.toString());
return snapshot.hasData
? Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: snapshot.data
.map(
(data) => Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
data[0].toString(),
style: TextStyle(fontSize: 16),
),
Text(
data[1].toString(),
style: TextStyle(fontSize: 16),
), Text(
data[2].toString(),
style: TextStyle(fontSize: 16),
),
Text(
data[3].toString(),
style: TextStyle(fontSize: 16),
),
],
),
),
)
.toList(),
),
)
: Center(
child: CircularProgressIndicator(),
);
},
),
);
final csvFile = File(path).openRead();
return await csvFile
.transform(utf8.decoder)
.transform(
CsvToListConverter(),
)
.toList();
}

Pingback: Rive Flutter Animations Example - CodingWithDhrumil
Pingback: Firebase Google Sign In Flutter - CodingWithDhrumil
Pingback: Flutter Localizations Integration - CodingWithDhrumil