Share
Embed
Bridging the Gap: Understanding Method Channels for Flutter and Native Communication
Noman Khan
September 12, 2024
Transcript
36 slides
-
こんにちは (Hello), My Name is Noman Khan Your Flutter
& Native Integration Guru -
🚀 What I Do • I’m a mobile developer who
blends Flutter with native code to craft magical apps. • An open source contributor, I love sharing my knowledge and improving the tech community. • Org Admin at The Palisadoes Foundation. 🔍 My Mission • To unravel the mysteries of Method Channels and make cross-platform development smoother. 🎮 Fun Fact: • When I’m not coding, you’ll find me gaming or cheering for my favorite cricket team! -
🌏 My Journey 📍 Bihar, India: Growing up in the
heartland of India. 🎓 CSE Engineering in New Delhi: Laid the foundation for my tech career and ignited my passion for tech. 🌟 Bangalore (Silicon Valley of India): Advanced my skills in India’s tech hub, driving cutting-edge projects. Japan: Bringing my expertise to the global stage at DroidKaigi! -
2020 Started Mobile Development 2022 Google Summer of Code 2023
Google Summer of Code Mentor 2024 Google Summer of Code Org Admin 2024 International Speaker My Journey as a Developer 開発者としての私の歩み -
• Platform channels are the gateway to accessing platform-specific code
in Flutter About Platform Channel プラットフォームチャンネルについて • Flutters offers three types of platform channels for developers to utilize: 1. MethodChannel 2. EventChannel 3. BasicMessageChannel -
• "Platform-specific" refers to features, functionalities, or code that are
designed to work specifically on a particular platform, such as Android, iOS, Windows, macOS, or web. What do I mean by platform-specific? プラットフォーム固有とはどういう意味ですか ? • Accessing device-specific APIs: Such as sensors, camera, battery info, etc. • Utilizing platform-specific UI components: For example, Android has Material Design, while iOS uses Cupertino design. • Handling platform-specific features: Features like background tasks, notifications, permissions, or platform-specific storage methods can vary significantly between platforms. -
What is Method Channels? 🧐 Communication Bridge: A Method Channel
is primarily for sending messages from Dart to a host platform and getting the results back. It makes integrating platform-specific APIs or libraries with your Flutter app an absolute breeze.. Simple API Calls: Works like calling a function—Flutter sends a message (method call), native code executes it, and then returns the result back to Flutter. -
What is Event Channel ? 🧐 • One key difference
differentiating it from MethodChannel is its ability to communicate continuously from a host platform to Dart. • When you need to observe platform-side events and reflect changes in your Flutter app. • It is ideal for scenarios like listening to sensor data, receiving platform notifications, or gathering information from third-party SDKs. -
What is BasicMessageChannel ? 🧐 • It permits communication in
both directions - from Dart to the host platform and vice-versa, lending itself well for use cases where bidirectional communication is needed without getting responses or results. • It doesn't support directly returning a result or having an event stream, such as method calls or event channels. • Broadcast messages from your native code to Dart or the reverse direction. -
Platform Channels 🆚 Method Channels ! • Only one type:
Method Channel. • Synchronous method call-based communication with immediate responses. • Uses binary message encoding. • Best for calling functions on the native side and getting immediate results back. • Includes Method Channels, Basic Message Channels, Event Channels, and Standard Message Channels. • Can be both synchronous (Method Channels) and asynchronous (Event Channels, etc.). • can be binary, string messages, or structured data streams. • Covers broader scenarios including real-time data streams, simple data transfer, and method invocation. Platform Channels Method Channels -
Dart Method Call Handler 🤔 • A Dart method call
handler is a necessary component when operating with method channels. It appoints a function responsible for receiving method calls and giving appropriate responses. -
Use Case of Method Channels 🤔 メソッドチャネルの使用例 • Access Native
Features (Bluetooth, GPS, sensors) • Integrate with Native SDKs • Reusability of Existing Code • Optimize Performance • Custom Functionality -
Step 1: Create the Flutter platform client How to Implement
Method Channel? メソッドチャネルを実装するには ? -
Step 2: Invoke a method on the method channel, specifying
the concrete method to call using the String identifier getBatteryLevel. -
Step 4: Open the file MainActivity.kt located in the kotlin
folder in the Project view. add the following method in the MainActivity class, below the configureFlutterEngine() method: -
Step 5: create a MethodChannel and call setMethodCallHandler(). Make sure
to use the same channel name as was used on the Flutter client side. -
Step 6: Open the file AppDelegate.swift Add the following as
a new method at the bottom of AppDelegate.swift: -
Step 7: Override the application:didFinishLaunchingWithOptions: function and create a FlutterMethodChannel
tied to the channel name noman.test/battery: -
Best Practices 🎯 ベストプラクティス • Consistent Channel Names • Error
Handling • Avoid Channel Blocking • Use Right Channel for the Right Job • Keyword Restrictions -
Handling Errors in Platform Channels ⚠ • we employ a
try-catch block to handle possible errors that could arise when we invoke the method MethodName. If a PlatformException is encountered, we print out the error message to our console. -
Understanding the Direct Communication 📱 • Direct communication implies writing
native code in your Dart files, often using inline strings, and then having Dart interface with this code. This approach could be facilitated using a package like 'ffi'. -
The Power of Flutter Platform Channels 📱 • Flutter platform
channels segregate native code cleanly away from your Dart codebase. • Flutter inherently supports efficient binary serialization, facilitating high-performance, low-latency communications. -
Handling Non-String Data in Flutter MethodChannel • The standard message
codec in the Flutter platform channel supports efficient binary serialization of simple JSON-like values, which include not just strings but booleans, lists, maps, and even byte buffers. • It gets serialized to a binary form, transmitted, and then deserialized at the receiver's end. -
Why Migrate? • They render direct interaction with platform-specific native
code, aiding in using specific APIs and delivering a more native-like feel to the apps. Developers can invoke native methods from Dart, harnessing the power of the underlying platform. • Further, the platform channels bestow greater control over the UI components, leading to user interface enhancements and making your Flutter app more responsive. -
Step-By-Step Migration Guide • Identify the Components • Select the
Appropriate Channel • Define the Channel on both Sides • Set Up the Method Call Handler • Handle the Method Call in Native Code • Testing & Debugging