所以我正在将一个项目切换到颤振空安全,但我在空值错误上使用了空检查运算符我尝试查看其他类似的 issue 尝试但它对我不起作用完整的错误如下
export const getMessageTemplates = (): Promise<
ReadonlyArray<MessageTemplate>
> =>
fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
method: "get",
credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
headers: {
Accept: "application/json",
},
})
.then(res => res.json())
.then(data => [{ templateId: " ", category: "", title: "blank message", defaultTemplate: false }, ...data])
.then((data) => /* your logic here */);
等等,这会出现在多个地方,我不知道如何解决这个问题。
The following _CastError was thrown building HomeBanner(dirty, dependencies: [MediaQuery, _InheritedProviderScope<HomeViewModel>], state: _HomeBannerState#2de56):
Null check operator used on a null value
The relevant error-causing widget was:
HomeBanner file:///D:/fabricoMAt/lib/ui/views/home_screen.dart:26:17
When the exception was thrown, this was the stack:
#0 HomeViewModel.initData (package:knoty/business_logic/view_models/home_viewmodel.dart:25:33)
#1 _HomeBannerState._getImageSliders (package:knoty/ui/widgets/home_banner.dart:30:18)
#2 _HomeBannerState.build (package:knoty/ui/widgets/home_banner.dart:20:23)
#3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
Null check operator used on a null value
The relevant error-causing widget was:
WhomeServices file:///D:/fabricoMAt/lib/ui/views/home_screen.dart:43:17
提到的另一行
HomeViewModel model = Provider.of<HomeViewModel>(context);
Size screenSize = MediaQuery.of(context).size;
return model.initData == null //home_banner line 30
? [1, 2, 3, 4]
.map(
(item) => Shimmer.fromColors(
child: Container(
margin: EdgeInsets.only(right: 8),
width: screenSize.width * .7,
height: screenSize.width * .35,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
color: Colors.black,
),
),
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
),
)
.toList()
答案 0 :(得分:1)
在第 30 行的 home_banner
中,您使用的是 initData
方法,该方法返回一个不可为空的值。
因此创建一个可为空的 initData
返回类型并从 !
中删除 _initData
。
Init? get initData => _initData;// home_viewmodel.dart 25
如果您在代码中使用 get selectedCity
而不检查 _initData
的空值,这可能会导致您的代码出错,
所以也要在这个方法中添加一个空检查。
City get selectedCity {
City? city = _initData?.cities
.firstWhere((element) => element.id == _initData?.selectedCityId);
if(city==null){
return City();// return default city
}else{
return city;
}
}