hi i am starting to work with flutter and now i have the following problem.
I am getting a dynamic list in is a collection from firebase
and I need to create a new data array from this list, I am trying something like this:
static Future<File> generate(List<dynamic> products) async {
var listArray = [];
for (var i = 0; i < products.length; i ) {
listArray.add([
products[i].quantity,
products[i].name,
products[i].price,
products[i].price,
]);
}
}
It is an example of what I tried in my function and the new array that I need to generate, in the end I need to get an array that looks like this:
final listArray = [
[
'1',
'Coffee',
'10',
'10,
],
[
'2',
'Blue Berries',
'30',
'60'
],
];
I haven't worked much with collections or list of data in flutter and I'm getting the following error: The argument type 'List<dynamic>' can't be assigned to the parameter type 'List<List<dynamic>>'.
any idea how i can fix this? Thank you
CodePudding user response:
You are inserting list items inside the list(listArray).
Convert
var listArray = [];
Into
List<List<dynamic>> listArray
As I dont see context fully, I have another suggestion.
This error maybe caused for the following reason:
Wherever you call the generate function you are passing it List<List as argument for the parameter with the type of List.
So please check the place where you are calling generate function, make sure that you are passing the argument with the expected/correct type.
CodePudding user response:
Looking at your code, the issue seems to be the following
static Future<File> generate(List<dynamic> products) async {
var listArray = [];//Here type inference make listArray a 'List<dynamic>'
for (var i = 0; i < products.length; i ) {
listArray.add([ //Here you add an array to your array, hence the 'List<List<dynamic>>'
products[i].quantity,
products[i].name,
products[i].price,
products[i].price,
]);
}
}
which could be fixed by using a forcing the type like this :
static Future<File> generate(List<dynamic> products) async {
//Here you declare the type as List<List<dynamic>>
//(growable: true is needed to allow to add new element to it)
List<List<dynamic>>listArray = List<List<dynamic>>.empty(growable: true);
for (var i = 0; i < products.length; i ) {
listArray.add([
products[i].quantity,
products[i].name,
products[i].price,
products[i].price,
]);
}
}```