I am trying to create a .csv file using a List<Stuff> type list. In order to use ListToCsvConverter(), I need a List<Dynamic>.
How do I convert a List<Stuff> to a List<Dynamic> so that I can convert it to .csv with ListToCsvConverter()?
"Stuff" model below:
class Stuff {
int id;
String stuffType;
String stuffSize;
String stuffTime;
Stuff({this.id, this.stuffType, this.stuffSize, this.stuffTime});
}
Your problem is that ListToCsvConverter() is not accepting a List<Stuff> but a List<List<dynamic>>.
The first level List is the list of rows for your csv, while the second level List is the list of cells in each row.
I added a getter csvRow in your Stuff class and map to the rows just before calling ListToCsvConverter():
Full source code:
import 'package:faker/faker.dart';
import 'package:csv/csv.dart';
void main() {
String csv = const ListToCsvConverter()
.convert(stuffList.map((stuff) => stuff.csvRow).toList());
print(csv);
}
class Stuff {
int id;
String stuffType;
String stuffSize;
String stuffTime;
Stuff({this.id, this.stuffType, this.stuffSize, this.stuffTime});
List<dynamic> get csvRow => [id, stuffType, stuffSize, stuffTime];
}
final faker = Faker();
final stuffList = List.generate(
100,
(index) => Stuff(
id: faker.randomGenerator.integer(999999, min: 100000),
stuffType: faker.person.name(),
stuffSize: '${faker.randomGenerator.integer(1000)}MB',
stuffTime: faker.date.toString(),
));
Posting a clear answer for people to see.
Initial List is "stuffList".
How do I convert a List<Stuff> to a List<Dynamic> so that I can convert it to .csv with ListToCsvConverter()?
//Create a new dynamic list
List<List<dynamic>> rows = List<List<dynamic>>();
//Convert stuffList to List<List<dynamic>>
for (int i = 0; i < listStuff.length; i++) {
List<dynamic> row = List();
row.add(listStuff[i].id);
row.add(listStuff[i].stuffType);
row.add(listStuff[i].stuffSize);
row.add(listStuff[i].stuffTime);
rows.add(row);
}
//convert the list to csv
final csv = const ListToCsvConverter().convert(rows);
Related
For each article the user browses, I want to save the ID information.
I am using getstorage my code sample is below.
I can not find a true way also, i am looking best way to save id's list.
final box = GetStorage();
List<String> myFavoriteList = [];
saveFav(String id) {
myFavoriteList.add(id);
box.write('favoriteArticles', myFavoriteList.cast<String>());
}
ifExistInFav(String id) async {
bool ifExists = false;
List<String> my = (box.read('favoriteArticles').cast<String>() ?? []);
ifExists = my.contains(id) ? true : false;
return ifExists;
}
First, you need to define your list and convert it to String.
** note that if you use a custom data type ensure you convert your model to String.
then you can use the following to store a List as a String object
final box = GetStorage('AppNameStorage');
/// write a storage key's value
saveListWithGetStorage(String storageKey, List<dynamic> storageValue) async => await box.write(/*key:*/ storageKey, /*value:*/ jsonEncode(storageValue));
/// read from storage
readWithGetStorage(String storageKey) => box.read(storageKey);
the saving procee implemention:
saveList(List<dynamic> listNeedToSave) {
/// getting all saved data
String oldSavedData = GetStorageServices().readWithGetStorage('saveList');
/// in case there is saved data
if(oldSavedData != null){
/// create a holder list for the old data
List<dynamic> oldSavedList = jsonDecode(oldSavedData);
/// append the new list to saved one
oldSavedList.addAll(listNeedToSave);
/// save the new collection
return GetStorageServices().saveListWithGetStorage('saveList', oldSavedList);
} else{
/// in case of there is no saved data -- add the new list to storage
return GetStorageServices().saveListWithGetStorage('saveList', listNeedToSave);
}
}
/// read from the storage
readList() => GetStorageServices().readWithGetStorage('saveList');
then the usage:
onTap: () async => debugPrint('\n\n\n read list items ${jsonDecode(await readList())}\n\n\n', wrapWidth: 800),
I have a Flutter app in which I make an http request, which brings me json data. Afer formatting it with a package I get a list of lists of dynamic type. Here´s what it looks like:
[[2016-04-01, 85.5254], [2016-05-01, 89.1118], [2016-06-01, 91.8528], [2016-07-01, 93.7328], [2016-08-01, 93.9221], [2016-09-01, 95.0014], [2016-10-01, 97.2428], [2016-11-01, 98.8166]]
So I created a class named IpcData, which recieves a String and a double.
class IpcData {
final String date;
final double value;
IpcData(this.date, this.value);
}
So we could guess that an IpcData instance would look like the following:
IpcData(2016-08-01, 93.9221)
I can´t figure out how, but I´d like to have a method that using the information from the List<List<dynamic>> to return a List<IpcData>, that would looke like:
[IpcData(2016-08-01, 93.9221), IpcData(2016-08-01, 93.9221), IpcData(2016-08-01, 93.9221),]
You can use .map function on the original list to construct the new one. Something like this.
class IpcData {
final String date;
final double value;
IpcData(this.date, this.value);
#override
String toString() {
return '$date -> $value';
}
}
void main() {
List<List<dynamic>> initList = [
['2016-04-01', 85.5254], ['2016-05-01', 89.1118], ['2016-06-01', 91.8528],
['2016-07-01', 93.7328], ['2016-08-01', 93.9221], ['2016-09-01', 95.0014],
['2016-10-01', 97.2428], ['2016-11-01', 98.8166], ['2016-12-01', 99.8166]
];
List<IpcData> ipcList = initList.map((e) => IpcData(e[0], e[1])).toList();
print(ipcList);
}
class Article{
final String id;
final List<ArticleArray> arrays;
}
class ArticleArray {
final String id;
final String array;
}
TextFormField(
onChanged: (_searchinput) {
List<String> searcharray = _searchinput.split(',');
),
_articlesForDisplay = _articles.where((article){
for(int i = 0; i < article.arrays.length; i++)
{
searchinit = article.arrays[i].arrays.toLowerCase();
}
return searchinit.contains(
RegExp(//necessary code here, caseSensitive: false),
);})
basically what i am trying to do is i am trying to search
array by array like:
-Textformfields follows the user input and every time "," is entered,i
put that word into "searcharray".
-Then i initiate a search in my function(total code is not needed to write here,
i included necessary functions),i try to use "regexp" function to search for the arrays
in my article archives.
Example:
articles[0].arrays[0].array = 'a1'
articles[0].arrays[1].array = 'a2'
articles[1].arrays[0].array = 'a1'
articles[1].arrays[1].array = 'b2'
searcharray = ['a1','b2']
Here,basically what i try to do is i try to search my article arrays by every list of arrays as possible so it matches the right one. Thats what i want.
Not sure I understand your specific requirements.
Here, I define a RegExp that I try to match to at least one item of my data.
void main() {
List<String> data = ['a1','b2', 'c3', 'a4', 'a5', 'd6'];
RegExp exp = new RegExp(r"(a\d+)");
print(data.any((item) => exp.hasMatch(item)));
}
I want to store list of structure data in a vector and that data comes from a request payload as:
{
"Id":"1",
"Name":"name1",
"Salary":"10000",
"Contact":"1937282912"
}
I have the following structure declaration in js folder.
struct data {
string id;
string name;
string salary;
string contact;
};
struct data1 {
vector<data> vect;
void put();
};
Then I have a method definition for the above structure:
void data1::put()
{
vector<string> details;
for(int i=0; i < vect.size(); i++) {
details.push_back(vect[i].id);
details.push_back(vect[i].name);
details.push_back(vect[i].salary);
details.push_back(vect[i].contact);
}
}
Then there is a method defined in another structure (in different folder called bk folder) which is taking all data from payload as follows:
static data dglobal;
static data1 d1global;
string getData(string &payload) {
data dlocal;
dglobal=dlocal;
data1 d1local;
d1global=d1local;
// I am making JSON object for accepting JSON data from payload then
string sid=jsonobject["id"]....;
string name=jsonobject["name"]...;
string salary=jsonobject["salary"]...;
string contact=jsonobject["contact"]..;
dglobal.id = did;
dglobal.name = name;
dglobal.salary = salary;
dglobal.contact = contact;
d1global.vect.push_back(dglobal);
d1global.put();
}
Hey guys do not focus above way of accepting JSON data because everything okay with that I just want to store all data which coming from request payload.Each time when I hit URL from rest client there is always erase previous data and store recently hit data but I want to keep all data which is already store and currently Storing data,how can I do this?
I'll like to parse column zero in a csv file to a particular datatype, in this example a Date Object.
The method below is what I use currently to parse a csv file but I don't know how to incorporate this requirement.
import java.sql.Date;
public class Data {
#Parsed(index = 0)
private Date date;
}
}
public <T> List<T> convertFileToData(File file, Class<T> clazz) {
BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
CsvParserSettings settings = new CsvParserSettings();
settings.setProcessor(rowProcessor);
settings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(settings);
parser.parseAll(file);
return rowProcessor.getBeans();
}
All you need is to define the format(s) of your date and you are set:
#Format(formats = {"dd-MMM-yyyy", "yyyy-MM-dd"})
#Parsed(index = 0)
private Date date;
}
As an extra suggestion, you can also replace a lot of your code by using the CsvRoutines class. Try this:
List<T> beanList = new CsvRoutines(settings).parseAll(clazz, file);
Hope it helps.