JSON数组页面ID如何飞镖

时间:2020-04-02 07:43:09

标签: flutter dart flutter-web

我的json:

{
  "result": {
    "name": "json1",
      "pages": [{
          "zones": [{
              "title": "title1"
           },
           {
              "title": "title2"
           }],
           "id": 4
       },
       {
          "zones": [{
            "title": "title3"
          },
          {
            "title": "title4"
          }],
          "id": 12
       }],
       "creatorUserName": "admin",
       "id": 2
    }
}

如何在飞镖颤动中构建算法,以便获得针对Ids的所有页面标题?

如果(id = 12)区域打印->文本(title3),文本(title4),


否则打印空白区域->文本(title1),文本(title2),区域->文本(title3),文本(title4),

我的示例代码:

List post = snapshot.data["result"]["pages"];
List post = pagesArray; 
children: post.map((post) => Container(
                      child: Center(child: Text(post.title]),) 
                  )).toList(),   

1 个答案:

答案 0 :(得分:0)

您将需要以下内容:

void initState() {
  result = getResponse();
}

Widget getTextWidgets(var array)
{
  List<Widget> list = new List<Widget>();
  for(var i = 0; i < array.length; i++){
      list.add(new Text(array[i]["title"], style: TextStyle(color: Colors.black)));
  }
  return new Row(children: list);
}

@override
Widget build(BuildContext context) {

  return MaterialApp(
    home:  Scaffold(
      appBar: AppBar(
        title: Text(
          'Sample',
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
        ),
        backgroundColor: Colors.black,
      ),
      body: Container(
        padding: EdgeInsets.all(5),
        child: ListView.builder(
          shrinkWrap: true,
          itemCount: result.length,
          itemBuilder: (BuildContext context, int index) {
            if(result[index]["id"] == 4){
              getTextWidgets(result[index]["zones"]);
            }
            else if(result[index]["id"] == 12){
              getTextWidgets(result[index]["zones"]);
            }
          },
        ),
      ))
  );
}

getResponse() {

  var response = '{ "result": { "name": "json1", "pages": [{ "zones": [{ "title": "title1" }, { "title": "title2" }], "id": 4 }, { "zones": [{"title": "title3"}, {"title": "title4"}], "id": 12 }], "creatorUserName": "admin", "id": 2 }}';

  print('Respone ${response}');
  var value = json.decode(response);
  var pages = value["result"]["pages"];
  return pages;    
}