首页 > 解决方案 > 未来' 不是类型 '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 赋值。请详细回答以清除我的概念。

标签: functionflutterdartflutter-provider

解决方案


当您调用 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 而不是一个函数。


推荐阅读