【问题标题】:Another exception was thrown: FormatException: Invalid number (at character 1)引发了另一个异常:FormatException: Invalid number (at character 1)
【发布时间】:2020-05-08 06:15:33
【问题描述】:

为什么在我的屏幕上出现错误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 条记录,只有一条设置了交货时间。其他是空的"" 字符串。

因此,几毫秒后,一切都按预期运行,即正确的 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 正在向列表传递不正确的数据(以及可能的错误来源)。为什么查询有时会返回错误的结果?!

【问题讨论】:

    标签: flutter dart google-cloud-firestore formatexception


    【解决方案1】:

    它再次发生,现在我知道为什么了。在代码中,实际上在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 class parse() 方法还为我们提供了一种处理带有 onError 参数的 FormatException 情况的方法。

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

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

    【讨论】:

    • 非常感谢。我已经坚持了好几个星期了。 tryParse 很有魅力!
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我的回答可能不适用于这个实例,但我也遇到了同样的错误“无效数字(在字符 1)”,我得到错误的地方指向我使用我的变量名的地方文本编辑控制器

      我的案例的问题是我已经在我的应用程序的另一个点使用了同名的 TextEditingController(也不是私有变量),并且在使用后没有处理它。

      在我处理完所有的 TextEditingControllers 后,我的问题就解决了!

      【讨论】:

        【解决方案4】:

        如果参数发生错误,您可以为您的参数值添加一个 isEmpty 条件。

        前:

        // 定义货币

         final _controller = TextEditingController();   static const _locale = 'id';   static const _symbol = 'Rp. ';    String _formatNumber(String s) =>
        
           NumberFormat.decimalPattern(
                _locale,
              ).format(s.isEmpty ? 0 : int.parse(s));   String get _currency =>
              NumberFormat.compactSimpleCurrency( locale: _locale, name: _symbol).currencySymbol;
        
        
        //textfield 
        
          TextfieldWidget(        prefixText: Text(_currency,   style: Theme.of(context).textTheme.subtitle1),
            controller: _controller,
        
            onChanged: (string) {
             string =
             '${_formatNumber(string.replaceAll(',', ''))}';
              _controller.value = TextEditingValue(
             text: string,
        
             selection: TextSelection.collapsed(
             offset: string.length ?? null),
             );
            },   ),
        
                     
        

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        • 2020-08-26
        • 2019-10-08
        相关资源
        最近更新 更多