首页 > 解决方案 > 颤振在运行时创建小部件

问题描述

我想在颤振中创建表单。但是将在表单中使用的小部件不是预定义的。使用哪些小部件将由 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"
}

标签: flutter

解决方案


假设您的模型类是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);
      }
     }
   );

推荐阅读