首先是初始化:
查看Nativeshell的demo代码
// ignore_for_file: undefined_hidden_name, // not in main
import 'package:flutter/material.dart' hide MenuItem;
import 'package:nativeshell/nativeshell.dart';
import 'pages/other_window.dart';
import 'pages/platform_channels.dart';
import 'main_window.dart';
import 'pages/modal_window.dart';
import 'widgets/veil.dart';
void main() async {
// Disable shader warmup - it delays producing first frame, which we want to
// produce as soon as possible to reduce time to open new windows.
disableShaderWarmUp();
runApp(Main());
}
// Common scaffold code used by each window
class ExamplesWindow extends StatelessWidget {
const ExamplesWindow({Key? key, required this.child}) : super(key: key);
final Widget child;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTextStyle(
style: TextStyle(
color: Colors.white,
fontSize: 14,
),
child: WindowLayoutProbe(child: child),
),
);
}
}
class Main extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Veil(
child: Container(
color: Color.fromARGB(255, 30, 30, 35),
child: WindowWidget(
onCreateState: (initData) {
WindowState? state;
state ??= PlatformChannelsWindowState.fromInitData(initData);
state ??= ModalWindowState.fromInitData(initData);
state ??= OtherWindowState.fromInitData(initData);
state ??= MainWindowState();
return state;
},
),
),
);
}
}
这里要注意 ??= 表示 state如果为null则赋值后面的值,否则返回state的自己的值
子窗口:
PlatformChannelsWindowState.fromInitData(initData);
ModalWindowState.fromInitData(initData);
OtherWindowState.fromInitData(initData);
主窗口:
MainWindowState();
其中initData为创建子窗口时传递过来的参数
initData['class'] 这个字段用于标识应该启动哪个子窗口
通过子窗口主动调用子窗口中的方法,并传参
await otherWindow?.callMethod('showMessage', 'Hello from parent window!');
通过父窗口调用父窗口中的方法,并传参
await Window.of(context).parentWindow?.callMethod('showMessage', 'Hello');