【问题标题】:Failed assertion: boolean expression must not be null (even bool variable assigned to true/false)断言失败:布尔表达式不能为空(即使布尔变量分配给真/假)
【发布时间】:2021-07-09 15:34:08
【问题描述】:

我已经在Dart Flutter 中创建了这个应用程序WorldTime 应用程序,并且我得到一个重复的无法解释的错误Failed assertion: boolean expression must not be null,我试图搜索这个错误,我得到的只是bool 变量必须分配给true 或@ 987654326@。所以这是一段代码,其中我有一个 bool 变量,我试图使其等于 false/true,但它仍然给了我错误。 有 bool 变量的代码:

import 'dart:convert';
import 'package:http/http.dart';
import 'package:intl/intl.dart';

class WorldTime {
  String location;
  String time;
  String flag;
  String url;
  bool isMorning ;

  WorldTime({this.location, this.flag, this.url});

  Future<void> getTime() async {
    try {
      Response response =
          await get(Uri.https('worldtimeapi.org', 'api/timezone/$url'));
      Map data = jsonDecode(response.body);

      String datetime = data['datetime'];
      String offset = data['utc_offset'].substring(0, 3);
      String offset_mnt = data['utc_offset'].substring(4, 6);

      DateTime now = DateTime.parse(datetime);
      now = now.add(
          Duration(hours: int.parse(offset), minutes: int.parse(offset_mnt)));

      isMorning = now.hour > 6 && now.hour < 20 ? true : false;

      time = DateFormat.jm().format(now);
    } catch (e) {
      print("Error occured: $e");
      time = "Cannot Display Time Due to Error Occured";
    }
  }
}

完整的代码链接和文件在我的 GitHub 存储库中 Link:WorldTimeApp

我的应用还需要active internet connection,所以我保证我有活跃的互联网来从 API 获取详细信息仍然得到同样的错误

任何帮助将不胜感激:)

【问题讨论】:

  • 不确定是否是问题所在,但您从未使用任何值初始化 isMorning。由于您使用bool 作为类型,这是一个问题,因为它最终会得到不允许的值null
  • @julemand101 我试图分配isMorning = true/false,但发生了同样的错误:(
  • 在 home.dart 中你有 String bgImg = data['isMorning'] ? 'Day.jpeg' : 'Night.jpeg'; 但我没有看到 "isMorning" 在启动应用程序时被添加到 data 中。这首先在 Scaffold 的创建中的 home.dart 中完成。所以data['isMorning'] 正确返回null

标签: android json flutter dart


【解决方案1】:

我猜,您的 api 调用可能失败,因此您的布尔标志 (isMorning) 从未初始化。可能的修复

  • 在调用 api 之前尝试初始化变量

  • 尝试在 catch 块中将 isMorning 标志设置为 true 或 false

  • 或尝试检查 null,然后进行布尔检查。例如,

     bool _isMorning = data['isMorning'] != null && data['isMorning'] != false;
     String bgImg = _isMorning ? 'Day.jpeg' : 'Night.jpeg';
     Color colors = _isMorning ? Colors.blue[50] : Colors.blueGrey[800];
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2020-07-05
    • 2021-05-29
    相关资源
    最近更新 更多