汎用パラメーターを実装するために Flutter でカスタム スイッチ クラスを作成し、flutter_switchパッケージを使用しました。スイッチを切り替えると、次のエラーに直面しました。
type '(String) => void' is not a subtype of type '(dynamic) => void'
また
type '(int) => void' is not a subtype of type '(dynamic) => void'
このエラーは、onChangeコールバックの処理に起因します。
Dart は、パラメーターのジェネリック関数を として定義しているようdynamicです。
これは私のコードです...
import 'package:flutter/material.dart';
import 'package:flutter_switch/flutter_switch.dart';
class CustomSwitch<T> extends StatefulWidget {
final T choice1;
final T choice2;
final T? value;
final Function(T)? onChange;
const CustomSwitch({
required this.choice1,
required this.choice2,
this.value,
this.onChange,
});
@override
_CustomSwitchState createState() => _CustomSwitchState();
}
class _CustomSwitchState extends State<CustomSwitch> {
bool value = true;
@override
void initState() {
super.initState();
value = widget.value == widget.choice1 || widget.value == null;
}
@override
Widget build(BuildContext context) {
return FlutterSwitch(
value: value,
activeText: widget.choice1.toString(),
inactiveText: widget.choice2.toString(),
onToggle: (bool value) {
setState(() {
this.value = value;
// here the error happened
// type '(String) => void' is not a subtype of type '(dynamic) => void'
if (widget.onChange != null) { // <--
widget.onChange!.call(value ? widget.choice1 : widget.choice2);
}
});
},
);
}
}
そして、私はCustomSwitchこのように使用します...
CustomSwitch<String>(
choise1: 'Active',
choise1: 'Inactive',
value: 'Active',
onChange: (value) {
print('value: $value');
}
);
このコードは、次のエラーをスローします。
type '(String) => void' is not a subtype of type '(dynamic) => void'
どうしたの?
修正方法は?