'flutter- I don't know the difference between these two case
Case 1 :
children: DUMMY_CATEGORIES.map((catData) {
CategoryItem(
catData.title,
catData.color,
);
}).toList(),
Case 2 :
children: DUMMY_CATEGORIES
.map(
(catData) => CategoryItem(
catData.title,
catData.color,
),
)
.toList(),
Case 1 causes an error. Isn't the two cases the same syntax? Why is this error occurring?
════════ Exception caught by rendering library ═════════════════════════════ Null check operator used on a null value The relevant error-causing widget was GridView lib\categories_screen.dart:12 ═════════════════════════════════════════════════════════════
Solution 1:[1]
Case 2 uses the Fat Arrow Expression or Lambda Function Expression, a syntax to write a function on a single line using => syntax AKA fat arrow. more info
DUMMY_CATEGORIES.map(
(catData) => CategoryItem(
catData.title,
catData.color,
),
).toList(),
Fat Arrow Syntax:
(args) => expression
If expression
has a return type (in your case, a CategoryItem), it directly returns.
It is the same as your Case 1 with a return statement:
DUMMY_CATEGORIES.map(
(catData) {
return CategoryItem(
catData.title,
catData.color,
),
}
).toList(),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thierry |