
علامة الـ ! وعد مش حل: إزاي الـ Sound Null Safety في Dart بتشتغل
- كاتب موثّق
- Dart 3
محتويات المقال
Null check operator used on a null value، جاي من شاشة الحساب. وبيحصل بس للناس اللي عملوا sign up برقم موبايل، لأن الإيميل بتاعهم null. من 3 شهور، الـ analyzer علّم على profile.email إنه ممكن يبقى null، والـ IDE عرض quick fix، ودوسة زرار واحدة شالت الخط الأحمر. الدوسة دي كانت !.
الفكرة الغلط الشائعة
! والـ late طرق مالهاش ضرر عشان تسكّت الـ analyzer. انت عارف إن القيمة مش هتبقى null، والـ analyzer بيدقق زيادة عن اللزوم، وحرف واحد بيخلّص النقاش.
error فيها عمره ما بيتقري وهو null، وده رابط الـ type checker مش قادر يتتبعه. والـ IDEs بتعرض "add a null check" كـ fix بضغطة واحدة. والـ developers الجايين من TypeScript أو C# بيجيبوا معاهم قاعدة إن الـ ! اللي بعد الـ expression مش بيغيّر أي حاجة وقت التشغيل، وده بالظبط اللي الـ docs بتاعة اللغتين دول بتقوله عن النسخة بتاعتهم. لكن في Dart الموضوع مختلف.
اللي بيحصل فعلًا
الـ Sound null safety ضمان، مش lint
String ماينفعش يشيل null، والـ String? ينفع. ومع الـ ، اللي Dart بيفرضها من أول Dart 3، الوعد قوي: لو النوع الـ static بتاع expression مش بيسمح بـ null، يبقى مفيش أي تشغيل ليها ممكن يطلّع null. والـ errors اللي بتشوفها من الـ analyzer هي طريقة Dart إنه يحافظ على الوعد ده قبل ما الكود يشتغل، والـ docs بتاعة Dart بتقول إن التصميم ده بيدّيك bugs أقل وbinaries أصغر وتنفيذ أسرع.
الـ ! عبارة عن cast بيتشيك وقت التشغيل
! عبارة عن cast بيتشيك وقت التشغيل! دايمًا بيرمي exception لو القيمة null. يعني مش بيصلّح الـ null، بيحوّل error وقت الـ compile لـ exception محتملة وقت التشغيل، في السطر ده بالظبط.
class Profile { Profile({this.email}); final String? email; // null until the user verifies it}String greeting(Profile profile) { // The analyzer is quiet now. The runtime isn't. return 'Signed in as ${profile.email!}';}void main() { print(greeting(Profile(email: 'sara@example.com'))); print(greeting(Profile())); // Null check operator used on a null value}class Profile { Profile({this.email}); final String? email; // null until the user verifies it}String greeting(Profile profile) { final email = profile.email; // a local copy, so the null check promotes it if (email == null) return 'Signed in (email not verified)'; return 'Signed in as $email';}void main() { print(greeting(Profile(email: 'sara@example.com'))); print(greeting(Profile())); // Signed in (email not verified)}dart run هتطبع Signed in as sara@example.com، وبعدين تقف بـ unhandled exception: Null check operator used on a null value، وبتشاور على السطر اللي فيه !. أما التانية فبتطبع الرسالتين.
ليه الـ analyzer زقّك ناحية الـ !؟
!؟if (profile.email != null) والـ analyzer برضه بيشتكي، لأن الـ بتشتغل على الـ local variables والـ parameters، ومن Dart 3.2 على الـ private final fields. والـ email هنا public field، والـ analyzer بيقولها صريحة: "'email' refers to a public property so it couldn't be promoted." يعني ممكن library تانية تعمل override له بـ getter بيرجّع حاجة مختلفة تاني مرة. ولما تنسخه في local variable زي النسخة الصح، بتدّي الـ analyzer قيمة مستحيل تتغير بين الـ check والاستخدام.
الـ late وعد بخصوص التوقيت
late وعد بخصوص التوقيتlate بيعمل نفس الصفقة بس مع الـ initialization. وعلى حسب كلام Dart، معناه إن الـ constraints بتاعة الـ variable تتشيك وقت التشغيل بدل وقت الـ compile. كل قراءة بتتأكد إن الـ variable اتحطله قيمة، ولو لأ بترمي LateInitializationError. والـ late final كمان بيتأكد إنه اتحطله قيمة مرة واحدة بس. وفي Flutter، الغلطة الكلاسيكية field بيتملي من async call:
class _ProfilePageState extends State<ProfilePage> { late User _user; // a promise: assigned before build() reads it @override void initState() { super.initState(); loadUser().then((user) => setState(() => _user = user)); } @override Widget build(BuildContext context) => Text(_user.name); // frame 1: throws}class _ProfilePageState extends State<ProfilePage> { User? _user; // null means "not loaded yet", and the type says so @override void initState() { super.initState(); loadUser().then((user) { if (mounted) setState(() => _user = user); }); } @override Widget build(BuildContext context) { final user = _user; // a local copy, so the null check promotes it if (user == null) return const CircularProgressIndicator(); return Text(user.name); }}build() بتشتغل بعد initState على طول، قبل ما الـ future يخلص بكتير. وفي widget test، أول frame في النسخة الغلط رمى LateInitializationError عشان _user، أما النسخة الصح فعرضت spinner وبعدين الاسم.
String? ومعاه if (x == null) … | ||
x ?? 'fallback'، x?.length | null بتكمّل عادي | |
x! | x بـ null | |
late String x; | ||
late final String x; |
تطبقها إزاي في مشروعك
راجع الـ `!` والـ `late` اللي عندك دوّر عليهم في الكود كله. ولكل واحد اسأل: إيه اللي ضامن إن القيمة دي موجودة؟ لو الإجابة "غالبًا بتبقى موجودة"، خلّي النوع nullable واتعامل مع الـ null. انسخ الـ fields في locals قبل ما تعمل check اكتب final email = profile.email;وبعدين اعمل check علىemail. الـ promotion هتشتغل على الـ local، والـ check والاستخدام هيشوفوا نفس القيمة، والـ!هيختفي.خلّي النوع يعبّر عن "لسه" و"مش موجود" الداتا اللي بتتحمّل async، والـ fields الاختيارية من الـ server، والـ input اللي لسه ماتأكدش، كلها nullable بطبيعتها. استخدم ?، أو loading state، أو قيمة default بـ??بدلlate.خلّي الـ quick fix بتاع الـ analyzer آخر حل لما الـ IDE يعرض "add a null check"، اقراها "ضيف crash وقت التشغيل لو طلعت غلطان". جرّب الـ promotion أو ??أو?.الأول.
الخلاصة
الـ null safety في Dart sound: النوع الـ non-nullable عمره ما يشيل null وقت التشغيل، فالـ compiler بيتشيك على وعودك. الـ !عبارة عن cast بيتشيك وقت التشغيل، وبيرميNull check operator used on a null valueلو القيمة null.الـ lateبينقل checks الـ initialization لوقت التشغيل، وبيرميLateInitializationErrorلو اتقرا قبل ما ياخد قيمة.اعمل promote بـ local variable وnull check، أو استخدم ??و?.، قبل ما تفكر في!.سيب الـ !والـlateللـ invariants اللي تقدر تثبتها، مش للقيم اللي "غالبًا" موجودة.
التعليقات (0)