Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

dart - Stacking Multiple Rows of Strings in Csv in Flutter

I have this code which should stack multiple rows one on top of another in Flutter with the CSV library.

exportCsv(List<Drink> drinksFeed, List<Alcohol> alcoholFeed
 ) async {
List<List<dynamic>> rows = List<List<dynamic>>();
for (int i = 0; i < drinksFeed.length; i++) {
  List<dynamic> row = List();
  row.add(drinksFeed[i].id);
  row.add(drinksFeed[i].name);
  row.add(drinksFeed[i].description);
  row.add(drinksFeed[i].price);
  rows.add(row);
  setState(() {
    drinksFeed = drinkFeedback;
  });

}
List<List<dynamic>> alcoholRows = List<List<dynamic>>();
for (int i = 0; i < alcoholFeed.length; i++) {
  List<dynamic> row = List();
  row.add(alcoholFeed[i].id);
  row.add(alcoholFeed[i].name);
  row.add(alcoholFeed[i].description);
  row.add(alcoholFeed[i].price);
  alcoholRows.add(row);
  setState(() {
    alcoholFeed = alcoholFeedback;
  });

}


  String drinkCsv = const ListToCsvConverter().convert(rows);
  String alcoholCsv = const ListToCsvConverter().convert(alcoholRows);
  f.writeAsString(drinkCsv);
  f.writeAsString(alcoholCsv);


}

}

As you can see, it takes each element from a list and writes it as a string, but for some reason, it isn't stacking rows on top of one another (drinkCsv and alcoholCsv), it just shows the drinksCsv elements in the CSV file. This isn't the full code, because it's too long and I don't think it's relevant to show CSV export, but this should be enough.

So my question is, is it possible to stack multiple elements one on top of another in 1 csv file (drinkCsv + alcoholCsv in this case).

question from:https://stackoverflow.com/questions/65924960/stacking-multiple-rows-of-strings-in-csv-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe awaiting before writing again could solve the problem, also changing the mode to append so it continues writing at the end of the file

await f.writeAsString(drinkCsv);
await f.writeAsString(alcoholCsv, mode: FileMode.append);

the best solution I can come up is combining the 2 lists before doing the convert (I haven't used that ListToCsvConverter().convert() so I'm not sure how does the string result looks like)

String fileCsv = const ListToCsvConverter().convert([...rows, ...alcoholRows]); 

await f.writeAsString(fileCsv);

That way maybe the converter do the correct append between the rows when converting to string


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...