Как json массива страниц ID Дарт - PullRequest
0 голосов
/ 02 апреля 2020

my json:

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

как я могу построить алгоритм в трепетании дротиков, чтобы я мог получить заголовок всех страниц по идентификаторам?

если (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 голосов
/ 02 апреля 2020

Вам понадобится что-то вроде этого:

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;    
}
...