flutter - 抛出了另一个异常 : FormatException: Invalid number (at character 1)

标签 flutter dart google-cloud-firestore formatexception

为什么会报错Another exception was thrown: FormatException: Invalid number (at character 1)在一切恢复正常之前,我的屏幕上会出现几微秒。有时它甚至不会发生。下面是我的 StreamBuilder 函数:

_delivered() {
    print('In the delivered function:${resId},${customerId}, ');
    return StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance
            .collection('restaurants')
            .document(resId)
            .collection('customers')
            .document(customer)
            .collection('orders')
            .where('deliveryTime', isGreaterThan: '')
            .snapshots(),
        builder: (context, snapshot) {
          print('Does snapshop have data? ${snapshot.hasData}');
          if (!snapshot.hasData) return Container();

          List deliveredListFromServer = snapshot.data.documents;
          return Expanded(
            child: ListView(
              shrinkWrap: true,
              children: deliveredListFromServer.map((item) {
                print('document id: ${item.documentID}');
                return InkWell(
                  child: SizedBox(
                    height: 50,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          width: 80,
                          child: Text(
                            item['orderBy']['username'],
                            textAlign: TextAlign.center,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                        SizedBox(
                          width: 5,
                        ),
                        Expanded(
                          child: ListView(
                            scrollDirection: Axis.horizontal,
                            children: item['order'].map<Widget>((item) {
                              return SizedBox(
                                width: 80,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '${item['qty']} ${item['drinkName']}',
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              );
                            }).toList(),
                          ), //
                        ),
                        SizedBox(
                          width: 5,
                        ),
                        SizedBox(
                          width: 60,
                          child: Text(DateFormat('h:mm a').format(
                              DateTime.fromMillisecondsSinceEpoch(
                                  int.parse(item['deliveryTime'])))),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                    _deliveredDetail(item);
                  },
                );
              }).toList(),
            ),
          );
        });
  }

这是我的控制台:
I/flutter (11506): In the delivered function:XufIsxA8a24lLhO6gTr1,zMrQmcoQwci9bVVRo6tx, 
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562
I/flutter (11506): document id: 1579595374166
I/flutter (11506): Another exception was thrown: FormatException: Invalid number (at character 1)
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562

从控制台,我什至不明白为什么它会带来 document id: 1579595374166从数据库。只有 document id: 1579534059562有一个 deliveryTime 设置。数据库有 6 条记录,只有一条记录设置了 deliveryTime。其他都是空的""字符串。

因此,几毫秒后,一切都按预期工作,即正确的 UI,屏幕上只显示一个数据库项目。第二次流只返回一个文档时,一切似乎都恢复了正常。事实上,它唯一不带红屏的时间是控制台看起来像这样:
I/flutter (11506): In the delivered function:XufIsxA8a24lLhO6gTr1,zMrQmcoQwci9bVVRo6tx, 
I/flutter (11506): Does snapshop have data? false
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562

这也意味着 streamBuilder正在向列表传递不正确的数据(以及可能的错误来源)。为什么查询有时会返回错误的结果?!

最佳答案

它再次发生,现在我知道为什么了。在代码中,它实际上是在这一行 int.parse(item['deliveryTime']) 中的问题因为在 parse()方法 如果输入字符串不是有效的整数形式,程序将抛出 FormatException:
所以为了处理这个案子,

int.tryParse(item['deliveryTime']) ?? defaultValue;
你也可以使用 Dart try-catch 块:
try {
  var n = int.parse(item['deliveryTime']);
  print(n);
} on FormatException {
  print('Format error!');
}
// Format error!
int类parse()方法也给了我们处理 FormatException 的方法带有 onError 参数的情况。
var num4 = int.parse(item['deliveryTime'], onError: (source) => -1);
// -1
抛出异常时,onError将使用 source 作为输入字符串调用。现在我们可以返回一个整数值或空值……在上面的例子中,函数返回 -1每当 source在错误的整数文字中。

关于flutter - 抛出了另一个异常 : FormatException: Invalid number (at character 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853750/

相关文章:

android - 通过后退按钮设备在 webview 中回退

flutter :参数格式不正确

dart - 如何在 Fedora 18 x86_64 的 eclipse 和 Dartium 中配置 Dart 插件

ios - 错误 : Index out of range in segment control

firebase - Firestore/Flutter - 如何获取文档 ID?

dart - Dart 中的"new"关键字

Flutter:移动到新屏幕而不提供返回上一屏幕的导航

flutter - 如何在 Flutter 中更改 Html 小部件中的字体样式?

firebase - 保存对其他集合的引用

sockets - Flutter/Dart套接字通信,字符编码问题