skip to Main Content

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?

3

Answers


  1. 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   
    }};
    
    Login or Signup to reply.
  2. 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]
          }
        };
      }
    ...
    }
    
    Login or Signup to reply.
  3. 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,
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search