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

Pau*_*tta 4 formatexception dart flutter google-cloud-firestore

为什么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(),
            ),
          );
        });
  }
Run Code Online (Sandbox Code Playgroud)

这是我的控制台:

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
Run Code Online (Sandbox Code Playgroud)

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

所以几毫秒后,一切都按预期工作,即正确的用户界面,屏幕上只显示一个数据库项目。第二次流只返回一个文档时,一切似乎都恢复了正常。事实上,它唯一不带红屏的时候是控制台看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

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

Par*_*iya 11

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

所以为了处理这个案子,

int.tryParse(item['deliveryTime']) ?? defaultValue;
Run Code Online (Sandbox Code Playgroud)

你也可以使用 Dart try-catch 块:

try {
  var n = int.parse(item['deliveryTime']);
  print(n);
} on FormatException {
  print('Format error!');
}
// Format error!
Run Code Online (Sandbox Code Playgroud)

int 类parse()方法还为我们提供了一种处理FormatException带有 onError 参数的情况的方法。

var num4 = int.parse(item['deliveryTime'], onError: (source) => -1);
// -1
Run Code Online (Sandbox Code Playgroud)

抛出异常时,onError将使用 source 作为输入字符串调用。现在我们可以返回一个整数值或空值……在上面的例子中,-1只要source是错误的整数文字,函数就会返回。


小智 5

当您获取空数据时会发生此错误我遇到了同样的问题,并且能够通过从我的 firestore 数据库中删除该空数据来解决它。

我建议您从获取列表的位置检查集合中的数据,其中一个字段必须为 null