LoginSignup
0
0

More than 1 year has passed since last update.

FlutterでiOSのソースを呼び出す

Posted at

押したら文字が変わるだけのシンプルなものです。ただFlutterではなくiOSのソースを呼び出しています。画面は下記。
Simulator Screen Shot - iPhone SE (3rd generation) - 2022-05-24 at 09.07.17.png Simulator Screen Shot - iPhone SE (3rd generation) - 2022-05-24 at 09.07.19.png

ソース(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のソースを読まないとできないような感じのことになり、調べたらわかりづらい記事ばかりで、イライラしたので自身の忘備録も兼ねて残しておきます。

誰かの参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0