当前位置: 首页 > 知识库问答 >
问题:

在API中使用用户输入按用户加载数据时发现Expection

任繁
2023-03-14

我试图从列表视图生成器中的应用编程接口接收数据,使用用户输入来显示要显示多少票...这是我试图反映用户输入的地方。每次我在列表视图生成器之前使用文本字段时,我都会收到错误

    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> {
  String _nos = '0';
  Ticket ticketList;
  String apiResult;
  Map<String, bool> cellStatus = {};
  final numCon = TextEditingController();

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

  _updateUserInput() {
    _nos = numCon.text;
  }

  @override
  void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the listener.
    numCon.dispose();
    super.dispose();
  }

  _getNumbers() async {
    var result = await http
        .post(
            'https://tickets-qzd55332wa-de.a.run.app/generateTickets?ticketsRequired=$_nos')
        .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 Scaffold(body: 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: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(28.0),
                child: Container(
                  child: TextField(
                    controller: numCon,
                    decoration: InputDecoration(
                      hintText: 'nos',
                    ),
                  ),
                ),
              ),
              RaisedButton(onPressed: () {
                setState(() {
                  _getNumbers();
                });
              }),
              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: 40,
                                width: 40,
                                decoration: BoxDecoration(
                                  border: Border.all(
                                    color: Colors.black,
                                  ),
                                  //color: Colors.pink
                                ),
                                child: GestureDetector(
                                  onTap: () {
                                    print('Working');
                                    if (cellStatus['$j$k'] ?? true) {
                                      print('Working');
                                      setState(() {
                                        cellStatus.addAll({'$j$k': false});
                                      });
                                    }
                                  },
                                  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 / 5,
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black,
                              ),
                              //color: Colors.pink
                            ),
                            child: Column(
                              //Adds the list of rows to the column
                              children: rows,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
  }
}

这是抛出例外

RenderBox was not laid out: RenderCustomPaint#aecb2 relayoutBoundary=up8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'
The relevant error-causing widget was
    ListView 
RenderBox was not laid out: RenderPadding#d9b88 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'
The relevant error-causing widget was
    Scaffold 

我希望我能解释这个问题,并希望看到帮助我解决这个问题。我被这个问题困扰了很多次。

共有1个答案

黄景胜
2023-03-14

该错误是由于列表视图中嵌套而发生的。

上面的代码可以修改为在Expanded中包装ListView。参考这个答案

例:

  @override
  Widget build(BuildContext context) {
    return _buildList(context);
  }

  Widget _buildList(BuildContext context) {
    var h = MediaQuery.of(context).size.height;

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

      return SafeArea(
        child: Scaffold(
          appBar: AppBar(
            title: Text('SO 62967820'),
          ),
          body: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(28.0),
                child: Container(
                  child: TextField(
                    controller: numCon,
                    decoration: InputDecoration(
                      hintText: 'nos',
                    ),
                  ),
                ),
              ),
              RaisedButton(
                  child: Text('Generate'),
                  onPressed: () {
                    setState(() {
                      _getNumbers();
                    });
                  }),
              Expanded(
                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: 40,
                            width: 40,
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black,
                              ),
                              //color: Colors.pink
                            ),
                            child: GestureDetector(
                              onTap: () {
                                print('Working');
                                if (cellStatus['$j$k'] ?? true) {
                                  print('Working');
                                  setState(() {
                                    cellStatus.addAll({'$j$k': false});
                                  });
                                }
                              },
                              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 / 5,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.black,
                          ),
                          //color: Colors.pink
                        ),
                        child: Column(
                          //Adds the list of rows to the column
                          children: rows,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      );
    }
  }
 类似资料:
  • 我想在用户使用Scanner输入时验证数据类型(在我的情况下是“int”)。 我在下面写了代码。 问题是,在第一个块中,若我给字符,程序终止。“如何在验证失败时保持循环运行??” 在第二个块中,如果我给出非整数,它将无限运行,并显示消息“仅输入整数值”。 从调试中,我得出结论,在不等待输入的情况下,它采用之前提供的最后一个非int值。 为什么编译器取最后一个值?? 有什么建议吗?

  • 我的代码不会跳出while循环,而是仍然要求用户输入。当我按enter时,它不会再次打印“::”,但从不执行que.view()

  • 问题内容: 我有一个JComboBox的子类。我尝试使用以下代码添加一个键侦听器。 但是,这不能正确检测用户何时按下一个键。实际上根本没有调用它。我添加的这个监听器是否错误?还有其他添加方式吗? 问题答案: 关键事件不是在框本身上触发的,而是在其编辑器上触发的。您需要将keyListener添加到JComboBox的编辑器中,而不是直接添加到框中: 编辑:固定方法调用。

  • 我试图在Python中做基本的加密,在下面的程序中,我加密任何用户类型,然后在解密后显示给用户。我使用的pyCrypto库,我从这里下载:http://www.voidspace.org.uk/python/modules.shtml#pycrypto 以下是我迄今为止编写的代码: 问题是当我从用户那里获取输入时,我的代码不起作用,但是当我给静态输入时,我评论过的代码工作正常。 有人能帮忙吗?我应

  • 我正在开发一个待办事项列表程序。 我想让用户可以输入日期、时间和关于。我已经知道日期了。我错过的是时间。 但我有很多例外。我错过了什么吗?

  • 我做了一个程序,要求我输入一个名字,这个名字应该在一个名为的数组中。看起来是这样的: 我在这里做错了什么?