FlutterFlutter · Chapterبەش 5 · Lectureوانە 5.3
Dart Functions and Collectionsکردارەکان و کۆکراوەکانی Dart
Functions with return types, arrow syntax, positional, optional and named parameters (required and default values), functions as values, callbacks and closures; then List, Set and Map, spread and collection if/for, and the iterable methods map, where, fold and toList — with a look at how Flutter widgets use all of them.
بە جۆری ، تیر، شوێنی، ئارەزوومەندانە و ناودار (required و )، وەک ، و ؛ پاشان List، Set و Map، و collection if/for و وەک map، where، fold و toList — لەگەڵ سەیرێک کە چۆن هەموویان بەکار دەهێنن.
What you will learnچی فێر دەبیت
- Write functions with return types, block bodies and arrow bodies.
- Use positional, optional and named parameters, with
requiredand default values. - Pass functions as values and write callbacks, avoiding the
save()vssavemistake. - Choose and use List, Set and Map, including nullable map reads.
- Build and transform collections with spread, collection if/for, map, where, fold and toList.
- بە جۆری ، ناوەڕۆکی بلۆک و ناوەڕۆکی تیر بنووسیت.
- شوێنی، ئارەزوومەندانە و ناودار بە
requiredو بەکاربهێنیت. - وەک بنێریت و بنووسیت، بەبێ هەڵەی
save()بەرامبەرsave. - List، Set و Map هەڵبژێریت و بەکاریان بهێنیت، لەوانە خوێندنەوەی Map کە دەشێت null بێت.
- کۆکراوەکان بە ، collection if/for، map، where، fold و toList دروست بکەیت و بیانگۆڕیت.
Functionsکردارەکان
A is a named block of code that you can run again and again by calling it. In Dart you write the return type first, then the name, the in parentheses and the body in braces. return sends a value back to the caller; a function that returns nothing has the type void. The general idea of functions, parameters and return values is taught in Defining and Calling Functions and Return Values; here is the Dart syntax.
ناونراوە کە دەتوانیت بە بانگکردنی چەند جار بتەوێت کاری پێبکەیت. لە سەرەتا جۆری دەنووسیت، پاشان ناوەکە، لە ناو کەوانەدا و ناوەڕۆکەکە لە ناو کەوانەی لوولیدا. return دەنێرێتەوە بۆ ؛ کە هیچ ناگەڕێنێتەوە جۆرەکەی voidـە (). بیرۆکە گشتییەکانی ، و لە پێناسەکردن و بانگکردنی کردارەکان و نرخە گەڕاوەکان فێر دەکرێن؛ ئەمە .
int add(int a, int b) {
return a + b;
}
void greet(String name) {
print('Hello, $name!');
}
void main() {
var total = add(2, 3);
print(total);
greet('Aram');
greet('Shilan');
}5 Hello, Aram! Hello, Shilan!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
intis the return type;aandbareintparameters.intجۆری ؛aوbintـن.- Lineدێڕی 2
returngives the result back to the caller.returnئەنجامەکە دەداتەوە بە .- Lineدێڕی 5
void: this function only does something (prints); it returns nothing.void: ئەم تەنها کارێک دەکات (چاپ دەکات)؛ هیچ ناگەڕێنێتەوە.- Lineدێڕی 10
Calling
add(2, 3): the result 5 goes intototal.بانگکردنی
add(2, 3): ئەنجامی 5 دەچێتە ناوtotalـەوە.
Functionsکردارەکان
Arrow functionsکردارەکانی تیر
When a function only returns one , you can write it on one line with an arrow: => expression; means { return expression; }. Flutter code is full of arrows. Only an expression may follow => — not a statement such as if (a conditional expression a ? b : c is fine).
کاتێک تەنها یەک دەگەڕێنێتەوە، دەتوانیت بە تیرێک لە یەک دێڕدا بینووسیت: => expression; واتە { return expression; }. کۆدی پڕە لە تیر. تەنها دەتوانێت دوای => بێت — نەک وەک if ( مەرجی a ? b : c دروستە).
int square(int x) => x * x;
bool isEven(int n) => n % 2 == 0;
String label(int mark) => mark >= 50 ? 'pass' : 'fail';
void main() {
print(square(4));
print(isEven(7));
print(label(64));
}16 false pass
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Same as
int square(int x) { return x * x; }.هەمان
int square(int x) { return x * x; }ـە.- Lineدێڕی 5
A conditional expression is allowed after
=>.مەرجی دوای
=>ڕێگەپێدراوە.
Positional, optional and named parametersپارامیتەرەکانی شوێنی، ئارەزوومەندانە و ناودار
Dart has three kinds of parameters. Required positional parameters come first, and the caller gives the in the same order. Optional positional parameters go in square brackets [ ] and may have a . go in braces { }; the caller writes their names (drink: 'tea'), so the order does not matter. A named parameter is optional unless you mark it required; an optional one must have a default value or a nullable type. Python calls the same idea keyword arguments — see Positional, Keyword and Default Arguments.
سێ جۆر هەیە. شوێنیی پێویست سەرەتا دێن و بە هەمان ڕیزبەندی دەدات. شوێنیی ئارەزوومەندانە لە ناو کەوانەی چوارگۆشە [ ]ـدا دەنووسرێن و دەتوانن هەبێت. لە ناو کەوانەی لوولی { }ـدان؛ ناوەکانیان دەنووسێت (drink: 'tea')، بۆیە ڕیزبەندی گرنگ نییە. ئارەزوومەندانەیە مەگەر نیشانەی requiredـی لێ بدەیت؛ دەبێت ئارەزوومەندانە هەبێت یان جۆرەکەی دەشێت null بێت. بە هەمان بیرۆکە دەڵێت — سەیری ئارگیومێنتەکان شوێنی، ناودار و بنەڕەتی بکە.
// 1. Required positional parameters: order matters.
double price(double unitPrice, int count) => unitPrice * count;
// 2. Optional positional parameter in [ ] with a default value.
String welcome(String name, [String place = 'CêIT']) => 'Welcome to $place, $name!';
// 3. Named parameters in { }: callers write the names.
void order({required String drink, int sugar = 1, String? note}) {
print('$drink, sugar: $sugar, ${note ?? 'no note'}');
}
void main() {
print(price(1.5, 4));
print(welcome('Karwan'));
print(welcome('Karwan', 'the bazaar'));
order(drink: 'tea');
order(sugar: 0, drink: 'coffee', note: 'no milk');
}6.0 Welcome to CêIT, Karwan! Welcome to the bazaar, Karwan! tea, sugar: 1, no note coffee, sugar: 0, no milk
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Two required positional parameters.
دوو شوێنیی پێویست.
- Lineدێڕی 5
[String place = 'CêIT']: optional, with a default value.[String place = 'CêIT']: ئارەزوومەندانە، لەگەڵ .- Lineدێڕی 8
drinkis required;sugarhas a default;notemay be null.drinkپێویستە؛sugarهەیە؛noteدەشێت null بێت.- Lineدێڕی 16-17
Named arguments can be in any order.
دەتوانن بە هەر ڕیزبەندییەک بن.
| Kindجۆر | Declared asڕاگەیاندن | Called asبانگکردن | If left outئەگەر نەدرێت |
|---|---|---|---|
| Required positionalشوێنیی پێویست | f(int a) | f(5) | compile-time error |
| Optional positionalشوێنیی ئارەزوومەندانە | f([int a = 1]) | f() or f(5) | default value (or null) (یان null) |
| Namedناودار | f({int a = 1}) | f(a: 5) | default value (or null) (یان null) |
| Required namedناوداری پێویست | f({required int a}) | f(a: 5) | compile-time error |
void order({required String drink, int sugar = 1}) {
print('$drink with $sugar sugar');
}
void main() {
order(sugar: 2);
}required_error.dart:6:8: Error: Required named parameter 'drink' must be provided.
order(sugar: 2);
^
required_error.dart:1:6: Context: Found this candidate, but the arguments don't match.
void order({required String drink, int sugar = 1}) {
^^^^^void order({String drink, int sugar = 1}) {
print('$drink with $sugar sugar');
}
void main() {
order(drink: 'tea');
}named_error.dart:1:20: Error: The parameter 'drink' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
void order({String drink, int sugar = 1}) {
^^^^^Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
String drinkwith no default and norequired: if the caller leaves it out it would benull, which aStringcannot hold. Fix:required String drinkorString drink = 'tea'orString? drink.String drinkبەبێ و بەبێrequired: ئەگەر نەیدات دەبێتnullبێت، کەStringناتوانێت هەڵیبگرێت. چاککردنەوە:required String drinkیانString drink = 'tea'یانString? drink.
Functions as values and callbacksکردارەکان وەک نرخ و کردارەکانی بانگکردنەوە
In Dart a function is a value, like a number or a string. You can store it in a variable and pass it to another function. A function without a name — () { … } or (x) => … — is an . A function you hand to someone else so that they call it later is a . This is how every Flutter button works: you give it a function in onPressed, and Flutter calls it when the user taps.
لە ، وەک ژمارە یان . دەتوانیت لە هەڵیبگریت و بیدەیت بە تر. بەبێ ناو — () { … } یان (x) => … — . ئەو دەیدەیت بە کەسێکی تر بۆ ئەوەی ئەو دواتر بانگی بکات . هەموو بەم شێوەیە کار دەکات: لە onPressedـدا پێدەدەیت و کاتێک دەستی لێدەدات بانگی دەکات.
// A pretend button: it receives a function and calls it when "pressed".
void pressButton(String label, void Function() onPressed) {
print('[$label] was pressed');
onPressed();
}
void sayHello() {
print('Hello!');
}
void main() {
var count = 0;
pressButton('Greet', sayHello); // pass the function itself, no ()
pressButton('Add', () {
// an anonymous function
count++;
print('count is $count');
});
pressButton('Add again', () => count++); // arrow form
print('count is $count');
var shout = (String word) => word.toUpperCase(); // a function in a variable
print(shout('dart'));
}[Greet] was pressed Hello! [Add] was pressed count is 1 [Add again] was pressed count is 2 DART
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
void Function() onPressed: this parameter takes a function with no parameters that returns nothing.void Function() onPressed: ئەم وەردەگرێت کە نییە و هیچ ناگەڕێنێتەوە.- Lineدێڕی 4
The button calls the function it was given.
ئەو پێی دراوە بانگ دەکات.
- Lineدێڕی 14
Pass the function itself:
sayHello, without().خودی بنێرە:
sayHello، بەبێ().- Lineدێڕی 16-20
An anonymous function with a body. It can change
count, a variable from outside.بە ناوەڕۆکەوە. دەتوانێت
countبگۆڕێت، کە دەرەوەیە.- Lineدێڕی 22
The arrow form of an anonymous function.
شێوەی تیری .
- Lineدێڕی 25
A function stored in a variable.
کە لە هەڵگیراوە.
You order a suit at the tailor's in the bazaar and leave your phone number: “call me when it is ready”. You do not stand and wait; the tailor decides when to call. A callback is that phone number: you give Flutter a function, and Flutter calls it when the moment comes — when the button is tapped.
لە بازاڕ لای بەرگدروو بەدلەیەک داوا دەکەیت و ژمارەی مۆبایلەکەت جێدەهێڵیت: «کاتێک ئامادە بوو پەیوەندیم پێوە بکە». ڕاناوەستیت و چاوەڕێ ناکەیت؛ بەرگدرووەکە بڕیار دەدات کەی پەیوەندی بکات. ئەو ژمارە مۆبایلەیە: دەدەیت بە و کاتێک ساتەکە دێت بانگی دەکات — کاتێک دەست لە دەدرێت.
Where the analogy stops workingسنووری ئەم نموونەیە
A phone number is only data; a callback is code that runs. And the tailor calls once, but a button can call your function every time it is tapped.
ژمارەی مۆبایل تەنها ؛ کۆدە و کار دەکات. هەروەها بەرگدرووەکە یەک جار پەیوەندی دەکات، بەڵام دەتوانێت هەر جارێک دەستی لێ بدرێت بانگ بکات.
Functions as values and callbacksکردارەکان وەک نرخ و کردارەکانی بانگکردنەوە
Pass it, do not call itبینێرە، بانگی مەکە
The most common callback mistake: writing save() instead of save. With parentheses you call the function at once and pass its result; without them you pass the function itself. Here save() returns nothing (void), so Dart refuses:
باوترین هەڵەی : نووسینی save() لە جیاتی save. بە کەوانەوە دەستبەجێ بانگ دەکەیت و ئەنجامەکەی دەنێریت؛ بەبێ کەوانە خودی دەنێریت. لێرەدا save() هیچ ناگەڕێنێتەوە (void)، بۆیە ڕەتی دەکاتەوە:
save() instead of savesave() لە جیاتی savecall_mistake.dartDARTType in a terminalلە تێرمیناڵدا بینووسەvoid pressButton(String label, void Function() onPressed) {
print('[$label] was pressed');
onPressed();
}
void save() {
print('Saved!');
}
void main() {
pressButton('Save', save());
}call_mistake.dart:11:23: Error: This expression has type 'void' and can't be used.
pressButton('Save', save());
^Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 11
Fix:
pressButton('Save', save);— or() => save().چاککردنەوە:
pressButton('Save', save);— یان() => save().
Functions as values and callbacksکردارەکان وەک نرخ و کردارەکانی بانگکردنەوە
Closures and tear-offsclosure و tear-off
An anonymous function remembers the variables around it, even after the outer function has finished. Such a function is called a . In the example, each counter made by makeCounter() keeps its own count. Also useful: writing a function's name without () (a tear-off), as in forEach(print).
دەوروبەری لە بیر دەمێنێت، تەنانەت دوای ئەوەی دەرەوە تەواو بوو. وا پێی دەوترێت . لە نموونەکەدا، هەر کە makeCounter() دروستی دەکات countـی خۆی دەپارێزێت. هەروەها بەسوودە: نووسینی ناوی بەبێ () (tear-off)، وەک forEach(print).
// makeCounter returns a function that remembers its own count.
int Function() makeCounter() {
var count = 0;
return () {
count++;
return count;
};
}
void main() {
var nextTicket = makeCounter();
print(nextTicket());
print(nextTicket());
print(nextTicket());
var other = makeCounter(); // a new, separate count
print(other());
['Aram', 'Hana'].forEach(print); // a tear-off: print is passed as a value
}1 2 3 1 Aram Hana
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The return type
int Function()means: it returns a function that returns an int.جۆری
int Function()واتە: دەگەڕێنێتەوە کەintدەگەڕێنێتەوە.- Lineدێڕی 4-7
The returned function keeps using
count.بەردەوام
countبەکار دەهێنێت.- Lineدێڕی 16
A second counter has its own
count, so it starts at 1.دووەم
countـی خۆی هەیە، بۆیە لە 1ـەوە دەست پێدەکات.- Lineدێڕی 19
printis passed as a value (a tear-off).printوەک دەنێردرێت (tear-off).
Listsلیستەکان
A List keeps values in order. Each item has an starting at 0, so the first item is cities[0] and the last is cities[cities.length - 1]. A list is written in square brackets, and Dart infers its — ['Erbil', 'Duhok'] is a List<String> and can hold only strings. Lists can grow and shrink with add, insert, remove and removeAt. (Python lists work the same way; see Lists in Python.)
List بە ڕیزبەندی هەڵدەگرێت. هەر هەیە کە لە 0ـەوە دەست پێدەکات، بۆیە یەکەم cities[0]ـە و دوایینیان cities[cities.length - 1]. لە ناو کەوانەی چوارگۆشەدا دەنووسرێت و دەدۆزێتەوە — ['Erbil', 'Duhok'] List<String>ـە و تەنها هەڵدەگرێت. بە add، insert، remove و removeAt گەورە و بچووک دەبنەوە. ( بە هەمان شێوە کار دەکەن؛ سەیری لیستەکان لە Pythonـدا بکە.)
void main() {
var cities = ['Erbil', 'Duhok', 'Zakho']; // List<String>
print(cities[0]); // the first item has index 0
print(cities.length);
cities.add('Halabja'); // add at the end
cities.insert(1, 'Koya'); // add at index 1
print(cities);
cities.remove('Duhok'); // remove by value
cities.removeAt(0); // remove by index
print(cities);
print(cities.contains('Zakho'));
print(cities.indexOf('Halabja'));
print('${cities.first} ... ${cities.last}');
print(cities.isEmpty);
cities[0] = 'Ranya'; // change an item
print(cities);
List<int> marks = []; // an empty list of int
marks.addAll([70, 85, 92]);
print(marks);
}Erbil 3 [Erbil, Koya, Duhok, Zakho, Halabja] [Koya, Zakho, Halabja] true 2 Koya ... Halabja false [Ranya, Zakho, Halabja] [70, 85, 92]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Index 0 is the first item.
0 یەکەم .
- Lineدێڕی 6-7
addputs an item at the end;insert(1, …)puts it at index 1 and moves the rest along.addلە کۆتایی دادەنێت؛insert(1, …)لە 1 دایدەنێت و ئەوانی تر دەجوڵێنێت.- Lineدێڕی 10-11
removedeletes by value;removeAtby index.removeبەپێی دەسڕێتەوە؛removeAtبەپێی .- Lineدێڕی 19
cities[0] = …replaces an item.cities[0] = …دەگۆڕێت.- Lineدێڕی 22
An empty list needs its type:
List<int> marks = [];.بەتاڵ پێویستی بە جۆرەکەیەتی:
List<int> marks = [];.
void main() {
var cities = ['Erbil', 'Duhok', 'Zakho'];
print(cities[3]); // there is no index 3
}Unhandled exception: RangeError (length): Invalid value: Not in inclusive range 0..2: 3 #0 List.[] (dart:core-patch/growable_array.dart) #1 main (list_error.dart:3:15)
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Valid indexes are 0, 1 and 2. This is a runtime error: the compiler cannot know the list's length.
0، 1 و 2ـن. ئەمە : ناتوانێت درێژیی بزانێت.
Clear Dart examples: list methods (add, insert, remove), maps of key-value pairs, and turning text into numbers with int.parse and double.parse.
نموونەی ڕوونی : (add، insert، remove)، Map بۆ و گۆڕینی بۆ ژمارە بە int.parse و double.parse.
Plays 19:12-26:21: making a list, indexes, changing, adding, inserting and removing items.
لە 19:12 تا 26:21 پەخش دەبێت: دروستکردنی ، ، گۆڕین، زیادکردن، تێخستن و سڕینەوەی .
Listsلیستەکان
Lists that cannot changeئەو لیستانەی ناگۆڕێن
A const list is fixed: you cannot add, remove or replace items. A final list is different — the variable cannot point to another list, but the list itself can still change. Flutter often uses const lists of widgets, because constant things are built only once.
const جێگیرە: ناتوانیت زیاد بکەیت، بسڕیتەوە یان بیگۆڕیت. final جیاوازە — ناتوانێت ئاماژە بۆ تر بکات، بەڵام خودی هێشتا دەگۆڕێت. زۆرجار constـی بەکار دەهێنێت، چونکە شتە نەگۆڕەکان تەنها یەک جار دروست دەکرێن.
void main() {
const weekend = ['Friday', 'Saturday'];
weekend.add('Sunday');
print(weekend);
}Unhandled exception: Unsupported operation: Cannot add to an unmodifiable list #0 UnmodifiableListMixin.add (dart:_internal/list.dart:112:5) #1 main (const_list_error.dart:3:11)
Setsکۆمەڵەکان
A Set holds different values: adding a value that is already there does nothing (and add returns false). Use a set when you care only whether something is in the collection — such as which cities a student has visited. Sets can be combined with union (in either), intersection (in both) and difference (in the first only). Careful: {} on its own makes an empty Map; an empty set must be written <String>{}. Python's sets are in Tuples, Sets and Dictionaries.
Set جیاواز هەڵدەگرێت: زیادکردنی کە پێشتر تێیدایە هیچ ناکات (و add false دەگەڕێنێتەوە). کاتێک بەکاربهێنە کە تەنها گرنگە بزانیت ئایا شتێک لە کۆکراوەکەدایە یان نا — وەک ئەوەی خوێندکارێک سەردانی کام شارانی کردووە. بە union (لە هەریەکیان)، intersection (لە هەردووکیان) و difference (تەنها لە یەکەمیان) پێکەوە دەبەسترێن. ئاگادار بە: {} بە تەنها Mapـێکی بەتاڵ دروست دەکات؛ بەتاڵ دەبێت بە <String>{} بنووسرێت. لە Tuple، کۆمەڵە و فەرهەنگدان.
void main() {
var visited = {'Erbil', 'Duhok'}; // Set<String>
print(visited.add('Zakho')); // true: it was new
print(visited.add('Erbil')); // false: already there
print(visited);
print(visited.length);
print(visited.contains('Duhok'));
var friends = {'Erbil', 'Halabja'};
print(visited.union(friends)); // in either set
print(visited.intersection(friends)); // in both sets
print(visited.difference(friends)); // only in visited
var names = ['Aram', 'Hana', 'Aram', 'Lana', 'Hana'];
print(names.toSet()); // duplicates are removed
var emptySet = <String>{}; // an empty Set needs the type
var emptyMap = {}; // this is a Map, not a Set!
print(emptySet.runtimeType);
print(emptyMap.runtimeType);
}true
false
{Erbil, Duhok, Zakho}
3
true
{Erbil, Duhok, Zakho, Halabja}
{Erbil}
{Duhok, Zakho}
{Aram, Hana, Lana}
_Set<String>
_Map<dynamic, dynamic>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-4
addreturnstruefor a new value andfalsefor a duplicate.addبۆ نوێtrueو بۆ دووبارەfalseدەگەڕێنێتەوە.- Lineدێڕی 10-12
Union, intersection and difference.
، و .
- Lineدێڕی 15
toSet()is the quickest way to remove duplicates from a list.toSet()خێراترین ڕێگەیە بۆ لابردنی دووبارەکان لە .- Lineدێڕی 17-18
<String>{}is a Set; plain{}is a Map.<String>{}Setـە؛{}ـی سادە Mapـە.
MapsMapـەکان
A Map stores : you look a value up by its key, not by a position — like finding a price by the name of the item. Each key appears only once. prices['tea'] reads a value; prices['juice'] = 1000 adds or changes one. Because a key might be missing, reading gives a nullable value (int?), so you handle null with ?? or a check. Python calls this a dictionary (see it here); PHP calls it an .
Map هەڵدەگرێت: بە دەدۆزیتەوە، نەک بە شوێنەکەی — وەک دۆزینەوەی نرخی کاڵایەک بە ناوەکەی. هەر تەنها یەک جار دەردەکەوێت. prices['tea'] دەخوێنێتەوە؛ prices['juice'] = 1000 یەکێک زیاد دەکات یان دەیگۆڕێت. چونکە لەوانەیە نەبێت، خوێندنەوە دەشێت null دەدات (int?)، بۆیە بە ?? یان پشکنین null چارەسەر دەکەیت. پێی دەڵێت (لێرە ببینە)؛ PHP پێی دەڵێت .
void main() {
var prices = {'tea': 500, 'coffee': 1500, 'bread': 250}; // Map<String, int>
print(prices['tea']); // read a value by its key
print(prices['juice']); // a missing key gives null
prices['juice'] = 1000; // add a new pair
prices['tea'] = 750; // change a value
prices.remove('bread');
print(prices);
print(prices.length);
print(prices.containsKey('coffee'));
print(prices.keys);
print(prices.values);
for (final entry in prices.entries) {
print('${entry.key} costs ${entry.value} dinars');
}
int teaPrice = prices['tea'] ?? 0; // the value may be null: give a default
print(teaPrice);
}500
null
{tea: 750, coffee: 1500, juice: 1000}
3
true
(tea, coffee, juice)
(750, 1500, 1000)
tea costs 750 dinars
coffee costs 1500 dinars
juice costs 1000 dinars
750Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Map<String, int>: keys are strings, values are ints.Map<String, int>: ،intـن.- Lineدێڕی 4
A missing key gives
null.نەبوو
nullدەدات.- Lineدێڕی 6-8
Add, change and remove pairs.
زیادکردن، گۆڕین و سڕینەوەی جووتەکان.
- Lineدێڕی 15-17
entriesgives each pair with.keyand.value.entriesهەر جووتێک بە.keyو.valueدەدات.- Lineدێڕی 19
?? 0turns the nullableint?into a safeint.?? 0int?ـی دەشێت null دەکات بەintـێکی سەلامەت.
void main() {
var prices = {'tea': 500, 'coffee': 1500};
int teaPrice = prices['tea'];
print(teaPrice);
}map_error.dart:3:24: Error: A value of type 'int?' can't be assigned to a variable of type 'int'.
int teaPrice = prices['tea'];
^Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
prices['tea']isint?. Writeprices['tea'] ?? 0(orprices['tea']!only if you are sure the key exists).prices['tea']int?ـە. بنووسەprices['tea'] ?? 0(یانprices['tea']!تەنها ئەگەر دڵنیایت هەیە).
Clear Dart examples: list methods (add, insert, remove), maps of key-value pairs, and turning text into numbers with int.parse and double.parse.
نموونەی ڕوونی : (add، insert، remove)، Map بۆ و گۆڕینی بۆ ژمارە بە int.parse و double.parse.
Plays 26:21-31:08: maps of key-value pairs, values, keys, length, adding and removing.
لە 26:21 تا 31:08 پەخش دەبێت: Map کە لە پێک دێت، ، ، درێژی، زیادکردن و سڕینەوە.
Spread, collection if and collection forکارپێکەری بڵاوکردنەوە، collection if و collection for
Dart lets you build a list (or set or map) with small pieces of logic inside the brackets. The ... pours all items of another collection in; ...? does nothing if that collection is null. Collection if adds an item only when a condition is true, and collection for adds one item per round of a loop. Flutter uses these all the time to build the children of a widget, as you will see on the next screen.
ڕێگەت پێدەدات (یان یان Map) بە پارچە بچووکەکانی لۆجیک لە ناو کەوانەکاندا دروست بکەیت. ... هەموو کۆکراوەیەکی تر دەڕێژێتە ناوەوە؛ ...? ئەگەر ئەو کۆکراوەیە null بێت هیچ ناکات. collection if تەنها کاتێک ڕاست بێت زیاد دەکات و collection for بۆ هەر یەک زیاد دەکات. هەمیشە ئەمانە بۆ دروستکردنی childrenـی بەکار دەهێنێت، وەک لە شاشەی داهاتوودا دەیبینیت.
void main() {
var hot = ['tea', 'coffee'];
var cold = ['juice', 'water'];
var menu = [...hot, ...cold]; // spread: put all items here
print(menu);
List<String>? specials; // may be null
var full = ['bread', ...?specials]; // ...? adds nothing if null
print(full);
var isRamadan = false;
var times = ['Morning', if (isRamadan) 'Suhoor', 'Evening']; // collection if
print(times);
var squares = [for (var i = 1; i <= 5; i++) i * i]; // collection for
print(squares);
var labels = [for (final drink in hot) 'Hot $drink'];
print(labels);
}[tea, coffee, juice, water] [bread] [Morning, Evening] [1, 4, 9, 16, 25] [Hot tea, Hot coffee]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
...hotand...coldinsert every item of both lists....hotو...coldهەموو هەردوو دادەنێن.- Lineدێڕی 8
...?specialsadds nothing, becausespecialsis null....?specialsهیچ زیاد ناکات، چونکەspecialsnullـە.- Lineدێڕی 12
'Suhoor'is added only ifisRamadanis true.'Suhoor'تەنها ئەگەرisRamadantrue بێت زیاد دەکرێت.- Lineدێڕی 15
One item per round: 1, 4, 9, 16, 25.
بۆ هەر یەک : 1، 4، 9، 16، 25.
map, where, toList and friendsmap، where، toList و هاوڕێکانیان
Lists and sets are : you can walk through them, and they share useful methods that replace many hand-written loops. map turns each item into something new; where keeps only the items that pass a test; any and every answer yes/no questions; firstWhere finds the first match; fold combines everything into one value, such as a total. map and where are lazy: they give an Iterable (printed in round brackets) and do the work only when needed — add .toList() when you need a real list, for example for a Flutter ListView (Lists and Grids).
و : دەتوانیت بەسەریاندا بڕۆیت و بەسوودی هاوبەشیان هەیە کە جێگەی زۆر دەستنووس دەگرنەوە. map هەر دەکات بە شتێکی نوێ؛ where لە نێو تەنها ئەوانە دەهێڵێتەوە کە لە تاقیکردنەوەیەک دەردەچن؛ any و every وەڵامی پرسیاری بەڵێ/نەخێر دەدەنەوە؛ firstWhere یەکەم گونجاو دەدۆزێتەوە؛ fold هەموو شتێک دەکات بە یەک ، وەک کۆی گشتی. map و where تەمبەڵن: Iterableـێک دەدەن (لە ناو کەوانەی ئاساییدا چاپ دەکرێت) و تەنها کاتێک پێویست بێت کارەکە دەکەن — کاتێک ڕاستەقینەت دەوێت .toList() زیاد بکە، بۆ نموونە بۆ ListViewـی (لیست و تۆڕ).
![Four frames. 1: four product cards: Tea glass 3.0, Honey 12.5, Bread 1.0, Olive oil 9.0. 2: map((p) => p['name']) turns each card into just its name. 3: where((p) => price < 5) keeps only Tea glass and Bread. 4: toList() puts the result into a real list in square brackets.](/_astro/flutter-dart-functions-and-collections-map-where.en.B5yEEWCL.gif)
![Four frames. 1: four product cards: Tea glass 3.0, Honey 12.5, Bread 1.0, Olive oil 9.0. 2: map((p) => p['name']) turns each card into just its name. 3: where((p) => price < 5) keeps only Tea glass and Bread. 4: toList() puts the result into a real list in square brackets.](/_astro/flutter-dart-functions-and-collections-map-where.ckb.DYK9HhNK.gif)
void main() {
var products = [
{'name': 'Tea glass', 'price': 3.0},
{'name': 'Honey', 'price': 12.5},
{'name': 'Bread', 'price': 1.0},
{'name': 'Olive oil', 'price': 9.0},
];
var names = products.map((p) => p['name']).toList();
print(names);
var cheap = products.where((p) => (p['price'] as double) < 5).toList();
print(cheap);
var prices = [3.0, 12.5, 1.0, 9.0];
print(prices.map((p) => p * 2)); // lazy: an Iterable, not a List
print(prices.where((p) => p > 5).toList());
print(prices.any((p) => p > 10));
print(prices.every((p) => p > 0));
print(prices.firstWhere((p) => p > 5));
print(prices.fold<double>(0, (sum, p) => sum + p)); // add them all up
}[Tea glass, Honey, Bread, Olive oil]
[{name: Tea glass, price: 3.0}, {name: Bread, price: 1.0}]
(6.0, 25.0, 2.0, 18.0)
[12.5, 9.0]
true
true
12.5
25.5Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-7
Product data as a list of maps, as in the course's product-catalogue project. (A class is cleaner; see the next lesson.)
کاڵاکان وەک لە Map، وەک لە پڕۆژەی کاتالۆگی کاڵای وانەکە. ( ڕێکترە؛ سەیری وانەی داهاتوو بکە.)
- Lineدێڕی 9
maptakes a function that receives one productpand returns its name.mapوەردەگرێت کە یەک کاڵاpوەردەگرێت و ناوەکەی دەگەڕێنێتەوە.- Lineدێڕی 12
wherekeeps the products whose price is below 5.as doubletells Dart the map value's type.whereئەو کاڵایانە دەهێڵێتەوە کە نرخیان لە 5 کەمترە.as doubleجۆری Mapـەکە بە دەڵێت.- Lineدێڕی 16
Without
toList()you see anIterablein round brackets.بەبێ
toList()Iterableـێک لە ناو کەوانەی ئاساییدا دەبینیت.- Lineدێڕی 21
foldstarts at 0 and adds each price: the total.foldلە 0ـەوە دەست پێدەکات و هەر نرخێک زیاد دەکات: کۆی گشتی.
Where you will meet this in Flutterلە Flutterـدا لە کوێ ئەمانە دەبینیت
Everything in this lesson appears in almost every Flutter screen. This small widget uses named parameters (one required, one with a default), a callback in onPressed, collection if and collection for. You do not need to understand the widget classes yet — just spot the Dart.
هەموو شتێکی ئەم وانەیە لە نزیکەی هەموو شاشەیەکی دەردەکەوێت. ئەم بچووکە (یەکێکیان required و یەکێکیان بە )، لە onPressed، collection if و collection for بەکار دەهێنێت. هێشتا پێویست ناکات تێبگەیت — تەنها بدۆزەرەوە.
import 'package:flutter/material.dart';
class MenuCard extends StatelessWidget {
const MenuCard({super.key, required this.drinks, this.showTitle = true});
final List<String> drinks;
final bool showTitle;
@override
Widget build(BuildContext context) {
return Column(
children: [
if (showTitle) const Text('Menu'),
for (final drink in drinks) Text(drink),
ElevatedButton(
onPressed: () => debugPrint('Order sent'),
child: const Text('Order'),
),
],
);
}
}
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(child: MenuCard(drinks: ['Tea', 'Coffee', 'Juice'])),
),
),
);
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
Named constructor parameters:
required this.drinksandthis.showTitle = true(a default).:
required this.drinksوthis.showTitle = true().- Lineدێڕی 13
Collection if: the title appears only when
showTitleis true.collection if: ناونیشانەکە تەنها کاتێک
showTitletrue بێت دەردەکەوێت.- Lineدێڕی 14
Collection for: one
Textwidget per drink.collection for: بۆ هەر خواردنەوەیەک یەک
Text.- Lineدێڕی 16
A callback: an anonymous arrow function that Flutter calls when the button is tapped.
: تیر کە کاتێک دەست لە دەدرێت بانگی دەکات.
- Lineدێڕی 28
Calling with a named argument and a list.
بانگکردن بە ناودار و .
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | Fixچاککردنەوە |
|---|---|
onPressed: save() | Pass the function: onPressed: save (or () => save()). بنێرە: onPressed: save (یان () => save()). |
var empty = {}; // meant a Set | {} is an empty Map. Write <String>{} for an empty Set.{} Mapـێکی بەتاڵە. بۆ Setـی بەتاڵ بنووسە <String>{}. |
cities[cities.length] | The last index is length - 1; or use cities.last.دوایین length - 1ـە؛ یان cities.last بەکاربهێنە. |
int price = prices['tea']; | A map read is nullable: prices['tea'] ?? 0.خوێندنەوەی Map دەشێت null بێت: prices['tea'] ?? 0. |
void f({String name}) | A named parameter needs required, a default value or a ? type. پێویستی بە required، یان جۆرێکی ? هەیە. |
names.map((n) => n.toUpperCase())[0] | map gives an Iterable without []. Add .toList() first.map Iterableـێک دەدات کە []ـی نییە. سەرەتا .toList() زیاد بکە. |
=> if (x > 0) print(x); | Only an expression may follow =>. Use a body { … } for statements.تەنها دەتوانێت دوای => بێت. بۆ ناوەڕۆکی { … } بەکاربهێنە. |
Adding to a const listزیادکردن بۆ const | Use a normal (or final) list if it must change.ئەگەر دەبێت بگۆڕێت، ئاسایی (یان final) بەکاربهێنە. |
Exercisesڕاهێنانەکان
Write an arrow function rectangleArea with two required named parameters width and height (both double). Call it twice, once with the arguments in the other order.
تیری rectangleArea بنووسە بە دوو پێویست width و height (هەردووکیان double). دوو جار بانگی بکە، جارێکیان بە ڕیزبەندییەکی تری .
Show answerوەڵامەکە پیشان بدە
double rectangleArea({required double width, required double height}) =>
width * height;
void main() {
print(rectangleArea(width: 4, height: 2.5));
print(rectangleArea(height: 3, width: 3)); // any order
}10.0 9.0
Write greet(String name, [String? title]) that returns Hello, Aram without a title and Hello, Dr. Hana with one.
greet(String name, [String? title]) بنووسە کە بەبێ نازناو Hello, Aram و لەگەڵ نازناو Hello, Dr. Hana بگەڕێنێتەوە.
Show answerوەڵامەکە پیشان بدە
String greet(String name, [String? title]) {
if (title == null) {
return 'Hello, $name';
}
return 'Hello, $title $name';
}
void main() {
print(greet('Aram'));
print(greet('Hana', 'Dr.'));
}Hello, Aram Hello, Dr. Hana
Start with ['bread', 'tea', 'sugar']. Add honey, remove sugar, print the list and its length, and say whether tea is on it (use the ternary operator).
بە ['bread', 'tea', 'sugar'] دەست پێبکە. honey زیاد بکە، sugar بسڕەوە، و درێژییەکەی چاپ بکە و بڵێ ئایا چا تێیدایە ( بەکاربهێنە).
Show answerوەڵامەکە پیشان بدە
void main() {
var shopping = ['bread', 'tea', 'sugar'];
shopping.add('honey');
shopping.remove('sugar');
print(shopping);
print('Items: ${shopping.length}');
print(shopping.contains('tea') ? 'Tea is on the list' : 'No tea');
}[bread, tea, honey] Items: 3 Tea is on the list
A library records each visit: ['Aram', 'Lana', 'Aram', 'Soran', 'Lana', 'Aram']. Print the number of visits and the number of different visitors.
کتێبخانەیەک هەموو سەردانێک تۆمار دەکات: ['Aram', 'Lana', 'Aram', 'Soran', 'Lana', 'Aram']. ژمارەی سەردانەکان و ژمارەی سەردانکەرە جیاوازەکان چاپ بکە.
Hintئاماژە
A Set keeps each name once.
Set هەر ناوێک یەک جار دەهێڵێتەوە.
Show answerوەڵامەکە پیشان بدە
void main() {
var visits = ['Aram', 'Lana', 'Aram', 'Soran', 'Lana', 'Aram'];
var visitors = visits.toSet();
print('Visits: ${visits.length}, different visitors: ${visitors.length}');
print(visitors);
}Visits: 6, different visitors: 3
{Aram, Lana, Soran}Count how often each word appears in 'tea and bread and tea' and store the counts in a Map<String, int>.
بژمێرە هەر وشەیەک چەند جار لە 'tea and bread and tea'ـدا دەردەکەوێت و ژمارەکان لە Map<String, int>ـێکدا هەڵبگرە.
Hintئاماژە
sentence.split(' ') gives a list of words.
sentence.split(' ') لە وشەکان دەدات.
Show answerوەڵامەکە پیشان بدە
void main() {
var sentence = 'tea and bread and tea';
var counts = <String, int>{};
for (final word in sentence.split(' ')) {
counts[word] = (counts[word] ?? 0) + 1;
}
print(counts);
}{tea: 2, and: 2, bread: 1}counts[word] ?? 0 gives 0 the first time a word is seen, because the key is still missing.
counts[word] ?? 0 یەکەم جار کە وشەیەک دەبینرێت 0 دەدات، چونکە هێشتا نییە.
From the prices [3.0, 12.5, 1.0, 9.0] keep those above 5, take 10% off each, and print the total with two decimal places — without writing a loop.
لە نرخەکانی [3.0, 12.5, 1.0, 9.0] ئەوانە بهێڵەرەوە کە لە 5 زیاترن، 10% لە هەریەکەیان کەم بکەرەوە و کۆی گشتییەکەیان بە دوو ژمارەی دوای خاڵ چاپ بکە — بەبێ نووسینی .
Show answerوەڵامەکە پیشان بدە
void main() {
var prices = [3.0, 12.5, 1.0, 9.0];
var expensive = prices.where((p) => p > 5).toList();
var discounted = expensive.map((p) => p * 0.9).toList();
var total = discounted.fold<double>(0, (sum, p) => sum + p);
print(expensive);
print(discounted);
print(total.toStringAsFixed(2));
}[12.5, 9.0] [11.25, 8.1] 19.35
Write void repeat(int times, void Function(int) action) that calls action with 1, 2, … times. Call it so that it prints a triangle of stars.
void repeat(int times, void Function(int) action) بنووسە کە action بە 1، 2، … times بانگ بکات. وا بانگی بکە کە سێگۆشەیەک لە ئەستێرە چاپ بکات.
Show answerوەڵامەکە پیشان بدە
void repeat(int times, void Function(int) action) {
for (var i = 1; i <= times; i++) {
action(i);
}
}
void main() {
repeat(3, (n) => print('*' * n));
}* ** ***
'*' * n repeats a string n times.
'*' * n n جار دووبارە دەکاتەوە.
Summaryپوختە
- A function: return type, name, parameters, body;
voidreturns nothing;=> expris a one-expression body. - Parameters: required positional, optional positional
[ ], named{ }(optional unlessrequired, with defaults or?). - Functions are values: store them, pass them, write them anonymously; a callback is a function others call later — pass
save, notsave(). - List: ordered, index from 0. Set: no duplicates (
<T>{}when empty). Map: key → value, reads are nullable. - Build collections with
..., collection if and collection for; transform them withmap,where,foldandtoList().
- : جۆری ، ناو، ، ناوەڕۆک؛
voidهیچ ناگەڕێنێتەوە؛=> exprناوەڕۆکێکی یەک . - : شوێنیی پێویست، شوێنیی ئارەزوومەندانە
[ ]، ناودار{ }(ئارەزوومەندانە مەگەرrequiredبێت، لەگەڵ یان?). - : هەڵیانبگرە، بیاننێرە، بێناو بیاننووسە؛ کە کەسانی تر دواتر بانگی دەکەن —
saveبنێرە، نەکsave(). - List: بە ڕیزبەندی، لە 0ـەوە. Set: بەبێ دووبارە (
<T>{}کاتێک بەتاڵە). Map: ← ، خوێندنەوەکان دەشێت null بن. - کۆکراوەکان بە
...، collection if و collection for دروست بکە؛ بەmap،where،foldوtoList()بیانگۆڕە.
What is the difference between [ ] and { } parameters?جیاوازیی نێوان پارامیتەرەکانی [ ] و { } چییە؟
[ ] are optional positional (given by position); { } are named (given by name, in any order).
[ ] شوێنیی ئارەزوومەندانەن (بە شوێن دەدرێن)؛ { } ناودارن (بە ناو دەدرێن، بە هەر ڕیزبەندییەک).
Why is prices['tea'] nullable?بۆچی prices['tea'] دەشێت null بێت؟
Because the key might not be in the map; then the result is null.
چونکە لەوانەیە لە Mapـەکەدا نەبێت؛ ئەو کاتە ئەنجامەکە nullـە.
When do you need .toList()?کەی پێویستت بە .toList() هەیە؟
After map or where, when you need a real List (indexing with [], or a Flutter list of children).
دوای map یان where، کاتێک ڕاستەقینەت دەوێت (خوێندنەوە بە و []، یان لیستی childrenـی ).
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
Mitch Koko's calm beginner course in Dart and Flutter: variables, operators, if/else, switch, loops, functions, collections, a first screen and a counter.
کۆرسە ئارامەکەی Mitch Koko بۆ سەرەتاییەکان لە و : ، ، if/else، switch، ، ، List/Set/Map، یەکەم شاشە و .
Plays 19:21-29:38: functions, parameters, return types, then List, Set and Map.
لە 19:21 تا 29:38 پەخش دەبێت: ، و جۆری ، پاشان List، Set و Map.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Dart Classes, Inheritance and Mixinsکلاسەکان، بۆماوە و میکسینەکان لە Dartـدا
Related lecturesوانە پەیوەندیدارەکان
- Defining and Calling Functionsناساندن و بانگکردنی کردارەکان
- Positional, Keyword and Default Argumentsئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان
- Tuples, Sets and Dictionariesتاپڵەکان، کۆمەڵەکان و فەرهەنگەکان
- Lists: Creating and Indexingلیستەکان: دروستکردن و ئیندێکسەکان
- Dart Classes, Inheritance and Mixinsکلاسەکان، بۆماوە و میکسینەکان لە Dartـدا
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.