Add a route for your widget which will be displayed in the overlay window:
HomePage(),
// add a route as entrypoint for your overlay window.
"/my-overlay-window": (_) => MyOverlayWindow(),
},
);
}">
@overrideWidgetbuild(BuildContext context) {
returnMaterialApp(
debugShowCheckedModeBanner:false,
initialRoute:"/",
routes: {
"/": (_) =>HomePage(),
// add a route as entrypoint for your overlay window."/my-overlay-window": (_) =>MyOverlayWindow(),
},
);
}
Before we start the floating window, we need to check and request the permission, and initialize the flutter_floatwing plugin in initState or any button's callback function:
// check and grant the system alert window permission.FloatwingPlugin().checkPermission().then((v) {
if (!v) FloatwingPlugin().openPermissionSetting();
});
// initialize the plugin at first.FloatwingPlugin().initialize();
Next to start create and start your overlay window:
// define window config and start the window from config.WindowConfig(route:"/my-overlay-window")
.to() // create a window object
.create(start:true); // create the window and start the overlay window.
Notes:
route is one of 3 ways to define entrypoint for overlay window. Please check the Entrypoint section for more information.
Before we see how flutter_floatwing manage windows in detail, we need to know some things about the design of the plugin.
id is the unique identifier for the window, and all operations on the window are based on this id, you must provide one before creating.
We consider the first engine created by opening the main application as the main engine or plugin engine. The other engines created by service are window engine.
Different engine are different threads and cannot communicate directly.
Subscribe events of all windows from main engine is allowed, it's also allowed to subscribe events of own and child windows in window engine. But we can not subscribe events of sibling or parent windows.
share data is the only way to communicate between window engine or plugin engine, there are no restrictions on it, except that the data needs to be serializable. Which means you can share data from anywhere to anywhere.
A floatwing window object contains: a flutter engine which run a widget by runApp and a view which add to window manager.
The whole view hierarchy like below:
Usage
Before we start how to use flutter_floatwing in detail, let's talk about how the flutter_floatwing create a new overlay window:
First of all we need to start a service as manager by main app.
Then create window request send to the service.
In the service, we start the flutter engine with entrypoint.
Create a new flutter view and attach it to the flutter engine.
Add the view to android window manager.
Window & Config
WindowConfig contains all configuration for window. We can use configuration to create a window like below:
void_createWindow() {
var config =WindowConfig();
w =Window(config, id="my-window");
w.create();
}
If you have no need to register event or data handler, you can just use config to create a window.
But as you can see, if you want to provide a id for window, must provide in WindowConfig.
If want to register handler, you can use a to() function to turn a config to a window at first, this is every useful when you want to make code simple.
Entrypoint is where the engine execute from. We support 3 modes of configuration:
Name
Config
How to use
route
WindowConfig(route: "/my-overlay")
- Add a route for overlay window in your main routes - Start window with config: WindowConfig(route: "/my-overlay")
staic function
WindowConfig(callback: myOverlayMain)
- Define a static function void Function() which calling runApp to start a widget. - Start window with config: WindowConfig(callback: myOverlayMain)
entry-point
WindowConfig(entry: "myOverlayMain")
- First step is same as staic function. - Add @pragma("vm:entry-point") above the static function. - Start window with config: WindowConfig(entry: "myOverlayMain") - like static function, but use string of function name as parameter
Example for route
Add route for your overlay widget in the main application.
HomePage(),
// add a route as entrypoint for your overlay window.
"/my-overlay-window": (_) => MyOverlayWindow(),
},
);
}">
@overrideWidgetbuild(BuildContext context) {
returnMaterialApp(
debugShowCheckedModeBanner:false,
initialRoute:"/",
routes: {
"/": (_) =>HomePage(),
// add a route as entrypoint for your overlay window."/my-overlay-window": (_) =>MyOverlayWindow(),
},
);
}
Start window with route as config.
void_startWindow() {
// define window config and start the window from config.WindowConfig(route:"/my-overlay-window")
.to() // create a window object
.create(start:true); // create the window and start the overlay window.
}
Example for static function
Define a static function which called runApp
voidmyOverlayMain() {
runApp(MaterialApp(
home:AssistivePannel(),
));
// or simply use `floatwing` method to inject `MaterialApp`// runApp(AssistivePannel().floatwing(app: true));
}
Start window with callback as config.
void_startWindow() {
// define window config and start the window from config.WindowConfig(callback: myOverlayMain)
.to() // create a window object
.create(start:true); // create the window and start the overlay window.
}
Example for entry-point
Define as static function which called runApp and add prama
@pragma("vm:entry-point")
voidmyOverlayMain() {
runApp(MaterialApp(
home:AssistivePannel(),
));
// or simply use `floatwing` method to inject `MaterialApp`// runApp(AssistivePannel().floatwing(app: true));
}
Start window with entry as config.
void_startWindow() {
// define window config and start the window from config.WindowConfig(entry:"myOverlayMain")
.to() // create a window object
.create(start:true); // create the window and start the overlay window.
}
Wrap your widget
For simple widget, you have no need to do with your widget. But if you want more functions and make your code clean, we provide a injector for your widget.
For now there are some functions listed below,
Auto resize the window view.
Auto sync and ensure the window.
Wrap a MaterialApp
more features are coming
Before, we write our overlay main function, like below,
We can wrap to a Widget and a WidgetBuilder, wrap the WidgetBuilder, we can access the window instance with Window.of(context), while FloatwingPlugin().currentWindow is the only to get window instance for wrap Widget.
If we want to access the window with Window.of(context), change the code like below,
In your window engine, you can access the window object in 2 ways:
Directly access the cache field of plugin: FloatwingPlugin().currentWindow.
If widget injected by .floatwing(), you can take window with Window.of(context).
FloatwingPlugin().currentWindow will return null unless initialize has been completed.
If you inject WidgetBuilder with .floatwing(), then you can access the current window. It will always return non-value, unless you enable debug with .floatwing(debug: true).
For example, if we want to get the id of current window, we can do it like below:
/// ...import'package:flutter_floatwing/flutter_floatwing.dart';
class_ExampleViewStateextendsState<ExampleView> {
Window? w;
@overridevoidinitState() {
super.initState();
SchedulerBinding.instance?.addPostFrameCallback((_) {
w =Window.of(context);
print("my window id is ${w.id}");
});
}
}
Subscribe events
We can subscribe events from windows, and trigger actions when events fired. Events of window will be sent to main engine, self window engine and the parent `window engine. Which means you can subscribe events of window from flutter of main application, overlay window and parent overlay window.
Currently we support events for window lifecycle and drag action.
More events type are coming, and contributtions are welcome!
For example, we want to do something when the window is started, we can code like below:
@overridevoidinitState() {
super.initState();
SchedulerBinding.instance?.addPostFrameCallback((_) {
w =Window.of(context);
w?.on(EventType.WindowStarted, (window, _) {
print("$w has been started.");
}).on(EventType.WindowDestroy, (window, data) {
// data is a boolean value, which means that the window// are destroyed force or not.print("$w has been destroy, force $data");
});
});
}
Share data with windows
Sharing data is the only way to communicate with windows. We provide a simple way to do this: window.share(data).
For example, if you want to share data to overlay window from main application.
First get the target window in main application, usually the created one can be used or you can get one from windows cache by id,
Window w;
void_startWindow() {
w =WindowConfig(route:"/my-overlay-window").to();
}
void_shareData(dynamic data) {
w.share(data).then((value) {
// and window can return value.
});
// or just take one from cache// FloatwingPlugin().windows["default"]?.share(data);
}
If you want to share data with a name, yon can add the name parameter: ``w.share(data, name="name-1")`.
And then you should listen the data in window by register the data handler.
@overridevoidinitState() {
super.initState();
SchedulerBinding.instance?.addPostFrameCallback((_) {
w =Window.of(context);
w?.onData((source, name, data) async {
print("get $name data from $source: $data");
});
});
}
The function signature of handler is Future Function(String? source, String? name, dynamic data).
source is where the data comes from, null if from main application, from window will be the id of window.
name is the data name, you can share data for different purposes.
data is the data that you get.
return some value if you want to do.
There are restrictions for directions of communication, unless you send data to self, which will not be allowed. Which means you can send data as long as you know the id of window. Currently share to main application is not implemented.
Note: The data you are sharing should be serializable.
API References
FloatwingPlugin instance
FloatwingPlugin is a singleton class that returns the same instance every time it called FloatwingPlugin() factory method.
WindowConfig Object
TODO
Window Object
TODO
Events
Window lifecycle
Action
More events type are coming, and comtributions are welcome!
Support
Did you find this plugin useful? Please consider to make a donation to help improve it!
flutter_floatwing-main\android\src\main\kotlin\im\zoe\labs\flutter_floatwing\FloatwingService.kt: (128, 32): Type mismatch: inferred type is Map<*, >? but Map<, *> was expected
I'm trying to run a simple test, where I show an overlay with the entry-point. But the window doesn't start/create, instead null is returned. The followings are the logs -
Logs
Launching lib\main.dart on Android SDK built for x86 in debug mode...
lib\main.dart:1
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:61440/5XyFBiJrhLk=/ws
D/FloatwingPlugin( 9392): [plugin] pixel radio already exits
D/FloatwingPlugin( 9392): [plugin] system config already exits: {"pixelRadio":2,"screen":{"width":1080,"height":2208}}
[log] [plugin] initialize result: {permission_grated: true, pixel_radio_updated: false, system_config_updated: false, service_running: false, windows: null}
[log] [plugin] there are 0 windows already started
D/FloatwingService( 9392): [service] wait for service created
I/FloatwingService( 9392): [service] create a window: default {entry=myOverlayMain}
D/FloatwingService( 9392): [service] wait for service created
I/flutter ( 9392): [ DEBUG ]: window null
I also noticed that awaiting the openPermissionSetting() doesn't actually wait for permission from the user/settings.
await FloatwingPlugin().openPermissionSetting();
Steps to reproduce:
Run the following code -
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_floatwing/flutter_floatwing.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FloatwingPlugin().initialize();
runApp(const RootApp());
}
@pragma("vm:entry-point")
void myOverlayMain() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Material(
color: Colors.transparent,
elevation: 0.0,
child: Container(
width: 100,
height: 100,
color: Colors.black,
),
),
),
);
}
class RootApp extends StatelessWidget {
const RootApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text("Floatwing Test"),
),
body: Center(
child: TextButton(
onPressed: _startWindow,
child: const Text("Start"),
),
),
),
);
}
void _startWindow() async {
// check permission and service status
final bool hasPermission = await FloatwingPlugin().checkPermission();
final bool serviceStarted = await FloatwingPlugin().isServiceRunning();
if (!hasPermission) {
await FloatwingPlugin().openPermissionSetting();
// ☝️ it doesn't wait for the value returned by permissions
}
if (!serviceStarted) {
await FloatwingPlugin().startService();
}
// start overlay window
final Window? window = await WindowConfig(
entry: "myOverlayMain",
).to().create(start: true);
debugPrint("[ DEBUG ]: window $window");
}
}
The WindowDestroy event which gets called when closing a window is not returning any value in the data i.e. forceClose value.
I am listening to the event in this manner:
_window?.on(EventType.WindowDestroy, (Window window, dynamic data)
The event call gets notified but data is empty.
Also seeing an error in the console:
W/FlutterJNI(17960): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++.
Could not send. Channel: im.zoe.labs/flutter_floatwing/window_msg. Response ID: 9
../../../flutter/.pub-cache/hosted/pub.dartlang.org/flutter_floatwing-0.2.0/lib/src/provider.dart:143:30: Warning: Operand of null-aware operation '?.' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('../../../flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance?.addPostFrameCallback(postFrameCallback);
Screen shows a scrollable windows, but appears to not respond to anything.
This may be a common issue. Plugins register method channels and message channels in onAttachEngine, While the window engine started, those channels will be registered again. That will cause the call from the main engine(the app) missing response.
Known issues: #6
Currently I don't know how to handle this issue. Discussion is welcome!
bughelp wanted
opened by jiusanzhou 2
Owner
Zoe
Cloud Native. Try to be an Indie hacker, running @wellwellwork + bootstrapping my own products. INTJ.
Make your native android Dialog Fancy and Gify. A library that takes the standard Android Dialog to the next level with a variety of styling options and Gif's. Style your dialog from code.