Skip to content

Improve typedef Usability for Named Tuple-like Structures in Dart #59607

@stephane-archer

Description

@stephane-archer

When using typedef for defining tuple-like structures, the behavior feels unintuitive and error-prone. For example, in the code below:

import 'package:flutter/material.dart';

typedef FeedbackData = (String message, Color color);

void Function(FeedbackData) getDisplayFeedbackForTheUser(
    BuildContext context) {
  return (feedbackData) {
    final snackBar = SnackBar(
      backgroundColor: feedbackData.$2,
      content: Text(feedbackData.$1),
      duration: feedbackData.$2 != Colors.green ? Duration(seconds: 6) : Duration(seconds: 4),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  };
}

The FeedbackData fields (message and color) must be accessed using . $1 and . $2. This feels strange, non-descriptive, and introduces potential errors due to lack of clarity.

Current Workaround:

I can rewrite the typedef like this:

typedef FeedbackData = ({String message, Color color});
This makes field access more intuitive:

final snackBar = SnackBar(
  backgroundColor: feedbackData.color,
  content: Text(feedbackData.message),
  duration: feedbackData.color != Colors.green ? Duration(seconds: 6) : Duration(seconds: 4),
);

However, this approach makes creation tedious because I need to explicitly name every parameter when creating a FeedbackData object.

Suggestion:

Can the following behavior be supported for typedef?

typedef FeedbackData = (String message, Color color);

void Function(FeedbackData) getDisplayFeedbackForTheUser(
    BuildContext context) {
  return (feedbackData) {
    final snackBar = SnackBar(
      backgroundColor: feedbackData.color,
      content: Text(feedbackData.message),
      duration: feedbackData.color != Colors.green ? Duration(seconds: 6) : Duration(seconds: 4),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  };
}

Here, FeedbackData would behave like a named tuple, allowing both intuitive field access (feedbackData.message and feedbackData.color) and concise creation syntax.

Why This Matters:

The current behavior of typedef makes tuple-like constructs harder to use in a way that is both expressive and practical. Enhancing typedef usability for named field access would make writing cleaner, safer, and more readable code easier.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions