Невозможно отобразить список массивов из API в контейнере - PullRequest
0 голосов
/ 11 июля 2020

Я пытался отобразить полученные данные из API в контейнере, но в результате возникли некоторые ошибки, поэтому я использовал метод stati c, чтобы отобразить данные API, полученные там успешно. Но я не могу понять, что не так с моим процессом.

    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.

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)))))),
      };
}

Пожалуйста, помогите мне Что не так с моим кодом и как отобразить число как на этом рисунке

1 Ответ

0 голосов
/ 11 июля 2020

При запросе API нужно дождаться результата, а затем попытаться разобрать результат. А поскольку модель, созданная из json, возвращает список с вложенными списками, итерация почти такая же, как и жестко закодированная структура данных. Я внес некоторые изменения в код, чтобы он заработал, но иногда кажется, что ваш API недоступен для запросов. Вам нужно это проверить. См. Комментарии в коде, чтобы понять сделанные изменения:

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(),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...