提问者:小点点

参数类型“Function”不能分配给参数类型“void Function()?”空安全后


我想实现制作一个上面有不同项目的抽屉,所以我正在为DrawerItems创建一个单独的文件,并使用构造函数,将数据传递给主文件。但是我在onP的函数上得到以下错误:

"The argument type 'Function' can't be assigned to the parameter type 'void Function()'"
class DrawerItem extends StatelessWidget {
    
      final String text;
      final Function onPressed;
    
      const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FlatButton(
          child: Text(
            text,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
            ),
          ),
          onPressed: onPressed,
        );
      }
    }

有人知道为什么吗?


共3个答案

匿名用户

更改您的代码以接受VoidCallback而不是函数
顺便说一句,VoidCallback只是void Function()的简写,因此您也可以将其定义为最终的void Function()onP的;

更新代码:

class DrawerItem extends StatelessWidget {
    
      final String text;
      final VoidCallback onPressed;
    
      const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FlatButton(
          child: Text(
            text,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
            ),
          ),
          onPressed: onPressed,
        );
      }
    }

匿名用户

而不是

final Function? onPressed; // Bad

使用

final void Function()? onPressed; // Good
final VoidCallback? onPressed; // Good

匿名用户

好吧,那是因为FlatButton中的onP的不是它的VoidCallBack函数的普通函数。你可以尝试这样的东西:

final VoidCallBack onPressed;

同时,您将普通的函数传递给VoidCallBack

按照这里的官方文档

更新代码:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  _myFunction() => print("Being pressed!");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            DrawerItem(
              text: "Hello Jee",
              onPressed: _myFunction,
            ),
          ],
        ),
      ),
    );
  }
}

class DrawerItem extends StatelessWidget {
  final String text;
  final Function onPressed;

  const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w600,
          fontSize: 18.0,
        ),
      ),
      onPressed: onPressed,
    );
  }
}