Irbisa · Шпаргалка
Основы Dart
Переменные, типы, функции, null safety и базовый синтаксис Dart
Какие встроенные типы есть в Dart и что значит «всё является объектом»?
В чём разница между
var,dynamicиObject?в Dart?void main() { var name = 'Alice'; // inferred as String // name = 42; // compile error dynamic value = 'Alice'; value = 42; // allowed: no static type…В чём разница между
finalиconstв Dart?final startedAt = DateTime.now(); // runtime value: fine for final// const now = DateTime.now(); // compile error: not a constant const maxItems = 100;const colors = ['red', 'green']; // deeply immutable…Что такое sound null safety в Dart и чем отличаются nullable и non-nullable типы?
void show(String? email) { // may be null // print(email.length); // compile error: email may be null if (email != null) { print(email.length); // promoted to String inside the if }}…Что делают null-aware операторы
?.,??,??=,?..,...?и оператор!?class User { final String? nickname; User(this.nickname);} String label(User? user) =>…Что делают
is,is!иasв Dart и почемуasможет упасть в рантайме, аisне может?double priceOf(Map<String, dynamic> json) { // wrong: throws when the server sends 10 instead of 10.0 // return json['price'] as double; // right: accept int or double, convert once return (json['price'] as num).toDouble();…Чем отличаются позиционные, именованные и необязательные параметры в Dart и что делает
required?int add(int a, int b) => a + b; // positional, required // optional positional: in [ ], must come lastString log(String msg, [String level = 'INFO']) => '[$level] $msg'; // named: in { }, any order at the call site…Что такое стрелочные функции, анонимные функции и замыкания в Dart?
int twice(int x) => x * 2; // named function, arrow body // closure: the returned function keeps `count` aliveint Function() makeCounter() { var count = 0; return () => ++count;…Что такое
typedefв Dart и как объявить тип функции?// a function type written inlinevoid run(int Function(int, int) op) => print(op(2, 3)); // the same idea with namestypedef BinaryOp = int Function(int a, int b);typedef Json = Map<String, dynamic>; // alias for any type…Что может содержать
enumв Dart начиная с Dart 2.17 (поля,const-конструктор, методы,implements) и как превратить значение вStringи обратно?enum Plan implements Comparable<Plan> { free(priceCents: 0, maxProjects: 3), pro(priceCents: 999, maxProjects: 50), team(priceCents: 2999, maxProjects: 500); const Plan({required this.priceCents, required this.maxProjects});…Чем отличаются
List,SetиMapи какие методы коллекций должен знать каждый Dart-разработчик?class User { final int id; final String name; const User(this.id, this.name);}…Как работают каскад
.., spread...и collectionif/forв Dart?class Request { String method = 'GET'; final headers = <String, String>{}; void send() => print('$method $headers');}…Что выведет этот код и как Dart передаёт объекты в переменные и функции?
void reassign(List<int> items) { items = [99];} void mutate(List<int> items) { items.add(4);} void main() { final a = [1, 2, 3]; final b = a; b.add(0); reassign(a); mutate(b); print(a);}Если бы каждая из строк A–E выполнялась отдельно, какие из них бросят исключение в рантайме и какой список в каждой переменной?
void main() { final a = [1, 2]; a.add(3); // line A const b = [1, 2]; b.add(3); // line B final c = List.unmodifiable(a); c[0] = 9; // line C final d = List.filled(2, 0); d[0] = 9; // line D d.add(1); // line E}Найдите баг: после одного хода
Xпоявляется в каждой строке этой доски.class Board { Board(this.size) : cells = List.filled(size, List.filled(size, '.')); final int size; final List<List<String>> cells; void place(int row, int col, String mark) => cells[row][col] = mark; String render() => cells.map((row) => row.join()).join('\n');} void main() { final board = Board(3)..place(0, 1, 'X'); print(board.render());}Как устроена обработка ошибок в Dart и чем
Exceptionотличается отError?class PaymentDeclined implements Exception { final String code; const PaymentDeclined(this.code); @override String toString() => 'PaymentDeclined($code)';}…Для чего в Dart нужен
assertи почему проверку данных в продакшене нужно делать черезthrow, а ветки только для debug оформлять черезkDebugMode?import 'package:flutter/foundation.dart'; class Badge { final int count; // our own invariant: checked in debug, gone in release const Badge(this.count) : assert(count >= 0, 'count must be >= 0');…Что выведет этот код и почему цикл
forи циклwhileведут себя по-разному?void main() { final callbacks = <void Function()>[]; for (var i = 0; i < 3; i++) { callbacks.add(() => print(i)); } var j = 0; while (j < 3) { callbacks.add(() => print(j)); j++; } for (final cb in callbacks) cb();}Найдите баг: этот контроллер иногда падает с «Null check operator used on a null value» в
refreshAvatar.class ProfileController { ProfileController(this.api); final AvatarApi api; User? user; // cleared on logout Future<void> refreshAvatar() async { if (user == null) return; final url = await api.fetchAvatarUrl(user!.id); user!.avatarUrl = url; } void logout() => user = null;}В чём разница между
==иidentical()в Dart и как на неё влияет канонизацияconst?class Point { final int x, y; const Point(this.x, this.y);} class Money {…Почему
0.1 + 0.2 == 0.3в Dart даёт false и как хранить и считать деньги?String formatCents(int cents) => '${cents ~/ 100}.${(cents % 100).toString().padLeft(2, '0')}'; void main() { print(0.1 + 0.2); // 0.30000000000000004 print(0.1 + 0.2 == 0.3); // false…Чем отличаются UTC и локальные значения
DateTimeв Dart и как хранить и сравнивать даты, чтобы пользователи за границей видели верное время?void main() { // wrong: no Z, parsed as LOCAL, so the instant differs per device final a = DateTime.parse('2026-03-29T10:00:00'); // right: explicit UTC, the same instant everywhere final b = DateTime.parse('2026-03-29T10:00:00Z');…