【发布时间】: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。