Sub topic 6
Passing initial data with creation parameters
This chapter assumes you can write a basic Flutter StatelessWidget and StatefulWidget. It also assumes you have used a MethodChannel and can read simple Kotlin and Swift. You should already have a registered view type, an Android PlatformViewFactory and an iOS FlutterPlatformViewFactory from the earlier chapters.
What creation parameters are
A native view often needs data before its first frame. A label needs its text, and a map needs its starting position. A video player needs a URL. Creation parameters carry that data from Dart to the native factory at the moment the native view is built.
Creation parameters are a single value, usually a Map. Dart serializes it with a codec and sends it along with the view type and the view id. The native factory receives the decoded value as its args (Android) or arguments (iOS) parameter. The factory uses it to build the view.
The alternative is to create the view empty and send a message afterwards. That works, but the user can see a flash of an empty view, and you must handle messages that arrive before the native side is ready. Creation parameters avoid both problems because the data is present when the view is constructed.
The data flow
Three pieces must agree for this to work:
- The Dart
creationParamsCodecencodes the value. - The native factory's codec decodes it.
- The Dart code and the native code agree on the shape of the data: key names and value types.
If the codecs differ, decoding fails or produces garbage. If the shape differs, you get nulls or a failed cast.
Sending parameters from Dart
The NativeLabel widget from earlier builds a map and passes it to AndroidView or UiKitView:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeLabel extends StatelessWidget {
const NativeLabel({super.key, required this.text});
final String text;
static const String viewType = 'com.example.app/native_label';
@override
Widget build(BuildContext context) {
final creationParams = <String, dynamic>{'text': text};
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return AndroidView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
case TargetPlatform.iOS:
return UiKitView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
default:
return const Text('Native view is not supported on this platform');
}
}
}Two properties matter here:
creationParamsis typed asdynamic. Dart does not check it against anything on the native side.creationParamsCodecis required whenevercreationParamsis not null. Leave it out and Flutter throws an assertion error in debug mode.
Choosing and matching a codec
StandardMessageCodec is the codec used by default for platform channels. It handles null, booleans, numbers, strings, byte arrays, lists and maps. For most platform views it is the right choice.
The table shows how Dart values arrive on each platform.
| Dart type | Kotlin type | Swift type |
|---|---|---|
| `null` | `null` | `nil` (as `NSNull` inside collections) |
| `bool` | `Boolean` | `NSNumber` (bool) |
| `int` | `Int` or `Long` | `NSNumber` (integer) |
| `double` | `Double` | `NSNumber` (double) |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` |
| `List` | `ArrayList` | `Array` |
| `Map` | `HashMap` | `Dictionary` |
The int row is a common source of bugs. On Android, a Dart int arrives as an Int if it fits in 32 bits and as a Long if it does not. A cast such as params["count"] as Long throws a ClassCastException when the value is small. Read numbers through Number instead:
val count = (params?.get("count") as? Number)?.toInt() ?: 0On the native side, the factory declares which codec to use. In Kotlin you pass it to the PlatformViewFactory constructor. In Swift you return it from createArgsCodec(). Both examples below use the standard codec, which matches the Dart side:
class NativeLabelFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val params = args as? Map<*, *>
val text = params?.get("text") as? String ?: ""
return NativeLabel(context, text)
}
}func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}If you pass null for the codec on Android, the factory receives null as args, whatever Dart sent. On Android, pass a codec in the constructor whenever you expect parameters.
Reading parameters safely on Android
The args value is typed Any?. Treat it as untrusted input. Check its type, supply defaults, and avoid unchecked casts.
class NativeLabelFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val params = args as? Map<*, *>
val text = params?.get("text") as? String ?: ""
return NativeLabel(context, text)
}
}The as? operator returns null instead of throwing when the type is wrong. The elvis operator ?: then supplies a default. A view with an empty label is a visible, debuggable result. A crash in the factory takes down the whole screen.
The context parameter deserves a note. It is the context the view should use for construction. Use it for views, resources and themes rather than reaching for the application context.
Reading parameters safely on iOS
The iOS factory receives arguments as Any?. The Swift version casts it to a dictionary and then extracts each key:
init(frame: CGRect, arguments args: Any?) {
label = UILabel(frame: frame)
if let params = args as? [String: Any], let text = params["text"] as? String {
label.text = text
}
label.font = UIFont.systemFont(ofSize: 20)
super.init()
}Notice that all stored properties are initialized before super.init(). The if let chain skips the assignment when the cast fails, which leaves the label empty.
Numbers need the same care as on Android. A value that Dart sent as int arrives as NSNumber, so as? Int usually works, but as? Double on an integer-valued NSNumber can also succeed. Convert explicitly when the distinction matters:
let size = (params["fontSize"] as? NSNumber)?.doubleValue ?? 20.0Sending richer data
A single string is the smallest useful example. Real views need several values, some optional. Build a map with a stable set of keys:
final creationParams = <String, dynamic>{
'text': text,
'fontSize': 18.0,
'bold': true,
'colors': <int>[0xFF112233, 0xFF445566],
};Here is the matching Kotlin read:
val params = args as? Map<*, *>
val text = params?.get("text") as? String ?: ""
val fontSize = (params?.get("fontSize") as? Number)?.toFloat() ?: 20f
val bold = params?.get("bold") as? Boolean ?: false
val colors = (params?.get("colors") as? List<*>)
?.mapNotNull { (it as? Number)?.toLong() }
?: emptyList()The colors illustrate a trap. The value 0xFF112233 is larger than the signed 32-bit maximum of 2,147,483,647. It arrives as a Long, not an Int. If you read it as Number and call toLong(), both cases work.
Keep these rules in mind:
- Send only types the standard codec supports. A Dart
ColororDurationobject is not supported. Convert it to anintbefore you send it. - Use the same key names on all platforms, and define them as constants in Dart so a typo shows up at one place.
- Keep the payload small. It is encoded and copied once, but it is not meant for large binary data such as images. For that, pass a file path or URL and let the native side load it.
Creation parameters are read once
The most common misunderstanding is expecting parameters to update. They do not. The factory runs once for each native view. If the Dart widget rebuilds with a new text value, Flutter does not call the factory again. The native view keeps its old state.
For example, suppose a parent calls setState and now builds NativeLabel(text: 'Second'). The widget tree updates, but the native TextView still shows 'First'. Flutter treats the platform view as the same element because the type and key match.
You have two options:
- Recreate the view. Give the widget a
ValueKeyderived from the data. When the key changes, Flutter disposes the old view and builds a new one, which calls the factory again with the new parameters. This is simple. It is also expensive, and the native view loses any internal state such as scroll position or playback progress. - Send a message. Open a per-view
MethodChanneland call a method such assetText. This updates the existing view. The next chapter covers it in depth.
Here is the recreate approach:
NativeLabel(
key: ValueKey(text),
text: text,
)Use recreation for values that really define the view's identity, such as a map's API key or a camera's lens. Use messages for values that change often, such as text or a zoom level.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Android factory receives `null` for `args` | The factory was built with a `null` codec, or Dart passed no `creationParams` | Pass `StandardMessageCodec.INSTANCE` to the factory constructor and check the Dart widget |
| Assertion error about `creationParamsCodec` | `creationParams` is set but the codec is missing | Add `creationParamsCodec: const StandardMessageCodec()` |
| `ClassCastException` on Android | A Dart `int` was cast to `Long` or `Int` directly | Read as `Number` and convert |
| Text never changes after rebuild | The factory runs only once for each view | Use a key to recreate the view, or send a message |
| Value is missing on one platform | Key names differ between Kotlin and Swift | Share the key names through a Dart constant and compare the native code |
| Crash while decoding on iOS | Dart and native codecs do not match | Return the same codec from `createArgsCodec()` |
Testing the parameters
A quick way to check the contract is to log what the factory receives. On Android:
import android.util.Log
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
Log.d("NativeLabelFactory", "viewId=$viewId args=$args")
val params = args as? Map<*, *>
val text = params?.get("text") as? String ?: ""
return NativeLabel(context, text)
}Run the app, open the screen, and read the log output with flutter logs or Logcat. You should see the map with the keys you sent. On iOS, use print("viewId=\(viewId) args=\(String(describing: args))") in the same place and read it in Xcode's console.
The viewId is worth noting. Each view instance has its own id, and the next chapter uses it to name the per-view channel. A screen that shows three native views causes three factory calls with three ids, and each call can receive different parameters.
Summary of the contract
- Dart sets
creationParamsandcreationParamsCodeconAndroidVieworUiKitView. - The native factory declares the matching codec.
- The factory decodes
argsdefensively and builds the view from the result. - Parameters are applied once. Later changes need a new key or a message.
Exercise
A Dart widget sends {'count': 3} as creation parameters. The Android factory contains val count = params["count"] as Long and crashes with a ClassCastException. Why does it crash, and how do you fix it?
Show answer
The standard codec decodes a Dart int as a Kotlin Int when the value fits in 32 bits, so 3 arrives as an Int and the cast to Long fails. Read it as a Number and convert: val count = (params["count"] as? Number)?.toInt() ?: 0. This works for both Int and Long values.
Exercise
Your screen builds NativeLabel(text: title). After the user edits title, the native label still shows the old text. Give two ways to make it show the new text, and say when you would prefer each.
Show answer
First, add key: ValueKey(title) so Flutter disposes the old view and calls the factory again with the new parameters. Prefer this when the change is rare or defines the view's identity, and when losing the view's internal state is acceptable. Second, open a per-view MethodChannel named with the view id and call a method such as setText. Prefer this when the value changes often or the view has state you must keep.