Home > OS >  Creating interface in dart like typescript
Creating interface in dart like typescript

Time:05-14

I am from typescript background and new to dart, in typescript we are able to define interface and attach those types to the required variable which have the correct format would work, for example

interface Answer {
  text: string;
  value: number;
}

interface Question {
  question: string;
  answers: Answer[
}


const questions: Question[] = [
    {
      'question': "What's your fav color?",
      'answers': [
        {
          'text': 'one',
          'value': 1,
        },
        {
          'text': 'one',
          'value': 2,
        },
        {
          'text': 'one',
          'value': 3,
        },
        {
          'text': 'one',
          'value': 4,
        },
      ],
    },
];

This would just do for typescript I will get no errors.

But in dart I am not able to achieve the same thing. Below is my dartpad code. please help me I am getting an error saying The element type 'Map<String, Object>' can't be assigned to the list type 'SingleQuestion'.

Is there any resource which can help me overcome typescript to dart migration will be best for the suggestions.

https://dartpad.dev/?id=bcef24b3cbd94a2150454cf0edea3704

CodePudding user response:

Actually your data is json. Then use Object class for your data and fromJson function for SingleQuestion. Your main function like this:

void main() {
  Object data = {
      'question': "What's your fav color?",
      'answers': [
         {
           'text': 'red',
           'value': 1,
         },
         {
           'text': 'green',
           'value': 2,
         },
         {
           'text': 'yellow',
           'value': 3,
         },
         {
           'text': 'black',
           'value': 4,
         },
       ],
   };

  final List<SingleQuestion> questions = [SingleQuestion.fromJson(data)];

  print(questions[0].question);
  print(questions[0].answers[1].value);
  print(questions[0].answers[1].text);
}
  • Related