본문 바로가기

dev/flutter

플랫폼 통신 MethodChannel (안드로이드, IOS)

안드로이드

android > app > src > main > MainActivity 에 통신할 코드를 작성한다. 안드로이드 스튜디오나 vscode를 사용해도 상관없다.

 

 

 

configureFlutterEngine함수를 오버라이딩하여 작성한다.

채널명은 플러터와 맞춰주면 된다.

플러터에서 통신한 메소드명이 test인 경우 OK를 보낸다.

 

 

 

IOS

ios > Runner > AppDelegate.swift 파일에 통신할 코드를 작성한다. Xcode나 vscode를 사용해도 상관없다.

 

 

 

 

플러터

메소드채널을 선언해주고, test라는 메소드명으로 값을 받아 로그를 찍어본다.

 

 

 

 

 

 

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  MethodChannel methodChannel = const MethodChannel("example.channel/test");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            methodChannel.invokeMethod("test").then((value) {
              String result = value.toString();
              log("result: $result");
            });
          }, 
          child: const Text('test')
        ),
      ),
    );
  }
}