best_of_man
best_of_man

Reputation: 728

How can I define a variable like JSON object in Flutter?

What I am trying to do is creating a variable that can hold the following data:

questiion = { 'title': '',
            'description': '',
            'questionTitle': '',
            'option1Text': '',
            'option2Text': '',
            'option3Text': '',
            'option1Correctness': false,
            'option2Correctness': false,
            'option3Correctness': false,
            'questionNumber' : 1 }

Then I can get these values from forms and save the users input data into them like following:

          onSaved: (value) {
            question['title'] = value!;
          },

I don't know if there is any data type in flutter for doing that? I know there is Map<> but it can only consist 1 pair of key:value. Maybe I should create a nested Map? Or there is a better way?

Upvotes: 1

Views: 2436

Answers (2)

diegoveloper
diegoveloper

Reputation: 103541

Using Map<String,dynamic> should be right way (if you don't want to create a class).

Like this:


    final question = <String, dynamic>{
      'title': '',
      'description': '',
      'questionTitle': '',
      'option1Text': '',
      'option2Text': '',
      'option3Text': '',
      'option1Correctness': false,
      'option2Correctness': false,
      'option3Correctness': false,
      'questionNumber': 1
    };

    print(question);

The print will give you this output:

{title: , description: , questionTitle: , option1Text: , option2Text: , option3Text: , option1Correctness: false, option2Correctness: false, option3Correctness: false, questionNumber: 1}

Upvotes: 3

sigmapie8
sigmapie8

Reputation: 467

Yes, you can go for a nested key-value map, or you can also keep everything in an object.

This ans might help you: Json parsing in dart (flutter)

Upvotes: 0

Related Questions