Learn/Platform Integration/Platform-Adaptive UI & Pigeon

Platform-Adaptive UI & Pigeon

Build platform-aware interfaces and generate type-safe platform channel code with Pigeon

8 min~7 min read+45 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Pigeon for Type-Safe Channels
  2. 2. Platform Adaptation Decision Rules
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. Quick Glossary
  10. 10. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Platform-Adaptive UI & Pigeon

Flutter apps run on Android, iOS, web, desktop, and more, but users on each platform expect the interface to follow their platform conventions. Android users expect Material Design components like floating action buttons, bottom navigation bars, and snack bars. iOS users expect Cupertino-style components like sliding segmented controls, tab bars at the bottom, and action sheets. Flutter provides both Material and Cupertino widget libraries so you can build platform-adaptive interfaces that feel native on every platform. You can detect the current platform at runtime using Theme.of(context).platform or the Platform class from dart:io and render the appropriate widget for each platform. Beyond UI adaptation, if you need to call native platform APIs, the Pigeon package generates type-safe platform channel code that eliminates the error-prone string matching of raw MethodChannel calls. You define your API in a Dart file, run the Pigeon code generator, and it produces strongly typed Kotlin, Swift, C++, or Objective-C code for the native side along with the corresponding Dart bindings. This ensures that method names, argument types, and return types are always in sync between Dart and native code.

dart
1// ── Platform-Adaptive Widgets ──
2import 'dart:io' show Platform;
3import 'package:flutter/cupertino.dart';
4import 'package:flutter/material.dart';
5
6// Adaptive dialog that uses Material on Android, Cupertino on iOS
7Future<void> showAdaptiveAlert(BuildContext context, String message) {
8 if (Platform.isIOS) {
9 return showCupertinoDialog(
10 context: context,
11 builder: (_) => CupertinoAlertDialog(
12 title: const Text('Alert'),
13 content: Text(message),
14 actions: [
15 CupertinoDialogAction(
16 child: const Text('OK'),
17 onPressed: () => Navigator.pop(context),
18 ),
19 ],
20 ),
21 );
22 }
23 return showDialog(
24 context: context,
25 builder: (_) => AlertDialog(
26 title: const Text('Alert'),
27 content: Text(message),
28 actions: [
29 TextButton(
30 onPressed: () => Navigator.pop(context),
31 child: const Text('OK'),
32 ),
33 ],
34 ),
35 );
36}
37
38// Adaptive switch using Flutter built-in adaptive constructor
39Switch.adaptive(
40 value: isDarkMode,
41 onChanged: (val) => setState(() => isDarkMode = val),
42)
43
44// Adaptive indicator
45CircularProgressIndicator.adaptive()
46
47// Platform-aware scaffold pattern
48class AdaptiveScaffold extends StatelessWidget {
49 final Widget body;
50 final String title;
51 const AdaptiveScaffold({super.key, required this.body, required this.title});
52
53 @override
54 Widget build(BuildContext context) {
55 if (Platform.isIOS) {
56 return CupertinoPageScaffold(
57 navigationBar: CupertinoNavigationBar(middle: Text(title)),
58 child: SafeArea(child: body),
59 );
60 }
61 return Scaffold(
62 appBar: AppBar(title: Text(title)),
63 body: body,
64 );
65 }
66}

Pigeon for Type-Safe Channels

The Pigeon package generates type-safe platform channel code from a simple Dart definition file. Instead of passing raw strings and dynamic values through MethodChannel, you define structured request and response classes along with an abstract API interface. Running the Pigeon code generator produces native code for Android (Kotlin or Java), iOS (Swift or Objective-C), Windows (C++), and macOS, along with the Dart bindings. The generated code handles serialization, deserialization, and error handling automatically, so you never have to worry about mismatched method names or data types.

dart
1// ── Pigeon Setup ──
2// pubspec.yaml (dev_dependencies):
3// pigeon: ^22.0.0
4
5// ── Step 1: Define the API in a Dart file ──
6// pigeons/messages.dart
7import 'package:pigeon/pigeon.dart';
8
9class SearchRequest {
10 final String query;
11 final int maxResults;
12 SearchRequest({required this.query, required this.maxResults});
13}
14
15class SearchResult {
16 final String title;
17 final String url;
18 SearchResult({required this.title, required this.url});
19}
20
21// @HostApi means Flutter calls native code
22@HostApi()
23abstract class SearchApi {
24 @async
25 List<SearchResult> search(SearchRequest request);
26}
27
28// @FlutterApi means native code calls Flutter
29@FlutterApi()
30abstract class NotificationApi {
31 void onNotificationReceived(String message);
32}
33
34// ── Step 2: Generate code ──
35// dart run pigeon --input pigeons/messages.dart
36
37// This generates:
38// - android/app/src/main/kotlin/.../Messages.g.kt
39// - ios/Runner/Messages.g.swift
40// - lib/messages.g.dart
41
42// ── Step 3: Use generated Dart code ──
43class SearchService {
44 final SearchApi _api = SearchApi();
45
46 Future<List<SearchResult>> search(String query) async {
47 final request = SearchRequest(query: query, maxResults: 10);
48 return await _api.search(request);
49 }
50}
51
52// ── Step 4: Implement native side (Kotlin example) ──
53// class SearchApiImpl : SearchApi {
54// override fun search(
55// request: SearchRequest,
56// callback: (Result<List<SearchResult>>) -> Unit
57// ) {
58// val results = performNativeSearch(request.query, request.maxResults)
59// callback(Result.success(results))
60// }
61// }
62//
63// // Register in MainActivity
64// SearchApi.setUp(flutterEngine.dartExecutor, SearchApiImpl())

Adaptive Widgets

💡 Adaptive Widgets

Flutter provides several widgets with an .adaptive constructor that automatically switch between Material and Cupertino styles based on the platform. These include Switch.adaptive, Slider.adaptive, CircularProgressIndicator.adaptive, and AlertDialog.adaptive. Use these whenever possible to reduce platform-specific code while still providing a native feel on each platform.

Platform Adaptation Decision Rules

Adaptation should preserve product consistency while respecting platform expectations:

  • Keep business flow identical, adapt interaction patterns and visual language.
  • Use adaptive widgets first, then custom branching only for major UX differences.
  • Centralize platform checks in reusable builders or scaffold abstractions.
  • Validate accessibility parity across Material and Cupertino variants.

The goal is native feel without maintaining two unrelated app experiences.

Adaptive And Pigeon Checklist

  • Platform-specific UI branches are intentional and documented.
  • Generated Pigeon code is committed and regenerated on API changes.
  • Host and Flutter API contracts include nullability and error semantics.
  • Native implementations are tested on both Android and iOS paths.
  • Fallback behavior exists when platform feature is unavailable.

This Lesson In Simple Words

Build platform aware interfaces and generate type safe platform channel code with Pigeon. Forms collect user input, and validation ensures the input is safe and useful.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Show validation messages early and clearly, near the field that needs correction.

Deep Understanding Guide

Why this lesson matters

Most app trust problems start when invalid or incomplete input reaches backend systems.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat forms as mini workflows: input, validate, submit, and recover from errors.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Validating only on submit and giving late feedback to users.
  • Using vague error text that does not tell users what to fix.
  • Forgetting to trim whitespace and normalize input values.
  • Not handling keyboard focus flow and accessibility labels.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build a signup form with per-field validators and submit-state handling.
  • Add password strength feedback with friendly, actionable hints.
  • Simulate a server validation error and show a user-safe message.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does the Pigeon package do?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • context: A handle to widget location and inherited data in the tree.
  • build: The method that describes UI for the current state.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Validated input at UI and domain layers protects business logic from invalid assumptions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Platform-Adaptive UI & Pigeon" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Validating only on submit and giving late feedback to users.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does the Pigeon package do?

Pigeon takes a Dart API definition file and generates strongly typed native code for Android, iOS, and other platforms along with Dart bindings.

What does the @HostApi() annotation mean in Pigeon?

The @HostApi annotation indicates that the API is implemented on the native (host) side and called from the Flutter (client) side.

How do you detect the current platform at runtime in Flutter?

The Platform class from dart:io provides boolean properties like isIOS, isAndroid, isWindows, and others to detect the current platform at runtime.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue