I know to add an integer to an integer list is:
List<int> myList = [];
myList.add(1);
I know to add a string to a string list is:
List<String> myList = [];
myList.add("Hello World");
But how do I add a set to my custom list?
Class MyList {
String name;
int price;
MyList({
this.name,
this.price,
});
}
I want myList to be something like this at the end:
List<MyList> myList = [
MyList(
name: 'Chorizo Canapes',
price: 12.99,
),
MyList(
name: 'Cucumber',
price: 8.99,
),
MyList(
name: 'Eggs',
price: 11.99,
),
];
Thanks in advance.
EDIT: Sorry I didn't make myself clear. I want to do something like this:
List<MyList> myList = [];
myList.add({name: 'patato', price: 10})
How do I do this?
So what's problem? You can create this class and you can create this list. Exactly what you want.
Just note:
Working code:
class MyList {
String name;
double price;
MyList({
this.name,
this.price,
});
}
List<MyList> myList = [
MyList(
name: 'Chorizo Canapes',
price: 12.99,
),
MyList(
name: 'Cucumber',
price: 8.99,
),
MyList(
name: 'Eggs',
price: 11.99,
),
];
Upd: Also you can mark parameter in class constructor as "@required" (with adding "import 'package:flutter/widgets.dart';") to make this parameter definitely required.
Example:
import 'package:flutter/widgets.dart';
class MyList {
String name;
double price;
MyList({
@required this.name,
this.price,
});
}
List<MyList> myList = [
MyList(
name: 'Chorizo Canapes',
price: 12.99,
),
MyList(//Error: need parameter "name"
price: 8.99,
),
MyList(
name: 'Eggs',
price: 11.99,
),
];
Upd2: To create your own lists you can write
List<MyList> myList2 = List<MyList>();
myList2.add(
MyList(
name: 'Chorizo Canapes',
price: 12.99,
),
);
or
List<MyList> myList3 = [];
myList3.add(
MyList(
name: 'Cucumber',
price: 8.99,
),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With