flutter - Dart-即使在使用后也会收到未使用的变量通知
问题描述
我在这里错过了什么?即使在使用变量之后,我也会收到这个未使用的变量消息。下面的 _userProfileImgae 变量在 GestureDetector 小部件内部使用,但是当我将鼠标悬停在声明上时,我会收到未使用的变量消息。另外,有人请解释我什么时候应该对变量使用this前缀。我看到有些地方不使用this前缀就可以工作,而有些地方则没有。
class _ProfilePictureState extends State<ProfilePicture> {
late File _userProfileImage;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Row(
children: [
GestureDetector(
onTap: () async {
final _picker = ImagePicker();
PickedFile image = await _picker.pickImage(
source: ImageSource.gallery) as PickedFile;
if (image != null) {
setState(() {
this._userProfileImage = File(image.path);
});
}
},
child: Image(
image: AssetImage('assets/icons/plus_icon.png'),
width: 300,
height: 300,
fit: BoxFit.fill,
),
),
],
),
],
),
);
}
}
解决方案
即使在使用变量之后,我也会收到这个未使用的变量消息。
尽管您正在写信给_userProfileImage
,但您不会在任何地方阅读它。这是一个正在写入和读取变量的示例:
class _MyWidgetState extends State<MyWidget> {
File? _userProfileImage;
@override
Widget build(BuildContext context) {
final File? userProfileImage = _userProfileImage;
return Column(
children: [
Image(
// =====> READING <=====
image: userProfileImage == null
? AssetImage('assets/icons/plus_icon.png')
: FileImage(userProfileImage),
width: 300,
height: 300,
fit: BoxFit.fill,
),
TextButton(
child: Text("Click me"),
onPressed: () async {
final XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
// =====> WRITING <=====
setState(() => this._userProfileImage = File(image.path));
},
)
]
);
}
}
另外,有人请解释我什么时候应该对变量使用 this 前缀。我看到有些地方不使用 this 前缀就可以工作,而有些地方则没有。
这是另一个使用this
而不重要的示例:
class Foo {
final int bar = 5;
void f() {
print(bar); // Outputs 5
print(this.bar); // Outputs 5
}
void g() {
final int bar = 10;
print(bar); // Outputs 10
print(this.bar); // Outputs 5
}
void h(int bar) {
print(bar); // Outputs the parameter `bar`
print(this.bar); // Outputs 5
}
}
推荐阅读
- postgresql - postgres sql 的新手——取出 fkey 约束后,删除速度很慢,没有触发器和新的重新索引
- django - python *args 作为一个元组?目录?
- multithreading - 如何打印cython的prange进度?
- swiftui - SwiftUI 保存收藏
- c++ - 逐行读取 gzip 文件
- mysql - 查询不显示表 1 行,其中 id 不在表 2 中使用内连接
- arrays - 过滤多个数组时更新文档中的数组
- amazon-web-services - 如何将 S3 + Cloudfront 登台服务器限制为特定 IP?
- angular - 如果用户已经使用电子邮件和密码注册,则阻止使用 google 登录
- javascript - 在 Electron 中禁用全屏模式