Skip to main content

Integrating the Switchboard SDK Into a Flutter Project

In order to use the Switchboard SDK in a Flutter application you need to write some custom platform-specific code, depending on which platform you want to use it on. Flutter's built-in platform-specific API support doesn't rely on code generation, but rather on a flexible message passing style. For more information please check out the Flutter documentation site.

Common Flutter Platform Client

You have to construct a MethodChannel and connect the client and host sides through the channel with a channel name passed in the channel constructor. The following code snippets illustrate how can this be achieved:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
static const MethodChannel methodChannel = MethodChannel('switchboard-sdk');

void startSineWaveGenerator() async {
try {
await methodChannel.invokeMethod('startSineWave');
} on PlatformException catch (e) {
print(e);
}
}

void stopSineWaveGenerator() async {
try {
await methodChannel.invokeMethod('stopSineWave');
} on PlatformException catch (e) {
print(e);
}
}


Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
child: const Text('Start', textDirection: TextDirection.ltr),
onPressed: () {
startSineWaveGenerator();
},
),
ElevatedButton(
child: const Text('Stop', textDirection: TextDirection.ltr),
onPressed: () {
stopSineWaveGenerator();
},
)
],
)),
));
}
}

iOS Platform-Specific Implementation

Integrate the Switchboard iOS SDK into the Flutter generated iOS project by following the iOS Integration Guide.

You can put together your audio engine in a Swift file. The following code snippet creates an audio engine with a sine tone generator.

//  SineGeneratorExample.swift

import SwitchboardSDK

class SineGeneratorExample {
let audioEngine = SBAudioEngine()
let audioGraph = SBAudioGraph()
let sineGeneratorNode = SBSineGeneratorNode()

init() {
audioGraph.addNode(sineGeneratorNode)
audioGraph.connect(sineGeneratorNode, to: audioGraph.outputNode)
}

func setFrequency(_ newValue: Float) {
sineGeneratorNode.frequency = newValue
}

func setAmplitude(_ newValue: Float) {
sineGeneratorNode.amplitude = newValue
}

func start() {
audioEngine.start(audioGraph)
}

func stop() {
audioEngine.stop()
}
}

To use the Swift methods of the above class you need to create a FlutterMethodChannel tied to the channel name:

// AppDelegate.swift 

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

let example = SineGeneratorExample()

override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let methodChannel = FlutterMethodChannel(name: "switchboard-sdk",
binaryMessenger: controller.binaryMessenger)
methodChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
// This method is invoked on the UI thread.
if (call.method == "startSineWave") {
self?.example.start()
} else if (call.method == "stopSineWave") {
self?.example.stop()
} else {
result(FlutterMethodNotImplemented)
}
})

GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

To learn more about iOS native modules you can check out the Flutter documentation site.

Android Platform-Specific Implementation

Integrate the Switchboard Android SDK into the Flutter generated Android project by following the Android Integration Guide.

You can put together your audio engine in a Kotlin file. The following code snippet creates an audio engine with a sine tone generator.

// SineWaveGeneratorExample.kt

package com.example.switchboard_sdk

import com.synervoz.switchboard.sdk.audioengine.AudioEngine
import com.synervoz.switchboard.sdk.audiograph.AudioGraph
import com.synervoz.switchboard.sdk.audiographnodes.SineGeneratorNode

class SineWaveGeneratorExample(context: Context) {

val audioEngine = AudioEngine(context)
val sineGeneratorNode = SineGeneratorNode()
val audioGraph = AudioGraph()

init {
sineGeneratorNode.frequency = 440f
sineGeneratorNode.amplitude = 0.8f

audioGraph.addNode(sineGeneratorNode)
audioGraph.connect(sineGeneratorNode, audioGraph.outputNode)
}

fun close() {
audioEngine.close()
audioGraph.close()
sineGeneratorNode.close()
}

fun start() {
if (!audioEngine.isRunning) {
audioEngine.start(audioGraph)
}
}

fun stop() {
if (audioEngine.isRunning) {
audioEngine.stop()
}
}
}

Create a FlutterActivity and inside the configureFlutterEngine() method, create a MethodChannel and call setMethodCallHandler(). Make sure to use the same channel name as was used on the Flutter client side.

// MainActivity.kt 

import android.Manifest
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.synervoz.switchboard.sdk.SwitchboardSDK


class MainActivity : FlutterActivity() {

init {
SwitchboardSDK.initialize("Your client ID", "Your client secret")
}

lateinit var example: SineWaveGeneratorExample = SineWaveGeneratorExample()

private val CHANNEL = "switchboard-sdk"

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)

MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// This method is invoked on the main thread.
call, result ->
if (call.method == "startSineWave") {
example.start()
} else if (call.method == "stopSineWave") {
example.stop()
} else {
result.notImplemented()
}
}

}
}

To learn more about Android native modules you can check out the Flutter documentation site.