无法通过容器中的API显示数组列表 [英] Unable to display the list of array from an API in a container

查看:86
本文介绍了无法通过容器中的API显示数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在容器中显示从API接收到的数据,但最终出现一些错误,因此我使用静态方法来显示在那里成功获得的API数据。
但是我无法弄清楚我的过程出了什么问题。

I was trying to display the received data from API in the container but ended up with some errors, so I used the static method to display the API data received well-got success there. But I cannot figure out what is going wrong with my process.

    import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Ticket extends StatefulWidget {
  @override
  _TicketState createState() => _TicketState();
}

class _TicketState extends State<Ticket> {

  var nos;

  @override
  void initState(){
    super.initState();
    _getNumbers();
  }
  _getNumbers() async{
    var result = await http.post('https://tickets-qzd55332wa-de.a.run.app/generateTickets?ticketsRequired=1');
    print(result.body);

  }
    //API RESPONSE(This is what I have made it locally but I want to fetch the same from the API itself)
  List tick = [
 // This is the exact output of the data fetched from the API
    {
      'tickets': [
        [
          [11, 5, 7, 10, 28, 9, 7, 74, 59],
          [1, 15, 7, 10, 8, 79, 27, 74, 9],
          [71, 5, 7, 20, 18, 9, 77, 74, 79],
        ],
        [
          [21, 5, 7, 80, 8, 9, 7, 74, 49],
          [31, 15, 7, 10, 18, 79, 7, 74, 19],
          [71, 5, 7, 20, 18, 79, 77, 74, 29],
        ],
      ]
    },
  ];

  @override
  Widget build(BuildContext context) {
    var h = MediaQuery.of(context).size.height;
    var w = MediaQuery.of(context).size.width;
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Container(
              decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.black,
                  )),
              child: ListView.builder(
                itemCount: tick.length,
                itemBuilder: (BuildContext context, index) {
                  List tripleNumbersList = [];
                  List<Widget> cells = [];
                  List<Widget> rows = [];
                  //Get the lenght of the list inside the 'tickets' map
                  int ticketsCount = tick[index]['tickets'].length;

                  //Iterates over the lists inside the 'tickets' map
                  for (int i = 0; i < ticketsCount; i++) {
                    //Get the lists of lists inside the 'tickets' map
                    tripleNumbersList = tick[index]['tickets'][i];
                    //Iterates over each list with other 3 lists
                    for (int j = 0; j < tripleNumbersList.length; j++) {
                      //Get one of the 3 lists
                      List<int> list = tripleNumbersList[j];
                      //Iterates over the list of numbers
                      for (int k = 0; k < list.length; k++) {
                        //Adds a Widget to 'cells; list for each number
                        cells.add(Container(
                            height: 40,
                            width: 40,
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black,
                              ),
                              //color: Colors.pink
                            ),
                            child: GestureDetector(
                                onTap: () {
                                  print('Working');
                                },
                                child: Text(
                                  ' ${list[k]}  ',
                                  style: TextStyle(
                                      fontSize: 22.0,
                                      fontWeight: FontWeight.bold),
                                ))));
                      }
                      //Adds the list of 'cells' in the 'rows' list
                      rows.add(Row(children: cells));
                      cells = [];
                    }
                    //Adds a empty row to make space
                    rows.add(Row(children: [
                      Container(
                        height: 20,
                      )
                    ]));
                  }

                  return Center(
                    child: Container(
                      height: h,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.black,
                        ),
                        //color: Colors.pink
                      ),
                      child: Column(
                        //Adds the list of rows to the column
                        children: rows,
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        ),
      ),
    );
  }
}

这是我使用API​​响应创建的目标文件。

This is the object file that I made using the response of the API.

Tickets ticketsFromJson(String str) => Tickets.fromJson(json.decode(str));

String ticketsToJson(Tickets data) => json.encode(data.toJson());
class Tickets {
  Tickets({
    this.tickets,
  });

  List<List<List<int>>> tickets;

  factory Tickets.fromJson(Map<String, dynamic> json) =>
      Tickets(
        tickets: List<List<List<int>>>.from(
            json["tickets"].map((x) => List<List<int>>.from(
                x.map((x) => List<int>.from(x.map((x) => x)))))),
      );

  Map<String, dynamic> toJson() =>
      {
        "tickets": List<dynamic>.from(tickets.map((x) => List<dynamic>.from(
            x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
      };
}

请帮助我解决我的代码有什么问题以及如何将数字显示为在这张图片中

Please help me out with what is wrong with my code and how to display the number as in this picture

推荐答案

使用API​​请求,您需要等待结果,然后尝试解析结果。并且由于从json创建的模型返回的列表带有嵌套列表,因此迭代几乎与硬编码数据结构相同。我对代码进行了一些更改以使其正常运行,但有时您的API似乎无法用于请求。您需要检查。请参阅代码中的注释以了解所做的更改:

With an API request you need wait for the result and then try to parse the result. And since the model created from the json return a list with nested lists, the iteration is almost the same as the hardcoded data structure. I made some changes in the code to make it work, but sometimes your API doesn't seems not available to requests. You need check this. See the comments in the code to understand the changes made:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Ticket {
  Ticket({
    this.tickets,
  });

  List<List<List<int>>> tickets;

  factory Ticket.fromJson(Map<String, dynamic> json) => Ticket(
        tickets: List<List<List<int>>>.from(json["tickets"].map((x) =>
            List<List<int>>.from(
                x.map((x) => List<int>.from(x.map((x) => x)))))),
      );

  Map<String, dynamic> toJson() => {
        "tickets": List<dynamic>.from(tickets.map((x) => List<dynamic>.from(
            x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
      };
}

class TicketPage extends StatefulWidget {
  @override
  _TicketPageState createState() => _TicketPageState();
}

class _TicketPageState extends State<TicketPage> {
  var nos;
  Ticket ticketList;

  String apiResult;

  @override
  void initState() {
    super.initState();
    _getNumbers();
  }

  _getNumbers() async {
    var result = await http
        .post(
            'https://tickets-qzd55332wa-de.a.run.app/generateTickets?ticketsRequired=2')
        .then((result) {
      //Waits for the API response and assigns to apiResult variable
      setState(() {
        apiResult = result.body;
      });
    });
  }

  // List tick = [
  //   {
  //     'tickets': [
  //       [
  //         [11, 5, 7, 10, 28, 9, 7, 74, 59],
  //         [1, 15, 7, 10, 8, 79, 27, 74, 9],
  //         [71, 5, 7, 20, 18, 9, 77, 74, 79],
  //       ],
  //       [
  //         [21, 5, 7, 80, 8, 9, 7, 74, 49],
  //         [31, 15, 7, 10, 18, 79, 7, 74, 19],
  //         [71, 5, 7, 20, 18, 79, 77, 74, 29],
  //       ],
  //     ]
  //   },
  // ];

  @override
  Widget build(BuildContext context) {
    var h = MediaQuery.of(context).size.height;
    var w = MediaQuery.of(context).size.width;

    if (apiResult == null) {
      return Center(child: CircularProgressIndicator());
    } else {
      //Get an instance of Ticket from the API assigned to apiResponse variable
      ticketList = Ticket.fromJson(json.decode(apiResult));
      print('Tickets: ${ticketList.tickets}');

      return Scaffold(
        body: SafeArea(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Container(
                decoration: BoxDecoration(
                    border: Border.all(
                  color: Colors.black,
                )),
                child: ListView.builder(
                  itemCount: ticketList.tickets.length,
                  itemBuilder: (BuildContext context, index) {
                    List tripleNumbersList = [];
                    List<Widget> cells = [];
                    List<Widget> rows = [];

                    //Get the lists of lists inside the 'tickets' list
                    tripleNumbersList = ticketList.tickets[index];
                    //Iterates over each list with other 3 lists
                    for (int j = 0; j < tripleNumbersList.length; j++) {
                      //Get one of the 3 lists
                      List<int> list = tripleNumbersList[j];
                      //Iterates over the list of numbers
                      for (int k = 0; k < list.length; k++) {
                        //Adds a Widget to 'cells; list for each number
                        cells.add(Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black,
                              ),
                              //color: Colors.pink
                            ),
                            child: GestureDetector(
                              onTap: () {
                                print('Working');
                              },
                              child: list[k] != 0
                                  ? Text(
                                      ' ${list[k]}  ',
                                      style: TextStyle(
                                          fontSize: 18.0,
                                          fontWeight: FontWeight.bold),
                                    )
                                  : Text(''),
                            )));
                      }
                      //Adds the list of 'cells' in the 'rows' list
                      rows.add(Row(children: cells));
                      cells = [];
                    }
                    //Adds a empty row to make space
                    rows.add(Row(children: [
                      Container(
                        height: 10,
                      )
                    ]));

                    return Center(
                      child: Container(
                        height: h / 3,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.black,
                          ),
                          //color: Colors.pink
                        ),
                        child: Column(
                          //Adds the list of rows to the column
                          children: rows,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        ),
      );
    }
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TicketPage(),
    );
  }
}

这篇关于无法通过容器中的API显示数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆