A Flutter project demonstrating bidirectional communication between Flutter and native platforms (iOS, Android, macOS) using Pigeon.
This project showcases how to implement type-safe communication between Flutter and native code using the Pigeon package. It demonstrates:
- Flutter-to-native platform communication
- Native-to-Flutter communication
- Handling of complex data types
- Integration with Stacked architecture
Pigeon is a code generator tool that creates type-safe interfaces for communication between Flutter and host platforms. It generates code for:
- Dart (Flutter)
- Swift/Objective-C (iOS/macOS)
- Kotlin/Java (Android)
- C++ (Windows/Linux)
This eliminates the need for error-prone manual coding of platform channels and ensures type safety across language boundaries.
/pigeons/example_pigeons.dart
- Pigeon interface definitions/lib/src/messages.g.dart
- Generated Dart code for Pigeon interfaces- iOS, Android, and macOS folders contain the generated native code
The project defines two main APIs:
// Flutter to Host
@HostApi()
abstract class ExampleHostApi {
String getHostLanguage();
int add(int a, int b);
bool sendMessage(MessageData message);
}
// Host to Flutter
@FlutterApi()
abstract class MessageFlutterApi {
String flutterMethod(String? aString);
}
Demonstrates passing complex data structures between Flutter and native platforms:
class MessageData {
MessageData({required this.code, required this.data});
String? name;
String? description;
Code code;
Map<String?, String?> data;
}
- Flutter can call native methods via
ExampleHostApi
- Native platforms can call Flutter methods via
MessageFlutterApi
- Flutter SDK
- Dart SDK
- Xcode (for iOS/macOS)
- Android Studio (for Android)
- Clone the repository
- Install dependencies:
flutter pub get
- Run the code generation for Pigeon:
dart run pigeon --input pigeons/example_pigeons.dart
- Run the app:
flutter run
- Define your API interfaces in the Pigeon file (
pigeons/example_pigeons.dart
) - Run the Pigeon code generator to create platform-specific code
- Implement the native side of the API in Swift, Kotlin, etc.
- Use the generated Dart classes in your Flutter code
The app uses the Stacked architecture pattern for state management. The HomeViewModel
demonstrates calling native methods through the Pigeon-generated API:
void showBottomSheet() {
MessageData messageData = MessageData(
code: Code.one,
data: {'name': 'From flutter', 'description': 'because its cool!'},
);
_exampleHostApi.sendMessage(messageData);
// ...
}
Native platforms implement the interface defined by Pigeon. For example, iOS implements the ExampleHostApi
protocol in Swift.
To modify or extend the API:
- Edit the
pigeons/example_pigeons.dart
file - Run the Pigeon code generator:
dart run pigeon --input pigeons/example_pigeons.dart
- Implement any new methods on the native side
- Use the updated API in your Flutter code
This project is for educational purposes and is available under the MIT License.