function - 未来' 不是类型 'Function?
问题描述
我在我的 ChangeNotifier 中定义函数如下:
pickDNIFrontPhoto (ImageSource source,{BuildContext? context}) async {
try {
final pickedFile = await _picker.getImage(
source: source,
);
dniPhotoFront = pickedFile;
notifyListeners();
} catch (e) {
_pickImageError = e;
print("Error picking image $_pickImageError");
}
}
并将此函数传递给另一个小部件,如下所示:
PicBox(
description:'Add DNI Front Photo',
path: signupViewModel.dniPhotoFront != null ? signupViewModel.dniPhotoFront!.path : '',
onClick: signupViewModel.pickDNIFrontPhoto(ImageSource.gallery,context: context),
),
在我的自定义小部件中,我声明并使用了如下函数:
final Function? onClick;
onTap: () async {
await onClick!();
},
但它给了我这个错误:
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building SignUp(dirty, dependencies: [MediaQuery, _InheritedProviderScope<SignupViewModel>], state: _SignUpState#a0d75):
type 'Future<dynamic>' is not a subtype of type 'Function?'
The relevant error-causing widget was:
SignUp file:///C:/goochil_driver_app/lib/views/login_signup.dart:80:94
When the exception was thrown, this was the stack:
#0 _SignUpState.build (package:goochil_driver_app/views/sign_up.dart:255:80)
#1 StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#3 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
...
我做错了什么?是函数声明还是 onTap 赋值。请详细回答以清除我的概念。
解决方案
当您调用 pickDNIFrontPhoto 时,它会返回一个 Future。相反,您想传递一个函数而不是未来。PicBox 小部件的使用应该如下:
PicBox(
description:'Add DNI Front Photo',
path: signupViewModel.dniPhotoFront != null ? signupViewModel.dniPhotoFront!.path : '',
onClick: () => signupViewModel.pickDNIFrontPhoto(ImageSource.gallery,context: context),
),
感谢@Ali Yar Khan 让我知道您还必须更改您的 onTap 功能,使其看起来像这样:
onTap: () { onClick!(); },
观察现在正在传递的函数。如果没有这个函数,它只会调用函数 pickDNIFrontPhoto 并传递它返回的 Future 而不是一个函数。
推荐阅读
- git - 带有奇怪分支的 SVN 到 Git 迁移
- java - Java 的未来
- normalization - “规范化”和“规范化”数据之间是否存在明确的区别?
- vue.js - 当值使用计算数据时,如何在 type=Number 上使用货币?
- html - 显示前 2 个 flex 项目彼此居中且顶部对齐
- javascript - 如何下载外部视频而不在浏览器中播放?
- c# - C# System.IO.File.Copy 问题
- xml - 在 XSL 中调整 targetNamespace
- ios - 属性列表是否在应用会话之间保存?
- codeigniter - 为什么 curl 到另一台服务器在 codeigniter 中不起作用?