5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】クラスでvoid関数を引数にすると「The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.」とエラーが出る

Last updated at Posted at 2021-05-16

更新履歴

2021.5.17 初回投稿

環境

  • macOS Big Sur(11.2.3)
  • Flutter (Channel stable, 2.0.6, on macOS 11.2.3 20D91 darwin-x64, locale ja-JP)
  • Android toolchain - develop for Android devices (Android SDK version 30.0.3)
  • Xcode - develop for iOS and macOS
  • Chrome - develop for the web
  • Android Studio (version 4.1)
  • VS Code (version 1.56.0)

今までのコードだとエラーが出て動かない

よく使うWidgetで引数にvoid関数を入れて処理したいのですが、今までは引数の必須は@requiredで引数が関数の場合の型はFunctionでOKでしたが、引数を指定するところで、「The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.」とエラーが出て動かせなくなりました。

今までのコード

import 'package:flutter/material.dart';

class TestButton extends StatelessWidget {
  TestButton({
    @required this.buttonTitle, 
    @required this.buttonTap
  });

  final String buttonTitle;
  final Function buttonTap;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: buttonTap,//ここでエラーが出る。
      child: Text(buttonTitle),
    );
  }
}


動いたコード

以下のように変えたら動きました!!

@required の@を削除
・final Function buttonTap;をfinal void Function() buttonTap;に変更

import 'package:flutter/material.dart';

class TestButton extends StatelessWidget {
  TestButton({
    required this.buttonTitle, //@requiredの@を削除
    required this.buttonTap
  });

  final String buttonTitle;
  final VoidCallback? buttonTap;
  //final void Function() buttonTap;
//Functionではなく、VoidCallback? または void Function()

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: buttonTap,
      child: Text(buttonTitle),
    );
  }
}

呼び出し側


class StartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Start'),
        actions: [
          IconButton(
            icon: Icon(Icons.menu),
            onPressed: () {
              debugPrint('test');
            },
          ),
        ],
      ),
      body: Center(
        child: TestButton(
          buttonTitle: 'testButton',
          buttonTap: () {
            debugPrint('test');
            );
          },
        ),
      ),
    );
  }
}

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?