Flutter同React Native一樣,可以調用原生方法。
Flutter 代碼如下:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async'; // 異步
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter & Android互動',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Flutter & Android互動'),
),
body: new HomeApp(),
),
);
}
}
class HomeApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new HomeAppPage();
}
}
class HomeAppPage extends State<HomeApp> {
static const platform = const MethodChannel("samples.flutter.io/battery");
String _batteryLevel = "Unknown battery level.";
Future<Null> _getBatteryLevel() async {
String batteryLevel;
try{
print('dart-_getBatteryLevel');
// 在通道上調用此方法
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e){
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
setState(() {
_batteryLevel = batteryLevel;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new RaisedButton(onPressed: _getBatteryLevel,
child: new Text('Get battery level'),
),
new Text('目前電量:$_batteryLevel')
],
);
}
}
Android代碼:
package com.example.beautifuldemo;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
// 擷取電池電量通道
private static final String CHANNEL = "samples.flutter.io/battery";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
// setMethodCallHandler在此通道上接收方法調用的回調
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
// 通過methodCall可以擷取參數和方法名 執行對應的平台業務邏輯即可
if(methodCall.method.equals("getBatteryLevel")){
int batteryLevel = getBatteryLevel();
if(batteryLevel != -1){
result.success(batteryLevel);
}else{
result.error("UNAVAILABLE", "Battery level not available.", null);
}
}else{
result.notImplemented();
}
}
}
);
}
/*擷取電池電量*/
private int getBatteryLevel(){
int batteryLevel = -1;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
}
iOS 代碼:
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// 擷取電池電量
FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel *batteryLevelChannel = [FlutterMethodChannel methodChannelWithName:@"samples.flutter.io/battery" binaryMessenger:controller];
[batteryLevelChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
if ([@"getBatteryLevel" isEqualToString:call.method]) {
result(@100);
return;
}
result(FlutterMethodNotImplemented);
}];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
效果圖: