Flutter Add to App DEMO 笔记
Posted aikongmeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter Add to App DEMO 笔记相关的知识,希望对你有一定的参考价值。
[GIT地址]
Add to App 官方文档
https://flutter.dev/docs/development/add-to-app
git clone --depth 1 https://github.com/flutter/samples.git
摘录部分代码块,全源码可看上述地址,应该Flutter 已经 出2.0+版本, 增加了空异常检测, 所以demo 所使用的库包都要升级到支持空检查的新版本。
android 端配置:
FlutterActivity 添加到 manifest
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize" />
自定义MyApplication , 使用 FlutterEngine Cached 的方式使用Flutter页面
public class MyApplication extends Application {
public FlutterEngine flutterEngine;
@Override
public void onCreate() {
super.onCreate();
// Instantiate a FlutterEngine.
flutterEngine = new FlutterEngine(this);
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartEntrypoint.createDefault()
);
// Cache the FlutterEngine to be used by FlutterActivity.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine);
}
}
Intent intent = FlutterActivity
.withCachedEngine("my_engine_id")
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(this);
startActivity(intent);
channel 配置
channel = new MethodChannel(flutterEngine.getDartExecutor(), "dev.flutter.example/counter");
channel.setMethodCallHandler((call, result) -> {
switch (call.method) {
case "incrementCounter":
count++;
reportCounter();
break;
case "requestCounter":
count--;
reportCounter();
break;
}
});
channel 注入方法
private void reportCounter() {
channel.invokeMethod("reportCounter", count);
}
Flutter 端代码:
void main() {
// This call ensures the Flutter binding has been set up before creating the
// MethodChannel-based model.
WidgetsFlutterBinding.ensureInitialized();
final model = CounterModel();
runApp(
ChangeNotifierProvider.value(
value: model,
child: MyApp(),
),
);
}
_channel 配置方法一一對應
class CounterModel extends ChangeNotifier {
CounterModel() {
_channel.setMethodCallHandler(_handleMessage);
_channel.invokeMethod('requestCounter');
}
final _channel = MethodChannel('dev.flutter.example/counter');
int _count = 0;
int get count => _count;
void increment() {
_channel.invokeMethod('incrementCounter');
}
Future<dynamic> _handleMessage(MethodCall call) async {
if (call.method == 'reportCounter') {
_count = call.arguments as int;
notifyListeners();
}
}
}
調用
Consumer<CounterModel>(
builder: (context, model, child) {
return ElevatedButton(
onPressed: () => model.increment(),
child: Text('Tap me!'),
);
},
),
以上是关于Flutter Add to App DEMO 笔记的主要内容,如果未能解决你的问题,请参考以下文章
Flutter Add-to-app 我可以在 iOS 视图控制器中添加半屏 Flutter 小部件吗