无法将参数类型'Function'分配给参数类型'void Function()'Flutter

时间:2020-10-22 14:11:45

标签: flutter

我想实现制作带有不同项目的抽屉,因此我要为DrawerItems创建一个单独的文件,并使用构造函数将数据传递到主文件。但是我在“ onPressed”功能上收到以下错误:

“不能将参数类型'Function'分配给参数类型'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,
        );
      }
    }

有人知道为什么吗?

7 个答案:

答案 0 :(得分:18)

具有空值安全性:

代替

final Function? onPressed;

使用

final VoidCallback? onPressed;

final Function()? onPressed;

答案 1 :(得分:0)

那是因为onPressed内的FlatButton不是其VoidCallBack函数的正常函数。 您可以尝试这样的事情:

final VoidCallBack onPressed;

同时,您将普通的function传递到VoidCallBack

按照官方文档here

enter image description here

更新的代码:

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,
    );
  }
}

答案 2 :(得分:0)

更改代码,以接受VoidCallback代替onPressed的Function。 Btw VoidCallback只是void Function()的简写,因此您也可以将其定义为final void Function() onPressed;

更新的代码:

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,
        );
      }
    }

答案 3 :(得分:0)

如果您仍然收到此错误“参数 'onPressed' 由于其类型的原因,其值不能为 'null',但隐式默认值为 'null'。”修改onPressed函数后,直接应用null安全解决这个问题;

import matplotlib.pyplot as plt

x = data = [29, 45, 56]
y = range(len(data))

fig, ax = plt.subplots()

plot = ax.bar(y,x)

ax.yaxis.grid(True, color ="green", lw = 1)
ax.set_axisbelow(True)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Title', fontsize = 12, fontweight ='bold')
plt.show()

这适用于 Dart 2.x

答案 4 :(得分:0)

使用:

VoidCallback? _onPressed

代替:

VoidCallback _onPressed

这对我有用!

答案 5 :(得分:0)

如果您在调用 DrawerItem 时发送参数,您还应该像这样向 Function 添加一个参数 ? final void Function(new par) onPressed;

答案 6 :(得分:0)

2021:如果您有一个接受多个参数的构造函数,您可能需要使用命名参数以避免混淆:

示例:应答按钮小部件

class AnswerButton extends StatelessWidget {
    
      late final Function()? submitAnswer;
    
      Answer({injectMethod}) {
        this.selectHandler = submitAnswer;
      }
    }

主要

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text("App Title"),
      ),
      body: Column(
        children: [
          AnswerButton(injectMethod: _nextQuestion) /* <--- named argument */
        ],
      ),
    ));
  }