在运行时快速创建小部件

时间:2018-10-20 08:37:13

标签: flutter

我想创建表单。但是,用于表单的小部件不是预定义的。使用哪个小部件将由json响应确定。有什么办法在运行时创建小部件并管理其状态。

json如下所示

{  
  id:1,
  Answer: "Click on Register button so that we can get you started",
  Widget:[  
      "google OAuth"
  ],
  ReplyUrl:"www.example.com/api"
}
{
  id:2,
  Widget: [  
     {  
       "Question":"What is your name ?",
       "Type":"text",
       "VariableName":"Onboarding_Name"
     },
     {  
         "Question":"What is your birth date ?",
         "Type":"date",
         "VariableName":"Onboarding_BirthDate"
     }
   ],
   ReplyUrl:"www.example.com/api"
}

1 个答案:

答案 0 :(得分:0)

假设您的模型类为Question,并且您想为列表中的每个Question制作一个小部件:

List<Question> Questions;

您只需将它们映射:

 Questions.map((question) {
      if question.type == date {
        return DateQuestionWidget(question.title);
      } else if question.type == text {
        return TextQuestionWidget(question.title);
      }
     }
   );