押したら文字が変わるだけのシンプルなものです。ただFlutterではなくiOSのソースを呼び出しています。画面は下記。
ソース(iOS)。コピペでOKです。
AppDelegate(ios/Runner/AppDelegate.swift)
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let controller :FlutterViewController = window?.rootViewController as! FlutterViewController
let methodChannel = FlutterMethodChannel(name: "test", binaryMessenger: controller as! FlutterBinaryMessenger)
methodChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: FlutterResult) -> Void in
if call.method == "getMessage" {
result("Hello from iOS")
} else {
result(FlutterMethodNotImplemented)
}
})
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Flutter(lib//testView.dart)
testViewだけ作ってください。あとはコピペでOKです
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class TestView extends StatefulWidget {
const TestView({Key? key}) : super(key: key);
@override
_TestView createState() => _TestView();
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
}
class _TestView extends State<TestView> {
final _channel = MethodChannel('test');
String _message = 'Push Button';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(''),
),
body: Center(
child: Column(
children: <Widget>[
Text(_message),
ElevatedButton(
child: Text("ボタン"),
onPressed: () async {
final message = await _channel.invokeMethod('getMessage');
setState(() {
_message = message;
});
},
),
]
),
),
);
}
}
FlutterでiOSのソースを読まないとできないような感じのことになり、調べたらわかりづらい記事ばかりで、イライラしたので自身の忘備録も兼ねて残しておきます。
誰かの参考になれば幸いです。