Reputation: 728
I have a Map
like following:
final Map<String, dynamic> question = {
'rating': {
'added': false,
}
};
And I want to use it inside another Map
like below:
final Map<String, dynamic> book = {
'detail': {
'questions': [
question // here I need to have a list of the above Map
]
}
};
But it doesn't work. How can I use another Map
's definition inside a Map
I am gonna define as it's parent?
Upvotes: 0
Views: 215
Reputation: 28
try to put the spread operator "..." like this:
final Map<String, dynamic> book = {
'detail': {
'questions': [...{question}] // here I need to have a list of the above Map
}};
[EDIT] try this instead,it should work fine now :
late final Map<String, dynamic> book = {
'detail': {
'questions': [...{question}] // here I need to have a list of the above Map
}};
Upvotes: 1
Reputation: 391
I tried your code and it works just fine, but as mentioned by @Soliev, it is recommended to use classes instead of plain maps. Here is an example of how you can use your code with classes. This is a very simple example, but later on, you can research data classes, toJson, and FromJson methods, and add them to your classes if needed.
class Question {
final Rating rating;
Question({
required this.rating,
});
}
class Rating {
final bool added;
Rating({
required this.added,
});
}
class BookDetail {
final List<Question> questions;
BookDetail({
required this.questions,
});
}
class Book {
final BookDetail detail;
//You can add more fields
//final String name
//final String author
Book({
required this.detail,
});
}
Upvotes: 1
Reputation: 1376
The instance member 'question' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
Use it like this:
class _MyHomePageState extends State<MyHomePage> {
late final Map<String, dynamic> question;
late final Map<String, dynamic> book;
@override
void initState() {
super.initState();
question = {
'rating': {
'added': false,
}
};
book = {
'detail': {
'questions': [question, question, question, question]
}
};
}
...
}
Upvotes: 0