Flutter load and display csv file content. Previously we have seen how to load JSON file in flutter and display it’s content.
We will be using a csv package for it. Let’ go ahead and download the csv package using the below command.
flutter pub add csv
And then run
flutter pub get
After that in your pubspec.yaml file make sure, you have the correct path for the assets.
And then your projects rool folder make sure you have a folder name assets and inside this you have mycsv.csv file.
Get the csv file content and copy paste in the assets/mycsv.csv
Id,Name,Age
1,John Doe,40
2,Dbestech,41
3,Voldermort,71
4,Joe Biden,80
5,Ryo Hanamura,35
Then we will start actual coding. The core part is loading and saving the data in local variable and use the data in the body section.
The most important part is
List<List<dynamic>> _data = [];
void _loadCSV() async {
final _rawData = await rootBundle.loadString("assets/mycsv.csv");
List<List<dynamic>> _listData =
const CsvToListConverter().convert(_rawData);
setState(() {
_data = _listData;
});
}
_data will hold csv file content.
_loadCSV() method loads the data from the local asset file calling CsvToListConverter().convert() does the magic for converting csv file to list.
You can use the package import ‘package:csv/csv. dart’; Inside you have a method called CsvToListConverter() , using this you can convert your CSV data to a nice list.
Flutter load CSV file and display complete code
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,
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 = [];
void _loadCSV() async {
final _rawData = await rootBundle.loadString("assets/mycsv.csv");
List<List<dynamic>> _listData =
const CsvToListConverter().convert(_rawData);
setState(() {
_data = _listData;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("dbestech"),
),
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),
// Display the contents from the CSV file
);
}
}
App that loads json files from local storage to firebase