目次
コンポーネントの準備
以下のような、サンプルのコンポーネントを用意してください。
import 'package:flutter/material.dart';
class Component extends StatelessWidget {
const Component();
@override
Widget build(BuildContext context) {
return Scaffold(
body: InkWell(
onTap: () {},
child: Container(
color: Colors.grey[300],
width: 80,
height: 50,
child: Center(
child: Text("ボタン"),
),
),
)
);
}
}
関数を引数に渡す方法
「Function」のデータ型を引数の受け口として用意することで、引数に関数を設定する事ができます。
具体的には以下のようなパラメータを用意します。
final Function() onPressedCallback;
コンストラクタを、引数を受け取るように修正します。
const Component({
required this.onPressedCallback,
});
使用する箇所では、以下のように使用する事ができます。
onPressedCallback();
サンプルソースコード
import 'package:flutter/material.dart';
class Component extends StatelessWidget {
const Component({
required this.onPressedCallback,
});
final Function() onPressedCallback;
@override
Widget build(BuildContext context) {
return Scaffold(
body: InkWell(
onTap: () {
onPressedCallback();
},
child: Container(
color: Colors.grey[300],
width: 80,
height: 50,
child: Center(
child: Text("ボタン"),
),
),
)
);
}
}