id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
8ebcffba73da-20 | flutterEngine
dartExecutor
binaryMessenger
CHANNEL
).
setMethodCallHandler
// This method is invoked on the main thread.
call
result
>
if
call
method
==
"getBatteryLevel"
val
batteryLevel
getBatteryLevel
()
if
batteryLevel
!=
result
success
batteryLevel
else
result
error
"UNAVAILABLE"
"Battery level not available."
null
else
result
notImplemented | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-21 | else
result
notImplemented
()
Start by opening the Android host portion of your Flutter app
in Android Studio:
Start Android Studio
Select the menu item File > Open…
Navigate to the directory holding your Flutter app,
and select the android folder inside it. Click OK.
Open the MainActivity.java file located in the java folder in the
Project view.
Next, create a MethodChannel and set a MethodCallHandler
inside the configureFlutterEngine() method.
Make sure to use the same channel name as was used on the
Flutter client side.
import
androidx.annotation.NonNull
import
io.flutter.embedding.android.FlutterActivity
import
io.flutter.embedding.engine.FlutterEngine
import
io.flutter.plugin.common.MethodChannel | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-22 | import
io.flutter.plugin.common.MethodChannel
public
class
MainActivity
extends
FlutterActivity
private
static
final
String
CHANNEL
"samples.flutter.dev/battery"
@Override
public
void
configureFlutterEngine
@NonNull
FlutterEngine
flutterEngine
super
configureFlutterEngine
flutterEngine
);
new
MethodChannel
flutterEngine
getDartExecutor
().
getBinaryMessenger
(),
CHANNEL
setMethodCallHandler | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-23 | CHANNEL
setMethodCallHandler
call
result
>
// This method is invoked on the main thread.
// TODO
);
Add the Android Java code that uses the Android battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native Android app.
First, add the needed imports at the top of the file:
import
android.content.ContextWrapper
import
android.content.Intent
import
android.content.IntentFilter
import
android.os.BatteryManager
import
android.os.Build.VERSION
import
android.os.Build.VERSION_CODES
import
android.os.Bundle | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-24 | import
android.os.Bundle
Then add the following as a new method in the activity class,
below the configureFlutterEngine() method:
private
int
getBatteryLevel
()
int
batteryLevel
if
VERSION
SDK_INT
>=
VERSION_CODES
LOLLIPOP
BatteryManager
batteryManager
BatteryManager
getSystemService
BATTERY_SERVICE
);
batteryLevel
batteryManager
getIntProperty
BatteryManager
BATTERY_PROPERTY_CAPACITY
);
else
Intent | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-25 | );
else
Intent
intent
new
ContextWrapper
getApplicationContext
()).
registerReceiver
null
new
IntentFilter
Intent
ACTION_BATTERY_CHANGED
));
batteryLevel
intent
getIntExtra
BatteryManager
EXTRA_LEVEL
100
intent
getIntExtra
BatteryManager
EXTRA_SCALE
);
return
batteryLevel | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-26 | );
return
batteryLevel
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. The implementation of
this platform method calls the Android code written
in the previous step, and returns a response for both
the success and error cases using the result argument.
If an unknown method is called, report that instead.
Remove the following code:
call
result
>
// This method is invoked on the main thread.
// TODO
And replace with the following:
call
result
>
// This method is invoked on the main thread.
if
call
method
equals
"getBatteryLevel"
))
int | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-27 | ))
int
batteryLevel
getBatteryLevel
();
if
batteryLevel
!=
result
success
batteryLevel
);
else
result
error
"UNAVAILABLE"
"Battery level not available."
null
);
else
result
notImplemented
();
You should now be able to run the app on Android. If using the Android
Emulator, set the battery level in the Extended Controls panel
accessible from the … button in the toolbar.
Step 4: Add an iOS platform-specific implementation
Swift
Objective-C | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-28 | Swift
Objective-C
Start by opening the iOS host portion of your Flutter app in Xcode:
Start Xcode.
Select the menu item File > Open….
Navigate to the directory holding your Flutter app, and select the ios
folder inside it. Click OK.
Add support for Swift in the standard template setup that uses Objective-C:
Expand Runner > Runner in the Project navigator.
Open the file AppDelegate.swift located under Runner > Runner
in the Project navigator.
Override the application:didFinishLaunchingWithOptions: function and create
a FlutterMethodChannel tied to the channel name
samples.flutter.dev/battery:
@UIApplicationMain
@objc
class
AppDelegate
FlutterAppDelegate
override
func
application | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-29 | override
func
application
application
UIApplication
didFinishLaunchingWithOptions
launchOptions
UIApplication
LaunchOptionsKey
Any
]?)
>
Bool
let
controller
FlutterViewController
window
rootViewController
as!
FlutterViewController
let
batteryChannel
FlutterMethodChannel
name
"samples.flutter.dev/battery"
binaryMessenger
controller
binaryMessenger
batteryChannel
setMethodCallHandler
({
call
FlutterMethodCall
result | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-30 | call
FlutterMethodCall
result
@escaping
FlutterResult
>
Void
in
// This method is invoked on the UI thread.
// Handle battery messages.
})
GeneratedPluginRegistrant
register
with
self
return
super
application
application
didFinishLaunchingWithOptions
launchOptions
Next, add the iOS Swift code that uses the iOS battery APIs to retrieve
the battery level. This code is exactly the same as you
would write in a native iOS app.
Add the following as a new method at the bottom of AppDelegate.swift:
private
func
receiveBatteryLevel
result | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-31 | func
receiveBatteryLevel
result
FlutterResult
let
device
UIDevice
current
device
isBatteryMonitoringEnabled
true
if
device
batteryState
==
UIDevice
BatteryState
unknown
result
FlutterError
code
"UNAVAILABLE"
message
"Battery level not available."
details
nil
))
else
result
Int
device
batteryLevel
100
)) | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-32 | batteryLevel
100
))
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
The implementation of this platform method calls
the iOS code written in the previous step. If an unknown method
is called, report that instead.
batteryChannel
setMethodCallHandler
({
weak
self
call
FlutterMethodCall
result
FlutterResult
>
Void
in
// This method is invoked on the UI thread.
guard
call
method
==
"getBatteryLevel"
else
result
FlutterMethodNotImplemented | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-33 | else
result
FlutterMethodNotImplemented
return
self
receiveBatteryLevel
result
result
})
Start by opening the iOS host portion of the Flutter app in Xcode:
Start Xcode.
Select the menu item File > Open….
Navigate to the directory holding your Flutter app,
and select the ios folder inside it. Click OK.
Make sure the Xcode projects builds without errors.
Open the file AppDelegate.m, located under Runner > Runner
in the Project navigator.
Create a FlutterMethodChannel and add a handler inside the application
didFinishLaunchingWithOptions: method.
Make sure to use the same channel name
as was used on the Flutter client side.
#import <Flutter/Flutter.h>
#import "GeneratedPluginRegistrant.h" | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-34 | @implementation
AppDelegate
BOOL
application
:(
UIApplication
application
didFinishLaunchingWithOptions
:(
NSDictionary
launchOptions
FlutterViewController
controller
FlutterViewController
self
window
rootViewController
FlutterMethodChannel
batteryChannel
FlutterMethodChannel
methodChannelWithName:
@"samples.flutter.dev/battery"
binaryMessenger:
controller
binaryMessenger
];
batteryChannel
setMethodCallHandler
FlutterMethodCall
call
FlutterResult
result | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-35 | call
FlutterResult
result
// This method is invoked on the UI thread.
// TODO
}];
GeneratedPluginRegistrant
registerWithRegistry
self
];
return
super
application
application
didFinishLaunchingWithOptions
launchOptions
];
Next, add the iOS ObjectiveC code that uses the iOS battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native iOS app.
Add the following method in the AppDelegate class, just before @end: | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-36 | Add the following method in the AppDelegate class, just before @end:
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. The implementation of
this platform method calls the iOS code written in the previous step,
and returns a response for both the success and error cases using
the result argument. If an unknown method is called, report that instead.
int
getBatteryLevel
UIDevice
device
UIDevice
currentDevice
device
batteryMonitoringEnabled
YES
if
device
batteryState
==
UIDeviceBatteryStateUnknown
return
else
return
int
)( | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-37 | return
int
)(
device
batteryLevel
100
);
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. The implementation of
this platform method calls the iOS code written in the previous step,
and returns a response for both the success and error cases using
the result argument. If an unknown method is called, report that instead.
__weak
typeof
self
weakSelf
self
batteryChannel
setMethodCallHandler
FlutterMethodCall
call
FlutterResult
result
// This method is invoked on the UI thread.
if
([
@"getBatteryLevel" | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-38 | if
([
@"getBatteryLevel"
isEqualToString
call
method
])
int
batteryLevel
weakSelf
getBatteryLevel
];
if
batteryLevel
==
result
([
FlutterError
errorWithCode
@"UNAVAILABLE"
message:
@"Battery level not available."
details:
nil
]);
else
result
batteryLevel
));
else
result
FlutterMethodNotImplemented
);
}]; | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-39 | );
}];
You should now be able to run the app on iOS.
If using the iOS Simulator,
note that it doesn’t support battery APIs,
and the app displays ‘Battery level not available’.
Step 5: Add a Windows platform-specific implementation
Start by opening the Windows host portion of your Flutter app in Visual Studio:
Run flutter build windows in your project directory once to generate
the Visual Studio solution file.
Start Visual Studio.
Select Open a project or solution.
Navigate to the directory holding your Flutter app, then into the build
folder, then the windows folder, then select the batterylevel.sln file.
Click Open.
Add the C++ implementation of the platform channel method:
Expand batterylevel > Source Files in the Solution Explorer.
Open the file flutter_window.cpp. | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-40 | Open the file flutter_window.cpp.
First, add the necessary includes to the top of the file, just
after #include "flutter_window.h":
#include
<flutter/event_channel.h>
#include
<flutter/event_sink.h>
#include
<flutter/event_stream_handler_functions.h>
#include
<flutter/method_channel.h>
#include
<flutter/standard_method_codec.h>
#include
<windows.h>
#include
<memory>
Edit the FlutterWindow::OnCreate method and create
a flutter::MethodChannel tied to the channel name
samples.flutter.dev/battery:
bool
FlutterWindow
::
OnCreate | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-41 | FlutterWindow
::
OnCreate
()
// ...
RegisterPlugins
flutter_controller_
>
engine
());
flutter
::
MethodChannel
<>
channel
flutter_controller_
>
engine
()
>
messenger
(),
"samples.flutter.dev/battery"
flutter
::
StandardMethodCodec
::
GetInstance
());
channel
SetMethodCallHandler
[](
const
flutter
::
MethodCall | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-42 | flutter
::
MethodCall
<>&
call
std
::
unique_ptr
flutter
::
MethodResult
<>>
result
// TODO
});
SetChildContent
flutter_controller_
>
view
()
>
GetNativeWindow
());
return
true
Next, add the C++ code that uses the Windows battery APIs to
retrieve the battery level. This code is exactly the same as
you would write in a native Windows application.
Add the following as a new function at the top of
flutter_window.cpp just after the #include section:
static
int | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-43 | static
int
GetBatteryLevel
()
SYSTEM_POWER_STATUS
status
if
GetSystemPowerStatus
status
==
||
status
BatteryLifePercent
==
255
return
return
status
BatteryLifePercent
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
The implementation of this platform method calls
the Windows code written in the previous step. If an unknown method
is called, report that instead.
Remove the following code:
channel
SetMethodCallHandler
[](
const | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-44 | SetMethodCallHandler
[](
const
flutter
::
MethodCall
<>&
call
std
::
unique_ptr
flutter
::
MethodResult
<>>
result
// TODO
});
And replace with the following:
channel
SetMethodCallHandler
[](
const
flutter
::
MethodCall
<>&
call
std
::
unique_ptr
flutter
::
MethodResult
<>>
result
if
call | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-45 | result
if
call
method_name
()
==
"getBatteryLevel"
int
battery_level
GetBatteryLevel
();
if
battery_level
!=
result
>
Success
battery_level
);
else
result
>
Error
"UNAVAILABLE"
"Battery level not available."
);
else
result
>
NotImplemented
();
}); | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-46 | NotImplemented
();
});
You should now be able to run the application on Windows.
If your device doesn’t have a battery,
it displays ‘Battery level not available’.
Step 6: Add a Linux platform-specific implementation
For this example you need to install the upower developer headers.
This is likely available from your distribution, for example with:
sudo apt
install libupower-glib-dev
Start by opening the Linux host portion of your Flutter app in the editor
of your choice. The instructions below are for Visual Studio Code with the
“C/C++” and “CMake” extensions installed, but can be adjusted for other IDEs.
Launch Visual Studio Code.
Open the linux directory inside your project.
Choose Yes in the prompt asking: Would you like to configure project "linux"?.
This enables C++ autocomplete. | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-47 | Open the file my_application.cc.
First, add the necessary includes to the top of the file, just
after #include <flutter_linux/flutter_linux.h:
#include
<math.h>
#include
<upower.h>
Add an FlMethodChannel to the _MyApplication struct:
struct
_MyApplication
GtkApplication
parent_instance
char
*
dart_entrypoint_arguments
FlMethodChannel
battery_channel
};
Make sure to clean it up in my_application_dispose:
static
void
my_application_dispose
GObject
object
MyApplication
self
MY_APPLICATION | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-48 | MyApplication
self
MY_APPLICATION
object
);
g_clear_pointer
self
>
dart_entrypoint_arguments
g_strfreev
);
g_clear_object
self
>
battery_channel
);
G_OBJECT_CLASS
my_application_parent_class
>
dispose
object
);
Edit the my_application_activate method and initialize
battery_channel using the channel name
samples.flutter.dev/battery, just after the call to
fl_register_plugins:
static
void
my_application_activate
GApplication
application | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-49 | my_application_activate
GApplication
application
// ...
fl_register_plugins
FL_PLUGIN_REGISTRY
self
>
view
));
g_autoptr
FlStandardMethodCodec
codec
fl_standard_method_codec_new
();
self
>
battery_channel
fl_method_channel_new
fl_engine_get_binary_messenger
fl_view_get_engine
view
)),
"samples.flutter.dev/battery"
FL_METHOD_CODEC
codec
)); | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-50 | codec
));
fl_method_channel_set_method_call_handler
self
>
battery_channel
battery_method_call_handler
self
nullptr
);
gtk_widget_grab_focus
GTK_WIDGET
self
>
view
));
Next, add the C code that uses the Linux battery APIs to
retrieve the battery level. This code is exactly the same as
you would write in a native Linux application.
Add the following as a new function at the top of
my_application.cc just after the G_DEFINE_TYPE line:
static
FlMethodResponse
get_battery_level
() | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-51 | get_battery_level
()
// Find the first available battery and report that.
g_autoptr
UpClient
up_client
up_client_new
();
g_autoptr
GPtrArray
devices
up_client_get_devices2
up_client
);
if
devices
>
len
==
return
FL_METHOD_RESPONSE
fl_method_error_response_new
"UNAVAILABLE"
"Device does not have a battery."
nullptr
));
UpDevice
device
UpDevice | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-52 | UpDevice
device
UpDevice
)(
g_ptr_array_index
devices
));
double
percentage
g_object_get
device
"percentage"
percentage
nullptr
);
g_autoptr
FlValue
result
fl_value_new_int
static_cast
int64_t
round
percentage
)));
return
FL_METHOD_RESPONSE
fl_method_success_response_new
result
)); | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-53 | result
));
Finally, add the battery_method_call_handler function referenced
in the earlier call to fl_method_channel_set_method_call_handler.
You need to handle a single platform method, getBatteryLevel,
so test for that in the method_call argument.
The implementation of this function calls
the Linux code written in the previous step. If an unknown method
is called, report that instead.
Add the following code after the get_battery_level function:
static
void
battery_method_call_handler
FlMethodChannel
channel
FlMethodCall
method_call
gpointer
user_data
g_autoptr
FlMethodResponse
response
nullptr
if
strcmp | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-54 | nullptr
if
strcmp
fl_method_call_get_name
method_call
),
"getBatteryLevel"
==
response
get_battery_level
();
else
response
FL_METHOD_RESPONSE
fl_method_not_implemented_response_new
());
g_autoptr
GError
error
nullptr
if
fl_method_call_respond
method_call
response
error
))
g_warning
"Failed to send response: %s"
error
> | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-55 | error
>
message
);
You should now be able to run the application on Linux.
If your device doesn’t have a battery,
it displays ‘Battery level not available’.
Typesafe platform channels using Pigeon
The previous example uses MethodChannel
to communicate between the host and client,
which isn’t typesafe. Calling and receiving
messages depends on the host and client declaring
the same arguments and datatypes in order for messages to work.
You can use the Pigeon package as
an alternative to MethodChannel
to generate code that sends messages in a
structured, typesafe manner.
With Pigeon, the messaging protocol is defined
in a subset of Dart that then generates messaging
code for Android or iOS. You can find a more complete
example and more information on the pigeon
page on pub.dev. | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-56 | Using Pigeon eliminates the need to match
strings between host and client
for the names and datatypes of messages.
It supports: nested classes, grouping
messages into APIs, generation of
asynchronous wrapper code and sending messages
in either direction. The generated code is readable
and guarantees there are no conflicts between
multiple clients of different versions.
Supported languages are Objective-C, Java, Kotlin,
and Swift (with Objective-C interop).
Pigeon example
Pigeon file:
Dart usage:
Separate platform-specific code from UI code
If you expect to use your platform-specific code
in multiple Flutter apps, you might consider
separating the code into a platform plugin located
in a directory outside your main application.
See developing packages for details.
Publish platform-specific code as a package
To share your platform-specific code with other developers
in the Flutter ecosystem, see publishing packages.
Custom channels and codecs | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-57 | Custom channels and codecs
Besides the above mentioned MethodChannel,
you can also use the more basic
BasicMessageChannel, which supports basic,
asynchronous message passing using a custom message codec.
You can also use the specialized BinaryCodec,
StringCodec, and JSONMessageCodec
classes, or create your own codec.
You might also check out an example of a custom codec
in the cloud_firestore plugin,
which is able to serialize and deserialize many more
types than the default types.
Channels and platform threading | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-58 | Channels and platform threading
When invoking channels on the platform side destined for Flutter,
invoke them on the platform’s main thread.
When invoking channels in Flutter destined for the platform side,
either invoke them from any Isolate that is the root
Isolate, or that is registered as a background Isolate.
The handlers for the platform side can execute on the platform’s main thread
or they can execute on a background thread if using a Task Queue.
You can invoke the platform side handlers asynchronously
and on any thread when the Task Queue API is available;
otherwise, they must be invoked on the platform thread.
Note:
On Android, the platform’s main thread is sometimes
called the “main thread”, but it is technically defined
as the UI thread. Annotate methods that need
to be run on the UI thread with @UiThread.
On iOS, this thread is officially
referred to as the main thread.
Using plugins and channels from background isolates | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-59 | Using plugins and channels from background isolates
Plugins and channels can be used by any Isolate, but that Isolate has to be
a root Isolate (the one created by Flutter) or registered as a background
Isolate for a root Isolate.
The following example shows how to register a background Isolate in order to
use a plugin from a background Isolate.
import
'package:flutter/services.dart'
import
'package:shared_preferences/shared_preferences.dart'
void
_isolateMain
RootIsolateToken
rootIsolateToken
async
BackgroundIsolateBinaryMessenger
ensureInitialized
rootIsolateToken
);
SharedPreferences
sharedPreferences
await
SharedPreferences
getInstance | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-60 | await
SharedPreferences
getInstance
();
print
sharedPreferences
getBool
'isDebug'
));
void
main
()
RootIsolateToken
rootIsolateToken
RootIsolateToken
instance
Isolate
spawn
_isolateMain
rootIsolateToken
);
Executing channel handlers on background threads
In order for a channel’s platform side handler to
execute on a background thread, you must use the
Task Queue API. Currently this feature is only
supported on iOS and Android.
In Java:
@Override
public
void
onAttachedToEngine | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-61 | public
void
onAttachedToEngine
@NonNull
FlutterPluginBinding
binding
BinaryMessenger
messenger
binding
getBinaryMessenger
();
BinaryMessenger
TaskQueue
taskQueue
messenger
makeBackgroundTaskQueue
();
channel
new
MethodChannel
messenger
"com.example.foo"
StandardMethodCodec
INSTANCE
taskQueue
);
channel
setMethodCallHandler
this
);
In Kotlin:
override
fun
onAttachedToEngine | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-62 | override
fun
onAttachedToEngine
@NonNull
flutterPluginBinding
FlutterPlugin
FlutterPluginBinding
val
taskQueue
flutterPluginBinding
binaryMessenger
makeBackgroundTaskQueue
()
channel
MethodChannel
flutterPluginBinding
binaryMessenger
"com.example.foo"
StandardMethodCodec
INSTANCE
taskQueue
channel
setMethodCallHandler
this
In Swift:
Note:
In release 2.10, the Task Queue API is only available on the master channel
for iOS.
public
static
func
register | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-63 | public
static
func
register
with
registrar
FlutterPluginRegistrar
let
taskQueue
registrar
messenger
makeBackgroundTaskQueue
()
let
channel
FlutterMethodChannel
name
"com.example.foo"
binaryMessenger
registrar
messenger
(),
codec
FlutterStandardMethodCodec
sharedInstance
taskQueue
taskQueue
let
instance
MyPlugin
()
registrar
addMethodCallDelegate
instance
channel | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-64 | addMethodCallDelegate
instance
channel
channel
In Objective-C:
Note:
In release 2.10, the Task Queue API is only available on the master channel
for iOS.
void
registerWithRegistrar
:(
NSObject
FlutterPluginRegistrar
>*
registrar
NSObject
FlutterTaskQueue
>*
taskQueue
[[
registrar
messenger
makeBackgroundTaskQueue
];
FlutterMethodChannel
channel
FlutterMethodChannel
methodChannelWithName
@"com.example.foo"
binaryMessenger:
registrar | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-65 | binaryMessenger:
registrar
messenger
codec:
FlutterStandardMethodCodec
sharedInstance
taskQueue:
taskQueue
];
MyPlugin
instance
[[
MyPlugin
alloc
init
];
registrar
addMethodCallDelegate
instance
channel
channel
];
Jumping to the UI thread in Android
To comply with channels’ UI thread requirement,
you might need to jump from a background thread
to Android’s UI thread to execute a channel method.
In Android, you can accomplish this by post()ing a
Runnable to Android’s UI thread Looper,
which causes the Runnable to execute on the
main thread at the next opportunity. | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-66 | In Java:
new
Handler
Looper
getMainLooper
()).
post
new
Runnable
()
@Override
public
void
run
()
// Call the desired channel message here.
});
In Kotlin:
Handler
Looper
getMainLooper
()).
post
// Call the desired channel message here.
Jumping to the main thread in iOS
To comply with channel’s main thread requirement,
you might need to jump from a background thread to
iOS’s main thread to execute a channel method.
You can accomplish this in iOS by executing a
block on the main dispatch queue: | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
8ebcffba73da-67 | In Objective-C:
dispatch_async
dispatch_get_main_queue
(),
// Call the desired channel message here.
});
In Swift:
DispatchQueue
main
async
// Call the desired channel message here. | https://docs.flutter.dev/development/platform-integration/platform-channels/index.html |
fbec2d782ebb-0 | Building a web application with Flutter
Platform integration
Web
Web development
Requirements
Create a new project with web support
Set up
Create and run
IDE
Command line
Build
Add web support to an existing app
This page covers the following steps for getting started with web support:
Configure the flutter tool for web support.
Create a new project with web support.
Run a new project with web support.
Build an app with web support.
Add web support to an existing project.
Requirements
To create a Flutter app with web support,
you need the following software:
Flutter SDK. See the
Flutter SDK installation instructions.
Chrome; debugging a web app requires
the Chrome browser. | https://docs.flutter.dev/development/platform-integration/web/building/index.html |
fbec2d782ebb-1 | Chrome; debugging a web app requires
the Chrome browser.
Optional: An IDE that supports Flutter.
You can install Visual Studio Code,
Android Studio, IntelliJ IDEA.
Also install the Flutter and Dart plugins
to enable language support and tools for refactoring,
running, debugging, and reloading your web app
within an editor. See setting up an editor
for more details.
For more information, see the web FAQ.
Create a new project with web support
You can use the following steps
to create a new project with web support.
Set up
Run the following commands to use the latest version of the Flutter SDK:
flutter channel stable
flutter upgrade
If Chrome is installed,
the flutter devices command outputs a Chrome device
that opens the Chrome browser with your app running,
and a Web Server that provides the URL serving the app.
flutter devices
1 connected device: | https://docs.flutter.dev/development/platform-integration/web/building/index.html |
fbec2d782ebb-2 | flutter devices
1 connected device:
Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150
In your IDE, you should see Chrome (web) in the device pulldown.
Create and run
Creating a new project with web support is no different
than creating a new Flutter project for other platforms.
IDE
Create a new app in your IDE and it automatically
creates iOS, Android, desktop, and web versions of your app.
From the device pulldown, select Chrome (web)
and run your app to see it launch in Chrome.
Command line
To create a new app that includes web support
(in addition to mobile support), run the following commands,
substituting my_app with the name of your project:
flutter create my_app
cd my_app | https://docs.flutter.dev/development/platform-integration/web/building/index.html |
fbec2d782ebb-3 | flutter create my_app
cd my_app
To serve your app from localhost in Chrome,
enter the following from the top of the package:
flutter run
d chrome
Note:
If there aren’t any other connected devices,
the -d chrome is optional.
The flutter run command launches the application using the
development compiler in a Chrome browser.
Warning:
Hot reload is not supported in a web browser
Currently, Flutter supports hot restart,
but not hot reload in a web browser.
Build
Run the following command to generate a release build:
flutter build web
dart2js
(instead of the
development compiler)
to produce a single JavaScript file | https://docs.flutter.dev/development/platform-integration/web/building/index.html |
fbec2d782ebb-4 | development compiler)
to produce a single JavaScript file
You can also include --web-renderer html or --web-renderer canvaskit to
select between the HTML or CanvasKit renderers, respectively. For more
information, see Web renderers.
For more information, see
Build and release a web app.
Add web support to an existing app
To add web support to an existing project
created using a previous version of Flutter,
run the following command
from your project’s top-level directory:
flutter create
-platforms web | https://docs.flutter.dev/development/platform-integration/web/building/index.html |
a3c8a352c7f2-0 | Web FAQ
Platform integration
Web
Web FAQ
What scenarios are ideal for Flutter on the web?
Search Engine Optimization (SEO)
How do I create an app that also runs on the web?
Does hot reload work with a web app?
How do I restart the app running in the browser?
Which web browsers are supported by Flutter?
Can I build, run, and deploy web apps in any of the IDEs?
How do I build a responsive app for the web?
Can I use dart:io with a web app?
How do I handle web-specific imports?
Does Flutter web support concurrency?
How do I embed a Flutter web app in a web page?
How do I debug a web app?
How do I test a web app? | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-1 | How do I test a web app?
How do I deploy a web app?
Does Platform.is work on the web?
What scenarios are ideal for Flutter on the web?
Not every web page makes sense in Flutter, but we think Flutter is particularly
suited for app-centric experiences:
Progressive Web Apps
Single Page Apps
Existing Flutter mobile apps
At this time, Flutter is not suitable for static websites with text-rich
flow-based content. For example, blog articles benefit from the document-centric
model that the web is built around, rather than the app-centric services that a
UI framework like Flutter can deliver. However, you can use Flutter to embed
interactive experiences into these websites.
For more information on how you can use Flutter on the web,
see Web support for Flutter.
Search Engine Optimization (SEO) | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-2 | Search Engine Optimization (SEO)
In general, Flutter is geared towards dynamic application experiences. Flutter’s
web support is no exception. Flutter web prioritizes performance, fidelity, and
consistency. This means application output does not align with what search
engines need to properly index. For web content that is static or document-like,
we recommend using HTML—just like we do on flutter.dev,
dart.dev, and pub.dev. You should also
consider separating your primary application experience—created in Flutter—from
your landing page, marketing content, and help content—created using
search-engine optimized HTML.
How do I create an app that also runs on the web?
See building a web app with Flutter.
Does hot reload work with a web app? | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-3 | Does hot reload work with a web app?
No, but you can use hot restart. Hot restart is a fast way of seeing your
changes without having to relaunch your web app and wait for it to compile and
load. This works similarly to the hot reload feature for Flutter mobile
development. The only difference is that hot reload remembers your state and hot
restart doesn’t.
How do I restart the app running in the browser?
You can either use the browser’s refresh button,
or you can enter “R” in the console where
“flutter run -d chrome” is running.
Which web browsers are supported by Flutter?
Flutter web apps can run on the following browsers:
Chrome (mobile & desktop)
Safari (mobile & desktop)
Edge (mobile & desktop)
Firefox (mobile & desktop) | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-4 | Edge (mobile & desktop)
Firefox (mobile & desktop)
During development, Chrome (on macOS, Windows, and Linux) and Edge (on Windows)
are supported as the default browsers for debugging your app.
Can I build, run, and deploy web apps in any of the IDEs?
You can select Chrome or Edge as the target device in
Android Studio/IntelliJ and VS Code.
The device pulldown should now include the Chrome (web)
option for all channels.
How do I build a responsive app for the web?
See Creating responsive apps.
Can I use dart:io with a web app?
No. The file system is not accessible from the browser.
For network functionality, use the http
package. Note that security works somewhat
differently because the browser (and not the app)
controls the headers on an HTTP request.
How do I handle web-specific imports? | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-5 | How do I handle web-specific imports?
Some plugins require platform-specific imports, particularly if they use the
file system, which is not accessible from the browser. To use these plugins
in your app, see the documentation for conditional imports
on dart.dev.
Does Flutter web support concurrency?
Dart’s concurrency support via isolates
is not currently supported in Flutter web.
Flutter web apps can potentially work around this
by using web workers,
although no such support is built in.
How do I embed a Flutter web app in a web page?
You can embed a Flutter web app,
as you would embed other content,
in an iframe tag of an HTML file.
In the following example, replace “URL”
with the location of your hosted HTML page:
<iframe
src=
"URL"
></iframe>
If you encounter problems, please file an issue. | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
a3c8a352c7f2-6 | ></iframe>
If you encounter problems, please file an issue.
How do I debug a web app?
Use Flutter DevTools for the following tasks:
Debugging
Logging
Running Flutter inspector
Use Chrome DevTools for the following tasks:
Generating event timeline
Analyzing performance—make sure to use a
profile build
How do I test a web app?
Use widget tests or integration tests. To learn more about
running integration tests in a browser, see the Integration testing page.
How do I deploy a web app?
See Preparing a web app for release.
Does Platform.is work on the web?
Not currently. | https://docs.flutter.dev/development/platform-integration/web/faq/index.html |
30461913a3e2-0 | Web support for Flutter
Platform integration
Web
Resources
Flutter’s web support delivers the same experiences on the web as on mobile.
Building on the portability of Dart, the power of the web platform and the
flexibility of the Flutter framework, you can now build apps for iOS, Android,
and the browser from the same codebase. You can compile existing Flutter code
written in Dart into a web experience because it is exactly the same Flutter
framework and web is just another device target for your app. | https://docs.flutter.dev/development/platform-integration/web/index.html |
30461913a3e2-1 | Adding web support to Flutter involved implementing Flutter’s
core drawing layer on top of standard browser APIs, in addition
to compiling Dart to JavaScript, instead of the ARM machine code that
is used for mobile applications. Using a combination of DOM, Canvas,
and WebAssembly, Flutter can provide a portable, high-quality,
and performant user experience across modern browsers.
We implemented the core drawing layer completely in Dart
and used Dart’s optimized JavaScript compiler to compile the
Flutter core and framework along with your application
into a single, minified source file that can be deployed to
any web server.
While you can do a lot on the web,
Flutter’s web support is most valuable in the
following scenarios:
Progressive Web Application built with Flutter
Flutter delivers high-quality PWAs that are integrated with a user’s
environment, including installation, offline support, and tailored UX. | https://docs.flutter.dev/development/platform-integration/web/index.html |
30461913a3e2-2 | Flutter’s web support enables complex standalone web apps that are rich with
graphics and interactive content to reach end users on a wide variety of
devices.
Web support for Flutter provides a browser-based delivery model for existing
Flutter mobile apps.
Not every HTML scenario is ideally suited for Flutter at this time.
For example, text-rich, flow-based, static content such as blog articles
benefit from the document-centric model that the web is built around,
rather than the app-centric services that a UI framework like Flutter
can deliver. However, you can use Flutter to embed interactive
experiences into these websites.
For a glimpse into how to migrate your mobile app to web, see
the following video:
Resources
The following resources can help you get started:
To add web support to an existing app, or to create a
new app that includes web support, see
Building a web application with Flutter. | https://docs.flutter.dev/development/platform-integration/web/index.html |
30461913a3e2-3 | To learn about Flutter’s different web renderers (HTML and CanvasKit), see
Web renderers
To learn how to create a responsive Flutter
app, see Creating responsive apps.
To view commonly asked questions and answers, see the
web FAQ.
To see code examples,
check out the web samples for Flutter.
To see a Flutter web app demo, check out the Flutter Gallery.
To learn about deploying a web app, see
Preparing an app for web release.
File an issue on the main Flutter repo.
You can chat and ask web-related questions on the
#help channel on Discord. | https://docs.flutter.dev/development/platform-integration/web/index.html |
79eac8579107-0 | Customizing web app initialization
Platform integration
Web
Customizing web app initialization
Getting started
Customizing web app initialization
Loading the entrypoint
Initializing the engine
Skipping this step
Example: Display a progress indicator
Upgrading an older project
You can customize how a Flutter app is initialized on the web
using the _flutter.loader JavaScript API provided by flutter.js.
This API can be used to display a loading indicator in CSS,
prevent the app from loading based on a condition,
or wait until the user presses a button before showing the app.
The initialization process is split into the following stages:
Fetches the main.dart.js script and initializes the service worker.
Initializes Flutter’s web engine by downloading required resources
such as assets, fonts, and CanvasKit. | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-1 | Prepares the DOM for your Flutter app and runs it.
This page shows how to customize the behavior
at each stage of the initialization process.
Getting started
By default, the index.html file
generated by the flutter create command
contains a script tag
that calls loadEntrypoint from the flutter.js file:
<html>
<head>
<!-- ... -->
<script
src=
"flutter.js"
defer
></script>
</head>
<body>
<script>
window
addEventListener
load
function
ev
// Download main.dart.js
_flutter
loader
loadEntrypoint
({
serviceWorker | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-2 | loadEntrypoint
({
serviceWorker
serviceWorkerVersion
serviceWorkerVersion
},
onEntrypointLoaded
async
function
engineInitializer
// Initialize the Flutter engine
let
appRunner
await
engineInitializer
initializeEngine
();
// Run the app
await
appRunner
runApp
();
});
});
</script>
</body>
</html>
Note:
In Flutter 2.10 or earlier,
this script doesn’t support customization.
To upgrade your index.html file to the latest version,
see Upgrading an older project. | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-3 | The loadEntrypoint function calls the onEntrypointLoaded callback
once the Service Worker is initialized, and the main.dart.js entrypoint
has been downloaded and run by the browser. Flutter also calls
onEntrypointLoaded on every hot restart during development.
The onEntrypointLoaded callback receives an engine initializer object as
its only parameter. Use the engine initializer to set the run-time
configuration, and start the Flutter Web engine.
The initializeEngine() function returns a Promise
that resolves with an app runner object. The app runner has a
single method, runApp(), that runs the Flutter app.
Customizing web app initialization
In this section,
learn how to customize each stage of your app’s initialization.
Loading the entrypoint
The loadEntrypoint method accepts these parameters:
entrypointUrl
The URL of your Flutter app’s entrypoint. Defaults to "main.dart.js".
String | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-4 | String
onEntrypointLoaded
The function called when the engine is ready to be initialized. Receives an engineInitializer object as its only parameter.
Function
serviceWorker
The configuration for the flutter_service_worker.js loader. (If not set, the service worker won’t be used.)
Object
The serviceWorker JavaScript object accepts the following properties:
serviceWorkerUrl
The URL of the Service Worker JS file. The serviceWorkerVersion is appended to the URL. Defaults to "flutter_service_worker.js?v="
String
serviceWorkerVersion
Pass the serviceWorkerVersion variable set by the build process in your index.html file.
String
timeoutMillis
The timeout value for the service worker load. Defaults to 4000.
Number
Initializing the engine | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-5 | Number
Initializing the engine
As of Flutter 3.7.0, you can use the initializeEngine method to
configure several run-time options of the Flutter web engine through a
JsFlutterConfiguration object.
You can pass in the following (optional) parameters:
canvasKitBaseUrl
The base URL from where canvaskit.wasm is downloaded.
String
canvasKitForceCpuOnly
When true, forces CPU-only rendering in CanvasKit (the engine won’t use WebGL).
bool
canvasKitMaximumSurfaces
The maximum number of overlay surfaces that the CanvasKit renderer can use.
double
debugShowSemanticNodes
If true, Flutter visibly renders the semantics tree onscreen (for debugging).
bool
renderer | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-6 | bool
renderer
Specifies the web renderer for the current Flutter application, either "canvaskit" or "html".
String
Note:
Some of the parameters described above might have been overridden
in previous releases by using properties in the window object.
That approach is still supported, but displays a deprecation
notice in the JS console, as of Flutter 3.7.0.
Skipping this step
Instead of calling initializeEngine() on the engine initializer (and then
runApp() on the application runner), you can call autoStart() to
initialize the engine with its default configuration, and then start the app
immediately after the initialization is complete:
_flutter
loader
loadEntrypoint
({
serviceWorker
serviceWorkerVersion
serviceWorkerVersion
},
onEntrypointLoaded
async | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-7 | },
onEntrypointLoaded
async
function
engineInitializer
await
engineInitializer
autoStart
();
});
Example: Display a progress indicator
To give the user of your application feedback
during the initialization process,
use the hooks provided for each stage to update the DOM:
<html>
<head>
<!-- ... -->
<script
src=
"flutter.js"
defer
></script>
</head>
<body>
<div
id=
"loading"
></div>
<script>
window
addEventListener
load | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-8 | window
addEventListener
load
function
ev
var
loading
document
querySelector
#loading
);
loading
textContent
Loading entrypoint...
_flutter
loader
loadEntrypoint
({
serviceWorker
serviceWorkerVersion
serviceWorkerVersion
},
onEntrypointLoaded
async
function
engineInitializer
loading
textContent
Initializing engine...
let
appRunner
await
engineInitializer
initializeEngine
();
loading
textContent | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
79eac8579107-9 | ();
loading
textContent
Running app...
await
appRunner
runApp
();
});
});
</script>
</body>
</html>
For a more practical example using CSS animations,
see the initialization code for the Flutter Gallery.
Upgrading an older project
If your project was created in Flutter 2.10 or earlier,
you can create a new index.html file
with the latest initialization template by running
flutter create as follows.
First, remove the files from your /web directory.
Then, from your project directory, run the following: | https://docs.flutter.dev/development/platform-integration/web/initialization/index.html |
df06366f8b52-0 | Web renderers
Platform integration
Web
Web renderers
Command line options
Runtime configuration
Choosing which option to use
Examples
When running and building apps for the web, you can choose between two different
renderers. This page describes both renderers and how to choose the best one for
your needs. The two renderers are:
Uses a combination of HTML elements, CSS, Canvas elements, and SVG elements.
This renderer has a smaller download size.
This renderer is fully consistent with Flutter mobile and desktop, has
faster performance with higher widget density, but adds about 2MB in
download size.
Command line options
The --web-renderer command line option takes one of three values, auto,
html, or canvaskit. | https://docs.flutter.dev/development/platform-integration/web/renderers/index.html |
df06366f8b52-1 | auto (default) - automatically chooses which renderer to use. This option
chooses the HTML renderer when the app is running in a mobile browser, and
CanvasKit renderer when the app is running in a desktop browser.
html - always use the HTML renderer
canvaskit - always use the CanvasKit renderer
This flag can be used with the run or build subcommands. For example:
This flag is ignored when a non-browser (mobile or desktop) device
target is selected.
Runtime configuration
To override the web renderer at runtime:
Build the app with the auto option.
Prepare a configuration object with the renderer property set to
"canvaskit" or "html".
Pass that object to the engineInitializer.initializeEngine(configuration);
method on your Flutter Web app initialization.
let
useHtml
// ...
_flutter | https://docs.flutter.dev/development/platform-integration/web/renderers/index.html |
df06366f8b52-2 | useHtml
// ...
_flutter
loader
loadEntrypoint
({
onEntrypointLoaded
async
function
engineInitializer
// Run-time engine configuration
let
config
renderer
useHtml
html
canvaskit
let
appRunner
await
engineInitializer
initializeEngine
config
);
await
appRunner
runApp
();
});
The web renderer can’t be changed after the Flutter engine startup process
begins in main.dart.js.
Customizing web app initialization.
Choosing which option to use | https://docs.flutter.dev/development/platform-integration/web/renderers/index.html |
df06366f8b52-3 | Customizing web app initialization.
Choosing which option to use
Choose the auto option (default) if you are optimizing for download size on
mobile browsers and optimizing for performance on desktop browsers.
Choose the html option if you are optimizing download size over performance on
both desktop and mobile browsers.
Choose the canvaskit option if you are prioritizing performance and
pixel-perfect consistency on both desktop and mobile browsers.
Examples
Run in Chrome using the default renderer option (auto):
Build your app in release mode, using the default (auto) option:
Build your app in release mode, using just the CanvasKit renderer:
Run your app in profile mode using the HTML renderer: | https://docs.flutter.dev/development/platform-integration/web/renderers/index.html |
39a9209237bd-0 | Support for WebAssembly (Wasm)
Platform integration
Web
Wasm
WebAssembly support for Dart and Flutter is under active development,
and is currently considered experimental.
We hope to have the feature ready to try out later in 2023.
The Flutter and Dart teams are excited to add
WebAssembly as a compilation target when building
applications for the web.
Compiling Dart to this new target requires
WebAssembly Garbage Collection (WasmGC),
an upcoming addition to the WebAssembly standard. The Chrome team is actively
working on WasmGC. You can
see the status of the Garbage Collection proposal—and all other Wasm
proposals—on the WebAssembly roadmap.
In the mean time, check out Flutter’s
existing support for the web. We are
optimistic that existing Flutter web applications will have to do little or no
work to support WebAssembly once work is complete. | https://docs.flutter.dev/development/platform-integration/web/wasm/index.html |
39a9209237bd-1 | You might also be interested in this talk by folks on our team:
Flutter, Dart, and WasmGC: A new model for web applications.
For the latest updates on this effort,
check out flutter.dev/wasm. | https://docs.flutter.dev/development/platform-integration/web/wasm/index.html |
477564d170d8-0 | Displaying images on the web
Platform integration
Web
Web images
Images in Flutter
Images on the web
Cross-Origin Resource Sharing (CORS)
Flutter renderers on the web
In-memory, asset, and same-origin network images
Cross-origin images
Host your images in a CORS-enabled CDN.
Lack control over the image server? Use a CORS proxy.
Use <img> in a platform view.
The web supports the standard Image widget to display images.
However, because web browsers are built to run untrusted code safely,
there are certain limitations in what you can do with images compared
to mobile and desktop platforms. This page explains these limitations
and offers ways to work around them.
Background
This section summarizes the technologies available
across Flutter and the web,
on which the solutions below are based on. | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-1 | Images in Flutter
Flutter offers the Image widget as well as the low-level
dart:ui/Image class for rendering images.
The Image widget has enough functionality for most use-cases.
The dart:ui/Image class can be used in
advanced situations where fine-grained control
of the image is needed.
Images on the web
The web offers several methods for displaying images.
Below are some of the common ones:
The built-in <img> and <picture> HTML elements.
The drawImage method on the <canvas> element.
Custom image codec that renders to a WebGL canvas. | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-2 | Custom image codec that renders to a WebGL canvas.
Each option has its own benefits and drawbacks.
For example, the built-in elements fit nicely among
other HTML elements, and they automatically take
advantage of browser caching, and built-in image
optimization and memory management.
They allow you to safely display images from arbitrary sources
(more on than in the CORS section below).
drawImage is great when the image must fit within
other content rendered using the <canvas> element.
You also gain control over image sizing and,
when the CORS policy allows it, read the pixels
of the image back for further processing.
Finally, WebGL gives you the highest degree of
control over the image. Not only can you read the pixels and
apply custom image algorithms, but you can also use GLSL for
hardware-acceleration.
Cross-Origin Resource Sharing (CORS) | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-3 | Cross-Origin Resource Sharing (CORS)
CORS is a mechanism that browsers use to control
how one site accesses the resources of another site.
It is designed such that, by default, one web-site
is not allowed to make HTTP requests to another site
using XHR or fetch.
This prevents scripts on another site from acting on behalf
of the user and from gaining access to another
site’s resources without permission.
When using <img>, <picture>, or <canvas>,
the browser automatically blocks access to pixels
when it knows that an image is coming from another site
and the CORS policy disallows access to data.
WebGL requires access to the image data in order
to be able to render the image. Therefore,
images to be rendered using WebGL must only come from servers
that have a CORS policy configured to work with
the domain that serves your application.
Flutter renderers on the web
Flutter offers a choice of two renderers on the web: | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-4 | Flutter offers a choice of two renderers on the web:
HTML: this renderer uses a combination of HTML,
CSS, Canvas 2D, and SVG to render UI.
It uses the <img> element to render images.
CanvasKit: this renderer uses WebGL to render UI,
and therefore requires
access to the pixels of the image.
Because the HTML renderer uses the <img>
element it can display images from
arbitrary sources. However,
this places the following limitations on what you
can do with them:
Limited support for Image.toByteData.
No support for OffsetLayer.toImage and
Scene.toImage.
No access to frame data in animated images
(Codec.getNextFrame,
frameCount is always 1, repetitionCount is always 0).
No support for ImageShader.
Limited support for shader effects that can be applied to images. | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-5 | Limited support for shader effects that can be applied to images.
No control over image memory (Image.dispose has no effect).
The memory is managed by the browser behind-the-scenes.
The CanvasKit renderer implements Flutter’s image API fully.
However, it requires access to image pixels to do so,
and is therefore subject to the CORS policy.
Solutions
In-memory, asset, and same-origin network images
If the app has the bytes of the encoded image in memory,
provided as an asset, or stored on the
same server that serves the application
(also known as same-origin), no extra effort is necessary.
The image can be displayed using
Image.memory, Image.asset, and Image.network
in both HTML and CanvasKit modes.
Cross-origin images
The HTML renderer can load cross-origin images
without extra configuration. | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-6 | The HTML renderer can load cross-origin images
without extra configuration.
CanvasKit requires that the app gets the bytes of the encoded image.
There are several ways to do this, discussed below.
Host your images in a CORS-enabled CDN.
Typically, content delivery networks (CDN)
can be configured to customize what domains
are allowed to access your content.
For example, Firebase site hosting allows
specifying a custom Access-Control-Allow-Origin
header in the firebase.json file.
Lack control over the image server? Use a CORS proxy.
If the image server cannot be configured to allow CORS
requests from your application,
you may still be able to load images by proxying the requests
through another server. This requires that the
intermediate server has sufficient access to load the images.
This method can be used in situations when the original
image server serves images publicly,
but is not configured with the correct CORS headers.
Examples: | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
477564d170d8-7 | Examples:
Using CloudFlare Workers.
Using Firebase Functions.
Use <img> in a platform view.
Flutter supports embedding HTML inside the app using
HtmlElementView. Use it to create an <img>
element to render the image from another domain.
However, do keep in mind that this comes with the
limitations explained in the section
“Flutter renderers on the web” above.
As of today, using too many HTML elements
with the CanvasKit renderer may hurt performance.
If images interleave non-image content Flutter needs to
create extra WebGL contexts between the <img> elements.
If your application needs to display a lot of images
on the same screen all at once, consider using
the HTML renderer instead of CanvasKit. | https://docs.flutter.dev/development/platform-integration/web/web-images/index.html |
8c0e1648bb75-0 | Building Windows apps with Flutter
Platform integration
Windows
Windows development
Integrating with Windows
Supporting Windows UI guidelines
Customizing the Windows host application
Compiling with Visual Studio
Distributing Windows apps
MSIX packaging
Create a self-signed .pfx certificate for local testing
Building your own zip file for Windows
This page discusses considerations unique to building
Windows apps with Flutter, including shell integration
and distribution of Windows apps through the
Microsoft Store on Windows.
Integrating with Windows | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-1 | Integrating with Windows
The Windows programming interface combines traditional Win32 APIs,
COM interfaces and more modern Windows Runtime libraries.
As all these provide a C-based ABI,
you can call into the services provided by the operating
system using Dart’s Foreign Function Interface library (dart:ffi).
FFI is designed to enable Dart programs to efficiently call into
C libraries. It provides Flutter apps with the ability to allocate
native memory with malloc or calloc, support for pointers,
structs and callbacks, and ABI types like long and size_t.
For more information about calling C libraries from Flutter,
see C interop using dart:ffi. | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-2 | In practice, while it is relatively straightforward to call
basic Win32 APIs from Dart in this way,
it is easier to use a wrapper library that abstracts the
intricacies of the COM programming model.
The win32 package provides a library
for accessing thousands of common Windows APIs,
using metadata provided by Microsoft for consistency and correctness.
The package also includes examples of
a variety of common use cases,
such as WMI, disk management, shell integration,
and system dialogs.
A number of other packages build on this foundation,
providing idiomatic Dart access for the Windows registry,
gamepad support, biometric storage,
taskbar integration, and serial port access, to name a few.
More generally, many other packages support Windows,
including common packages such as url_launcher, shared_preferences, file_selector, and path_provider.
Supporting Windows UI guidelines | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-3 | Supporting Windows UI guidelines
While you can use any visual style or theme you choose,
including Material, some app authors might wish to build
an app that matches the conventions of Microsoft’s
Fluent design system. The fluent_ui package,
a Flutter Favorite, provides support for visuals
and common controls that are commonly found in
modern Windows apps, including navigation views,
content dialogs, flyouts, date
pickers, and tree view widgets.
In addition, Microsoft offers fluentui_system_icons,
a package that provides easy access to thousands of
Fluent icons for use in your Flutter app.
Lastly, the bitsdojo_window package provides support
for “owner draw” title bars, allowing you to replace
the standard Windows title bar with a custom one
that matches the rest of your app.
Customizing the Windows host application | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-4 | Customizing the Windows host application
When you create a Windows app, Flutter generates a
small C++ application that hosts Flutter.
This “runner app” is responsible for creating and sizing a
traditional Win32 window, initializing the Flutter
engine and any native plugins,
and running the Windows message loop
(passing relevant messages on to Flutter for further processing).
You can, of course, make changes to this code to suit your needs,
including modifying the app name and icon,
and setting the window’s initial size and location.
The relevant code is in main.cpp,
where you will find code similar to the following:
Win32Window
::
Point
origin
10
10
);
Win32Window
::
Size
size
1280
720 | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-5 | 1280
720
);
if
window
CreateAndShow
L"myapp"
origin
size
))
return
EXIT_FAILURE
Replace myapp with the title you would like displayed in the
Windows caption bar, as well as optionally adjusting the
dimensions for size and the window coordinates.
To change the Windows application icon, replace the
app_icon.ico file in the windows\runner\resources
directory with an icon of your preference.
The generated Windows executable filename can be changed
by editing the BINARY_NAME variable in windows/CMakeLists.txt:
cmake_minimum_required
(VERSION 3.14
project
(windows_desktop_app LANGUAGES CXX | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-6 | project
(windows_desktop_app LANGUAGES CXX
# The name of the executable created for the application.
# Change this to change the on-disk name of your application.
set
(BINARY_NAME
"YourNewApp"
cmake_policy
(SET CMP0063 NEW
When you run flutter build windows,
the executable file generated in the
build\windows\runner\Release directory
will match the newly given name.
Finally, further properties for the app executable
itself can be found in the Runner.rc file in the
windows\runner directory. Here you can change the
copyright information and application version that
is embedded in the Windows app, which is displayed
in the Windows Explorer properties dialog box.
To change the version number, edit the VERSION_AS_NUMBER
and VERSION_AS_STRING properties;
other information can be edited in the StringFileInfo block. | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-7 | Compiling with Visual Studio
For most apps, it’s sufficient to allow Flutter to
handle the compilation process using the flutter run
and flutter build commands. If you are making significant
changes to the runner app or integrating Flutter into an existing app,
you might want to load or compile the Flutter app in Visual Studio itself.
Follow these steps:
Run flutter build windows to create the build\ directory.
Open the Visual Studio solution file for the Windows runner,
which can now be found in the build\windows directory,
named according to the parent Flutter app.
In Solution Explorer, you will see a number of projects.
Right-click the one that has the same name as the Flutter app,
and choose Set as Startup Project.
Run Build / Build Solution (or press Ctrl+Shift+B)
to generate the necessary dependencies.
You should now be able to run Debug / Start Debugging
(or press F5) to run the Windows app from Visual Studio. | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-8 | Use the toolbar to switch between Debug and Release
configurations as appropriate.
Distributing Windows apps
There are various approaches you can use for
distributing your Windows application.
Here are some options:
Use tooling to construct an MSIX installer
(described in the next section)
for your application and distribute it through
the Microsoft Windows App Store.
You don’t need to manually create a signing
certificate for this option as it is
handled for you.
Construct an MSIX installer and distribute
it through your own website. For this
option, you need to to give your application a
digital signature in the form of a
.pfx certificate.
Collect all of the necessary pieces
and build your own zip file.
MSIX packaging | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-9 | MSIX packaging
MSIX, the new Windows application package format,
provides a modern packaging format and installer.
This format can either be used to ship applications
to the Microsoft Store on Windows, or you can
distribute app installers directly.
The easiest way to create an MSIX distribution
for a Flutter project is to use the
msix pub package.
For an example of using the msix package
from a Flutter desktop app,
see the Desktop Photo Search sample.
Create a self-signed .pfx certificate for local testing
For private deployment and testing with the help
of the MSIX installer, you need to give your application a
digital signature in the form of a .pfx certificate.
For deployment through the Windows Store,
generating a .pfx certificate is not required.
The Windows Store handles creation and management
of certificates for applications
distributed through its store. | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-10 | Distributing your application by self hosting it on a
website requires a certificate signed by a
Certificate Authority known to Windows.
Use the following instructions to generate a
self-signed .pfx certificate.
If you haven’t already, download the OpenSSL
toolkit to generate your certificates.
Go to where you installed OpenSSL, for example,
C:\Program Files\OpenSSL-Win64\bin.
Set an environment variable so that you can access
OpenSSL from anywhere:
"C:\Program Files\OpenSSL-Win64\bin"
Generate a private key as follows:
openssl genrsa -out mykeyname.key 2048
Generate a certificate signing request (CSR)
file using the private key:
openssl req -new -key mykeyname.key -out mycsrname.csr | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
8c0e1648bb75-11 | Generate the signed certificate (CRT) file using
the private key and CSR file:
openssl x509 -in mycsrname.csr -out mycrtname.crt -req -signkey mykeyname.key -days 10000
Generate the .pfx file using the private key and
CRT file:
openssl pkcs12 -export -out CERTIFICATE.pfx -inkey mykeyname.key -in mycrtname.crt
Install the .pfx certificate first on the local machine
in Certificate store as
Trusted Root Certification Authorities
before installing the app.
Building your own zip file for Windows
The Flutter executable, .exe, can be found in your
project under build\windows\runner\<build mode>\.
In addition to that executable, you need the following:
From the same directory:
all the .dll files
the data directory | https://docs.flutter.dev/development/platform-integration/windows/building/index.html |
Subsets and Splits