-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
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.