断言失败:布尔表达式不能为null(甚至布尔变量赋值为true/false)



我已经在Dart Flutter中制作了这个应用程序WorldTime,并且我得到了一个重复的未经解释的错误Failed assertion: boolean expression must not be null,我试图搜索这个错误,但我得到的只是布尔变量必须分配给truefalse。这里有一段代码,我有一个bool变量,我试图让它等于false/true,但它仍然给了我错误。具有布尔变量的代码:

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获取详细信息,仍然会得到相同的错误

任何帮助都将不胜感激:(

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

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

  • 尝试将true或false设置为捕获块中的isMorning标志

  • 或者尝试检查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];
    

最新更新