dart-lang / dart-lang/language

How to Create a Flexible Custom Wrapper for Widgets to overriding some default properties?

Open
#3,777 5 comments 4 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

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:

```typescript

const CustomIconButton: React.FC = ({
accessibilityLabel,
...rest
}) => {
return (

);
};
```

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:

```dart
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.

Contributor guide

Open the contributing guide

Research direction

Start with the issue body's TypeScript spread example and the Dart CustomIconButton/IconButtonConfig example. Determine whether the requested behavior requires a Dart language change or can be addressed with existing widget APIs; no source files or tests are named, so completion would require a documented design and agreed scope.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.