【发布时间】:2021-11-03 05:02:01
【问题描述】:
我正在学习 Flutter / Dart,在此 video 中进行练习时遇到了一个错误,据我所知,这是由于 null-safety 功能,并且因为示例来自以前的版本,所以出现了问题.
import 'package:flutter/material.dart';
class OurImage extends StatelessWidget {
final String pathImage;
final double widthImage;
final double heightImage;
OurImage({this.pathImage, this.heightImage, this.widthImage});
@override
Widget build(BuildContext context) {
final photo = Container(
width: this.widthImage,
height: this.heightImage,
margin: EdgeInsets.only(right: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(this.pathImage), fit: BoxFit.cover)),
);
return photo;
}
}
参数“pathImage”的值不能为“null”,因为它 类型,但隐含的默认值为“null”。尝试添加一个 显式非“null”默认值或“必需”修饰符。
在阅读1、2、3 关于空安全性的这些错误时,我想通过添加“?”来纠正出现在我身上的错误。和 ”!”到我的代码,我用它来验证错误不再出现。
import 'package:flutter/material.dart';
class OurImage extends StatelessWidget {
final String? pathImage; //change here
final double? widthImage; //change here
final double? heightImage; //change here
OurImage({this.pathImage, this.heightImage, this.widthImage});
@override
Widget build(BuildContext context) {
final photo = Container(
width: this.widthImage,
height: this.heightImage,
margin: EdgeInsets.only(right: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(this.pathImage!), fit: BoxFit.cover)), //change here
);
return photo;
}
}
我获得的修复方法是否正确?我应该如何创建 OurImage 类的变量,使其不会产生此错误?
【问题讨论】:
-
是的,按照屏幕上的建议修复错误是绝对正确的。查看 null 安全指南以更好地理解和使用它。
-
使
widthImage和heightImage可以为空看起来没问题。将pathImage设为可空看起来是错误的,因为您稍后无条件地 使用pathImage!,它断言pathImage是不是null。如果未设置pathImage,这将导致运行时崩溃。更合适的解决方法是: A. 使pathImage不可为空,并将其作为构造函数的required参数; B. 检查pathImage是否为null并且有条件地 使用AssetImage; C. 使pathImage不可为空并将其初始化为某个默认的非null值(如果未作为构造函数参数提供)。
标签: flutter class dart widget dart-null-safety