首页 > 解决方案 > 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,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

标签: flutterdart

解决方案


即使在使用变量之后,我也会收到这个未使用的变量消息。

尽管您正在写信给_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
  }
}

推荐阅读