الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 9 دقائق للقراءة

الـ platform channels رسايل async مش function calls: إزاي Flutter بيكلم الكود الـ native

الـ invokeMethod بيعمل encode للـ arguments، ويبعتها للـ main thread بتاع المنصة، ويدّيك Future. مفيش غير قيم الـ codec اللي بتعدّي، والأخطاء بتوصل بعدين.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

تطبيق Flutter بيعمل schedule للـ reminders عن طريق MethodChannel. الـ handler بتاع الزرار بينادي invokeMethod('schedule', ...) بـ map فيها الـ ID بتاع الـ reminder والـ DateTime بتاعه، وبعدين يعرض snackbar مكتوب فيه "Reminder set". والمستخدمين بيشتكوا إن الـ reminders مش بتشتغل. كود الـ Kotlin والـ Swift سليم؛ هو أصلًا ماتنداش. الـ DateTime ماينفعش يتعمله encode، والـ error راح في Future محدش عمله await، والـ snackbar كان وعد بالنجاح خلاص.

الفكرة الغلط الشائعة

الفكرة بتقول إن نداء الكود الـ native عن طريق MethodChannel ده function call مباشر جوه Kotlin أو Swift. بيتنفذ على طول، وتقدر تبعتله أي Dart object، بالظبط زي ما تبعته لأي Dart function تانية.

والـ API نفسه بيشجّعك تفهمه كده. الـ class اسمها MethodChannel، والـ method اسمها invokeMethod، والناحية الـ native بتستلم call فيه method وarguments، زي أي dispatcher. والـ parameter بتاع arguments نوعه dynamic، فالـ compiler بيقبل أي حاجة. وأغلب الـ plugins بتخبّي الـ channel ورا Dart method ليها types، وعلى موبايل سريع الرد بيبان كأنه فوري. ونص الحقيقة: هو فعلًا call من ناحية الفكرة، request وليه رد. بس بيسافر كرسالة، بين threads، وبيعدّي على serialization، وكل واحدة من دول ليها قواعدها وطرق فشلها.

اللي بيحصل فعلًا

الـ call بتاعك بيتحوّل لرسالة

الـ docs بتاعة الـ API بتوصفها بوضوح: الـ method calls "are encoded into binary before being sent, and binary results received are decoded into Dart values." ودليل Flutter بيضيف إن الرسايل والردود بتتبعت "asynchronously through channels to ensure the user interface remains responsive." فالـ invokeMethod دايمًا بيرجّع Future، والكود اللي بعده بيتنفذ قبل ما الرد يبقى موجود. وفي test فيه native handler معمول له mock، الـ log اللي اتكتب حوالين الـ call طلع بالترتيب ده: before call وبعدين after call وبعدين result: true.

وعلى الناحية التانية، الـ handler بيشتغل by default على الـ main thread بتاع المنصة. الدليل بيقول إن الـ handlers "can execute on the platform's main thread or they can execute on a background thread if using a Task Queue." ومن ناحية Dart، الـ calls لازم تطلع من الـ root isolate أو من متسجّل كـ background isolate. وفيه حاجة مطمّنة: الـ channels اللي الـ framework بيوفّرها "guarantee FIFO ordering"، فالـ calls على نفس الـ channel بتوصل بنفس الترتيب اللي بعتّها بيه.

مفيش غير قيم الـ codec اللي بتعدّي

الـ بيشيل اللي الـ بتاعه يقدر يعمله encode. والـ default، اللي هو StandardMessageCodec، بيدعم null والـ bools والأرقام والـ strings والـ typed data lists زي Uint8List، والـ lists والـ maps اللي فيها الحاجات دي. والـ docs بتاعة MethodChannel واضحة في الباقي: "The use of unsupported values should be considered programming errors, and will result in exceptions being thrown."

وإحنا عدّينا قيم كتير من channel جوه flutter test. الـ DateTime والـ Duration والـ Uri والـ Set والـ BigInt وclass خاصة اسمها User، كل واحدة فيهم فشلت بـ ArgumentError زي Invalid argument: Instance of 'DateTime'. والـ map اللي جواها DateTime فشلت بنفس الشكل. وفي كل حالة فشل، الـ native handler اللي عاملينله mock ماشتغلش خالص: الـ call مات وهو بيتعمله encode، ولسه جوه Dart. والـ invokeMethod نفسه مارماش exception. رجّع Future، والـ error ماظهرش غير لما الـ Future ده اتعمله await.

اللي بيرجع ملوش types واضحة

الـ codec بيعمل decode لـ List<Object?> وMap<Object?, Object?> "irrespective of content." ولما طلبنا invokeMethod<Map<String, Object?>> في الـ test، رمى TypeError: '_Map<Object?, Object?>' is not a subtype of type 'Map<String, Object?>?'. والـ docs بتحذّر إن الـ type argument "cannot be a class with generics other than dynamic." أما invokeMapMethod<String, Object?> فاشتغل، لأنه بيعمل cast للـ map بدالك.

الفشل جزء من الاتفاق

الـ Future اللي بيرجع بيخلص بواحدة من تلاتة: نتيجة، أو PlatformException لما الكود الـ native يبلّغ عن error، أو MissingPluginException لما مفيش حد بيتعامل مع الـ method. وأسامي الـ methods والـ channels strings بتتطابق وقت التشغيل، فأي typo مش compile error؛ وفي الـ test بتاعنا ظهر كـ No implementation found for method ping on channel app/missing. ومقال ReadIn عن إن الـ network call مش method call بيقول نفس الكلام عن السيرفرات، وأغلبه بينطبق هنا كمان.

نخلّي نداء الـ reminder صريح

Dart reminder_button.dart
const channel = MethodChannel('app/reminders');void onSetReminder(BuildContext context, Reminder r) {  // Not awaited, and DateTime isn't a codec type:  // the ArgumentError lands in a Future nobody listens to  channel.invokeMethod('schedule', {'id': r.id, 'at': r.at});  ScaffoldMessenger.of(context)      .showSnackBar(const SnackBar(content: Text('Reminder set')));}

شغّلنا النسخة الغلط جوه guarded zone: سطر الـ snackbar اتنفذ، والـ zone مسكت Invalid argument: Instance of 'DateTime'، والـ native handler اتنادى صفر مرات. ومع millisecondsSinceEpoch اتنادى مرة واحدة. والنسخة الصح كمان بتمسك الـ ScaffoldMessenger قبل الـ await، للأسباب اللي في المقال بتاع الـ BuildContext بعد الـ await. والـ MissingPluginException مش PlatformException، فامسكه هو كمان لو الـ method ممكن تبقى مش موجودة على منصة معينة.

function call في Dartcall على MethodChannel
النتيجة بتبقى موجودة إمتىلما الـ function ترجعبعدين، من خلال Future
تقدر تبعت إيهأي Dart objectقيم الـ codec: null وbool وnum وString وtyped data وList وMap
إيه اللي بيرجعالنوع المكتوبMap<Object?, Object?> أو List<Object?>، وانت اللي بتعمل cast
الأسامي بتتشيك إزايبالـ compilerكـ strings وقت التشغيل
الكود بيشتغل فينفي نفس الـ isolateعلى الـ main thread بتاع المنصة، إلا لو استخدمت Task Queue
Dart pigeons/reminders.dart
// Input for Pigeon's code generator, not app codeclass ReminderMessage {  ReminderMessage({required this.id, required this.atMillis});  final String id;  final int atMillis;}@HostApi()abstract class ReminderApi {  @async  bool schedule(ReminderMessage reminder);}

والـ mode بتاع الـ platform channels في Pigeon لسه messaging asynchronous، بس بـ types. والـ README بتاعه بيوصف كمان mode تجريبي للـ native interop مبني على Dart FFI وJNI، بيدعم الـ synchronous host calls، على Android وiOS وmacOS بس.

تطبقها إزاي في مشروعك

  1. اعمل await لكل invokeMethodدوّر على أي invokeMethod مش معمولها await أو return. واتعامل مع PlatformException، ومع MissingPluginException لو فيه منصة ممكن ماتكونش فيها الـ method.
  2. حوّل القيم عند الحدودحوّل الـ DateTime لـ milliseconds أو ISO string، والـ enums لأسامي، والـ objects لـ maps قبل ما تبعت. وعمرك ما تبعت domain objects من channel.
  3. اعمل cast للي بيرجعاستخدم invokeMapMethod أو invokeListMethod، أو اعمل cast للنتيجة على طول، واتأكد من الـ fields اللي بتقراها.
  4. ابعد الشغل الـ native التقيل عن الـ main threadانقل الـ handlers التقيلة لـ Task Queue. ولو بتنادي channel من background isolate، سجّله بـ BackgroundIsolateBinaryMessenger الأول.
  5. اختبر الـ channel وفكّر في Pigeonاكتب tests بـ flutter test وsetMockMethodCallHandler بتبعت arguments حقيقية، وانقل البروتوكولات اللي معمولة بـ strings بإيدك لـ Pigeon لما تكبر.

الخلاصة

  • الـ invokeMethod بيبعت رسالة متعملها encode ويرجّع Future، والكود اللي بعده بيتنفذ قبل الرد.
  • مفيش غير قيم الـ codec اللي بتعدّي: الـ DateTime والـ Set والـ classes بتاعتك بتفشل بـ ArgumentError قبل ما تخرج من Dart.
  • الـ error ده بيوصل من خلال الـ Future، فالـ call اللي مش معمولها await بتفشل من غير صوت.
  • النتايج بتتعمل decode كـ Map<Object?, Object?> وList<Object?>، فاستخدم invokeMapMethod أو اعمل cast.
  • الـ native handlers بتشتغل على الـ main thread بتاع المنصة by default، فاستخدم Task Queue للشغل البطيء، وPigeon للـ types.

📚 المصادر

  1. Writing custom platform-specific code — Flutter docs
  2. MethodChannel class — Flutter API
  3. MethodChannel.invokeMethod — Flutter API
  4. StandardMessageCodec class — Flutter API
  5. pigeon — pub.dev

التعليقات (0)