Description
I'm currently developing a custom wrapper for widgets in Flutter that enables extensive customization, similar to how {...rest}
works in TypeScript with React components. However, Dart doesn't support the spread operator for widget properties, so I'm struggling to find an effective way to forward a wide range of properties to a base widget like IconButton
.
Here's an example of what I might do in TypeScript:
const CustomIconButton: React.FC = ({
accessibilityLabel,
...rest
}) => {
return (
<IconButton {...rest} aria-label={"go to next"} color={"red"}/>
);
};
In Flutter, I'm looking for a way to achieve something similar. How can I create a wrapper that allows users to customize any widget with multiple properties without manually specifying each one? Here's a basic approach in Dart, but it requires explicitly forwarding each property, which isn't scalable. For example, an IconButton
can have additional properties like color and border. Manually copying all of them can make the code redundant. Here's my current approach:
import 'package:flutter/material.dart';
class CustomIconButton extends StatelessWidget {
final VoidCallback onPressed;
final IconData icon;
final IconButtonConfig config;
const CustomIconButton({
Key? key,
required this.onPressed,
required this.icon,
this.config = const IconButtonConfig(),
}) : super(key: key);
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(icon),
onPressed: onPressed,
tooltip: config.tooltip,
color: config.color,
// add other IconButton properties here using the config object
);
}
}
class IconButtonConfig {
final String tooltip;
final Color color;
final double iconSize;
const IconButtonConfig({
this.tooltip = '',
this.color = Colors.black,
this.iconSize = 24.0,
});
}
How can I achieve similar behavior to React Native in Flutter? Any insights would be greatly appreciated!
I try to use extend and extension , but they all looks like required you copy all the properties.