在Dart中以泛型类作为参数的泛型回调



我在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'

我做错了什么?

如何修复?

你也应该在_CustomSwitchState中使用泛型,就像@jamesdlin说的。

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<T> createState() => _CustomSwitchState<T>();
}
class _CustomSwitchState<T> extends State<CustomSwitch<T>> {

相关内容

  • 没有找到相关文章

最新更新