更新履歴
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');
);
},
),
),
);
}
}