1

I want to load the list question in question.dart into main.dart. I wrote the code as

final newoptions = quiz[1].options

to get the options('good') in the second of the list question.

But after running it I get this error:

Class '_ImmutableMap<String, Object>' has no instance getter 'options'. Receiver: Instance of '_ImmutableMap<String, Object>' Tried calling: options

How do I solve this?

question.dart

class Question {
  final int id;
  final String options;


  Question({required this.id, required this.options});
}

const List quiz = [
  {
    "id": 1,
    "options": 'hello',
  },
  {
    "id": 2,
    "options": 'good',
  },
  {
    "id": 3,
    "options": 'abc',
  },
];

main.dart

class Body extends StatefulWidget {
  @override
  _Body createState() => _Body();
}

class _Body extends State<Body> {
  final newoptions = quiz[1].options;
  ...
}
1
  • Try it this way final newoptions = quiz[1]['options'] Commented Nov 7, 2021 at 19:55

1 Answer 1

1
const List quiz = [
  {
    "id": 1,
    "options": 'hello',
  },
  {
    "id": 2,
    "options": 'good',
  },
  {
    "id": 3,
    "options": 'abc',
  },

The above code is not a list of the class Question, it is a list of maps, if you want the list to be a list of Questions, it would look like this:

const List quiz = [
  Question(
    id: 1,
    options: 'hello',
  ),
  Question(
    id: 2,
    options: 'good',
  ),
  Question(
    id: 3,
    options: 'abc',
  ),

You can either change the list to what I just showed you, or change this line:

final newoptions = quiz[1].options

to this in order to access the map's values:

final newoptions = quiz[1]['options'];

If you do decide to not change the list into instances of Question, then you can get rid of the Question class, because you don't use it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.