【问题标题】:Future<dynamic>' is not a subtype of type 'Function?Future<dynamic>' 不是'Function?
【发布时间】:2021-08-22 19:37:31
【问题描述】:

我在我的 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 赋值。请详细回答以清除我的概念。

【问题讨论】:

    标签: function flutter dart flutter-provider


    【解决方案1】:

    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 而不是函数。

    【讨论】:

    • 错误消失了,但现在 onClick 不起作用...
    • 我也必须更改 onTap 并使其像 onTap: () { onClick!(); }, ...在你的答案中添加这个我会接受。谢谢,@YairChen
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2020-10-13
    • 2020-09-24
    • 2020-09-11
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多