Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(docs): Add documentation for using records and typedef #6382

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/content/language/records.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,56 @@ parallelization of futures of different types, which you can read about in the
[`dart:async` documentation][].
:::

## Records as simple data structures

The provided example illustrates how developers can leverage this pattern to
define dynamic UI widgets in a type-safe manner, similar to interfaces in
TypeScript but without the overhead of classes. This approach is particularly
useful for scenarios where simplicity and reusability are prioritized.

```dart
typedef ButtonItem = ({
String label,
Widget? icon,
void Function()? onPressed,
});
```

Here is an example about using `record` and `typedef` as structure of dynamic UI
widgets render:

```dart
// Define list from `buttonItem` interface.
List<ButtonItem> buttons = [
(
label: "Button I",
icon: const Icon(Icons.upload_file),
onPressed: () => print("Action -> Button I"),
),
(
label: "Button II",
icon: const Icon(Icons.info),
onPressed: () => print("Action -> Button II"),
)
];

List<Container> widget = buttons.map(
(ButtonItem button) => Container(
margin: const EdgeInsets.all(4.0),
child: OutlinedButton.icon(
onPressed: button.onPressed,
icon: button.icon!,
label: Text(button.label),
),
)
)
.toList();
```

The example demonstrates how to define a `ButtonItem` structure using records
and `typedef`, which promotes cleaner and more maintainable code by adhering to
the DRY (Don't Repeat Yourself) principle.

[language version]: /resources/language/evolution#language-versioning
[collection types]: /language/collections
[pattern]: /language/patterns#destructuring-multiple-returns
Expand Down