Intégration de l’interface native
Explorez les techniques permettant d’intégrer des vues natives de la plateforme dans l’arborescence de vos widgets Flutter afin de créer des expériences utilisateur hautement personnalisées.
Intégration de l’interface native est une leçon Flutter Mobile Development gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Flutter Mobile Development, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Flutter Mobile Development comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Bridging Flutter and Native UI
Welcome to Native UI Integration! While Flutter offers a rich set of widgets, sometimes you might encounter a need to embed a pre-existing or highly specialized native Android or iOS UI component directly into your Flutter application.
This lesson explores how to achieve this, allowing you to leverage the best of both Flutter and native platforms.
Why Embed Native UI?
Why would you choose to embed native UI instead of building everything in Flutter? Here are some common reasons:
- Performance: For highly optimized native components like complex map views, video players, or 3D rendering engines.
- Complexity: When replicating a feature in Flutter would be overly difficult or time-consuming, especially for intricate platform-specific behaviors.
- Existing Libraries: To leverage powerful, platform-specific UI libraries that do not have Flutter equivalents or robust plugins.
- Specific Features: Accessing unique native UI elements not easily exposed via standard Flutter widgets or plugins.
It's a powerful tool for advanced integration challenges.
The `PlatformView` Widget
Flutter provides the abstract PlatformView widget as the foundation for embedding native UI. You won't use PlatformView directly, but it serves as the base for platform-specific implementations:
AndroidViewfor embedding native Android views.UiKitViewfor embedding native iOS views.
These widgets act as a crucial bridge, allowing Flutter to render a native view within its own widget tree seamlessly.
Android: `AndroidView` Basics
On Android, you use the AndroidView widget to embed native views. For this to work, you need to register a PlatformViewFactory in your native Android project (Kotlin or Java).
This factory is responsible for creating instances of your native Android View or ViewGroup when Flutter requests it. Each native view needs a unique viewType string to identify it.
Android: Conceptual Setup
Setting up a native Android view for Flutter embedding involves a few key steps on the native side:
- Create Native View: Develop your custom Android
VieworViewGroupsubclass. - Implement Factory: Create a
PlatformViewFactoryclass that instantiates your native view. - Register Factory: Register this factory with a unique
viewTypein yourMainActivity.ktorMainActivity.java.
This tells Flutter how to find and create your specific native UI component.
Flutter `AndroidView` Example
Here's how you'd use AndroidView in your Flutter code. This example assumes you've set up a native Android TextView named "myNativeTextView" via a factory in your Android project.
Try running this simple Flutter code (note: the native view will only appear if the corresponding Android setup is complete):
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Native Android View')),
body: Center(
child: SizedBox(
width: 200,
height: 100,
child: AndroidView(
viewType: 'myNativeTextView',
layoutDirection: TextDirection.ltr,
creationParams: <String, dynamic>{'text': 'Hello from Android!'},
creationParamsCodec: const StandardMessageCodec(),
),
),
),
),
);
}
}iOS: `UiKitView` Basics
For iOS, the equivalent widget is UiKitView. Similar to Android, you need to register a FlutterPlatformViewFactory in your native iOS project (Swift or Objective-C).
This factory is responsible for creating instances of your native iOS UIView when Flutter needs to display it. Each native view requires a unique viewIdentifier string.
iOS: Conceptual Setup
Integrating an iOS native view for Flutter embedding involves these steps on the native side:
- Create Native View: Develop your custom iOS
UIViewor aUIViewsubclass. - Implement Factory: Create a
FlutterPlatformViewFactoryclass that instantiates your native view. - Register Factory: Register this factory with a unique
viewIdentifierin yourAppDelegate.swiftorGeneratedPluginRegistrant.m.
This allows Flutter to reference and embed your iOS UI component directly into its widget tree.
Communicating with Native Views
Once a native view is embedded, you'll often need your Flutter app to interact with it, and vice-versa. This communication typically happens using MethodChannels, similar to how Flutter communicates with native code in general.
You can send messages (method calls) from Flutter to the native view controller to update its state or trigger actions. Conversely, the native view can send messages back to Flutter to report events or data changes.
For instance, a native map view could send its current camera position to Flutter, or Flutter could tell it to zoom in.
Quick Check: When to Embed?
You're building a Flutter app and need to integrate a highly optimized 3D rendering engine available only as a native Android/iOS library. Which scenarios best describe when you would use Native UI Integration?
Recap: Native UI Integration
In this lesson, you learned about embedding native Android (AndroidView) and iOS (UiKitView) views within your Flutter application. This technique is invaluable for integrating highly specialized or performance-critical platform-specific UI components.
Remember to consider native UI integration when Flutter's widgets or existing plugins can't fully meet your needs for complex native UI functionality. It's a powerful way to extend your Flutter app's capabilities by bridging to the native platform.
Questions Fréquemment Posées
La leçon « Intégration de l’interface native » est-elle gratuite ?
Oui — le texte complet de « Intégration de l’interface native » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Flutter Mobile Development, passe à CoddyKit PRO. Le cours Flutter Mobile Development comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Intégration de l’interface native » ?
Explorez les techniques permettant d’intégrer des vues natives de la plateforme dans l’arborescence de vos widgets Flutter afin de créer des expériences utilisateur hautement personnalisées. Tu pratiques Flutter Mobile Development avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Flutter Mobile Development ?
Aucune expérience préalable n'est requise. Flutter Mobile Development sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Intégration de l’interface native » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Flutter Mobile Development ?
Oui. Chaque leçon Flutter Mobile Development inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Canaux de plateforme (MethodChannel)
- Géolocalisation et plugins d’appareil photo
- Intégration de l’interface native
- Autorisations et capteurs