Integrating WiFi SDK in Flutter apps

This article is intended to illustrate, at a high level, the process required to create a Flutter plugin for the Cloud4Wi SDK. It is not necessarily exhaustive in code examples. A prerequisite for this project is to be a knowledgeable Flutter developer.

The guide is divided into two parts. The first part focuses on creating a Flutter plugin from the two SDKs (Android and iOS), using the registerUser method as an example implementation. The second part demonstrates how to integrate the newly created plugin into a sample Flutter app, properly configuring both projects to initialize the SDKs.

Prerequisites

  • Flutter Setup: Ensure you have Flutter installed and configured on your development machine.

  • Development Knowledge:

    • Proficiency in Flutter and Dart.

    • Familiarity with native iOS (Swift/Objective-C) and Android (Kotlin/Java) development.

  • Cloud4Wi SDK Access:

    • Obtain the Cloud4Wi SDK for both iOS and Android.

    • Acquire necessary API keys or credentials required by the SDK.

  • Development Tools:

    • Xcode for iOS development.

    • Android Studio for Android development.


Table of Contents

  1. Creating the Flutter Plugin

  2. Adding Native SDK Dependencies

    • iOS Dependency Setup

    • Android Dependency Setup

  3. Implementing Native Code

    • iOS Implementation

    • Android Implementation

  4. Creating the Dart Interface

  5. Using the Plugin in Your Flutter App

  6. Testing the Integration

  7. Conclusion


Creating the Flutter Plugin

To integrate the Cloud4Wi SDK, you'll create a Flutter plugin that bridges Flutter and the native SDKs.

  1. Create the Plugin:

    flutter create --template=plugin --platforms=android,ios flutter_cloud4wi_sdk
  2. Navigate to the Plugin Directory:

    cd flutter_cloud4wi_sdk

Adding Native SDK Dependencies

iOS Dependency Setup

  1. Modify Podspec File:

    • Open ios/flutter_cloud4wi_sdk.podspec.

    • Add the Cloud4Wi SDK dependency:

      Pod::Spec.new do |s|
        ...
        s.dependency 'c4w-wifi-sdk', '~> 1.7.0' # Replace with actual version
      end

Android Dependency Setup

  1. Modify build.gradle:

    • Open android/build.gradle and ensure the repositories include the Cloud4Wi SDK repository if required.

      repositories {
          ...
          
          maven {
              url = 'https://artifacts.cloud4wi.com/release'
          }
      }
  2. Add SDK Dependency:

    • In android/src/main/build.gradle, add the SDK dependency:

      dependencies {
          implementation 'com.cloud4wi:c4w-wifi-sdk:1.7.0' // Replace with actual version
      }

Implementing Native Code

iOS Implementation

  1. Open iOS Module in Xcode:

    • Navigate to ios/ directory and open the .xcworkspace file.

  2. Import Cloud4Wi SDK:

    • In your plugin's main Swift file (e.g., SwiftFlutterCloud4wiSdkPlugin.swift), add:

      import Cloud4WiSDKWiFi
  3. Implement createCustomer Method:

    import Flutter
    import UIKit
    import Cloud4WiSDKWiFi
    
    public class FlutterCloud4wiSdkPlugin: NSObject, FlutterPlugin {
    
    	public static func register(with registrar: FlutterPluginRegistrar) {
    		let channel = FlutterMethodChannel(name: "flutter_cloud4wi_sdk", binaryMessenger: registrar.messenger())
    		let instance = FlutterCloud4wiSdkPlugin()
    		registrar.addMethodCallDelegate(instance, channel: channel)
    	}
    
    	public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    		switch call.method {
    		case "createCustomer":
    			guard let args = call.arguments as? [String: Any],
    				  let customer = args["customer"] as? [String: Any],
    				  let deduplicateAttribute = args["deduplicateAttribute"] as? String else {
    				result(FlutterError(code: "INVALID_ARGUMENT", message: "Invalid arguments", details: nil))
    				return
    			}
    			createCustomer(customer: customer, deduplicateAttribute: deduplicateAttribute, result: result)
    		default:
    			result(FlutterMethodNotImplemented)
    		}
    	}
    
    	private func createCustomer(customer: [String: Any], deduplicateAttribute: String, result: @escaping FlutterResult) {
    		let customerSDK = Customer()
    		customerSDK?.firstName = customer["firstName"] as? String
    		customerSDK?.lastName = customer["lastName"] as? String
    		customerSDK?.email = customer["email"] as? String
    		customerSDK?.policies = customer["policies"] as? [String: Any] // Verifica il tipo corretto
    
    		Cloud4WiSDKWiFi.init().createCustomer(customerSDK, deduplicate: deduplicateAttribute) { (customerResponse) in
    			if let customerResponse = customerResponse {
    				let responseDictionary: [String: Any] = [
    					"status": customerResponse.status as Any,
    					"generated": customerResponse.generated as Any,
    					"id": customerResponse.id as Any,
    					"organizationId": customerResponse.organizationId as Any,
    					"locationId": customerResponse.locationId as Any,
    					"hotspotId": customerResponse.hotspotId as Any,
    					"username": customerResponse.username as Any,
    					"password": customerResponse.password as Any,
    					"mailSent": customerResponse.mailSent as Any
    				]
    				result(responseDictionary)
    			} else {
    				result(FlutterError(code: "INVALID_ARGUMENT", message: "No customer response found", details: nil))
    			}
    		} onError: { (error) in
    			if let error = error as NSError? {
    				result(FlutterError(code: String(error.code), message: error.localizedDescription, details: nil))
    			}
    		}
    	}
    }
    

Android Implementation

  1. Open Android Module in Android Studio:

    • Navigate to android/ directory and open it in Android Studio.

  2. Import Cloud4Wi SDK:

    • In your plugin's main Kotlin file (e.g., FlutterCloud4wiSdkPlugin.kt), add:

      import com.cloud4wi.sdk.Cloud4WiSDKWiFi
  3. Implement createCustomer Method:

    
    COMING SOON!
    

Creating the Dart Interface

Create a Dart interface that exposes the native methods to Flutter code.


  // lib/flutter_cloud4wi_sdk.dart
import 'dart:async';
import 'package:flutter/services.dart';

class Customer {
  String username;
  String password;
  String firstName;
  String lastName;
  String phoneNumber;
  String email;
  String gender;
  String birthDate;
  String language;
  String country;
  String zipCode;
  String companyName;
  String civilStatus;
  bool phoneVerified;
  bool emailVerified;
  bool ppd;
  bool profiling;
  Map<String, String> custom;
  Map<String, bool> policies;
  CustomerDocument document;
  bool lock;
  String extId;
  String extProp1;
  String extProp2;

  Customer({
    required this.username,
    required this.password,
    required this.firstName,
    required this.lastName,
    required this.phoneNumber,
    required this.email,
    required this.gender,
    required this.birthDate,
    required this.language,
    required this.country,
    required this.zipCode,
    required this.companyName,
    required this.civilStatus,
    required this.phoneVerified,
    required this.emailVerified,
    required this.ppd,
    required this.profiling,
    required this.custom,
    required this.policies,
    required this.document,
    required this.lock,
    required this.extId,
    required this.extProp1,
    required this.extProp2,
  });

  Map<String, dynamic> toMap() {
    return {
      'username': username,
      'password': password,
      'firstName': firstName,
      'lastName': lastName,
      'phoneNumber': phoneNumber,
      'email': email,
      'gender': gender,
      'birthDate': birthDate,
      'language': language,
      'country': country,
      'zipCode': zipCode,
      'companyName': companyName,
      'civilStatus': civilStatus,
      'phoneVerified': phoneVerified,
      'emailVerified': emailVerified,
      'ppd': ppd,
      'profiling': profiling,
      'custom': custom,
      'policies': policies,
      'document': document.toMap(), // assuming CustomerDocument has toMap()
      'lock': lock,
      'extId': extId,
      'extProp1': extProp1,
      'extProp2': extProp2,
    };
  }
}

class CustomerDocument {
  String documentType;
  String documentNumber;

  CustomerDocument({
    required this.documentType,
    required this.documentNumber,
  });

  Map<String, dynamic> toMap() {
    return {
      'documentType': documentType,
      'documentNumber': documentNumber,
    };
  }
}

class CustomerCreateResponse {
  String status;
  String generated;
  String id;
  String organizationId;
  String locationId;
  String hotspotId;
  String username;
  String password;
  int mailSent;

  CustomerCreateResponse({
    required this.status,
    required this.generated,
    required this.id,
    required this.organizationId,
    required this.locationId,
    required this.hotspotId,
    required this.username,
    required this.password,
    required this.mailSent,
  });
}

class FlutterCloud4wiSdk {
  static const MethodChannel _channel = MethodChannel('flutter_cloud4wi_sdk');

  static Future<CustomerCreateResponse> createCustomer(
      Customer customer,
      String deduplicateAttribute,
      ) async {
    try {
      final response = await _channel.invokeMethod('createCustomer', {
        'customer': customer.toMap(),
        'deduplicateAttribute': deduplicateAttribute,
      });

      // Handle the response here if needed
      return CustomerCreateResponse(
        status: response['status'],
        generated: response['generated'],
        id: response['id'],
        organizationId: response['organizationId'],
        locationId: response['locationId'],
        hotspotId: response['hotspotId'],
        username: response['username'],
        password: response['password'],
        mailSent: response['mailSent'],
      );
    } catch (e) {
      throw Exception('Failed to create customer: $e');
    }
  }
}

Using the Plugin in Your Flutter App

  1. Add Plugin Dependency:

    • In your app's pubspec.yaml:

      dependencies:
        flutter:
          sdk: flutter
        flutter_cloud4wi_sdk:
          path: ../flutter_cloud4wi_sdk # Adjust the path accordingly
  2. In app folder call to fetch dependencies listed :

    flutter pub get
  3. Configure single project (ios and Android):

  4. Import and Use the Plugin:

    import 'package:flutter_cloud4wi_sdk/flutter_cloud4wi_sdk.dart';
    
    ...
    Customer customer = Customer(
            username: 'johndoe',
            password: 'securepassword123',
            firstName: 'John',
            lastName: 'Doe',
            phoneNumber: '1234567890',
            email: 'john.doe@example.com',
            gender: 'Male',
            birthDate: '1990-01-01',
            language: 'en',
            country: 'USA',
            zipCode: '12345',
            companyName: 'Example Company',
            civilStatus: 'Single',
            phoneVerified: true,
            emailVerified: true,
            ppd: false,
            profiling: true,
            custom: {},
            policies: {},
            document: CustomerDocument(
              documentType: 'Passport',
              documentNumber: '123456789',
            ),
            lock: false,
            extId: 'external_id_001',
            extProp1: 'extProp1_value',
            extProp2: 'extProp2_value',
          );
    
          String deduplicateAttribute = 'email';
    
          try {
            CustomerCreateResponse response =
                await FlutterCloud4wiSdk.createCustomer(
              customer,
              'email',
            );
            print("Customer created successfully: ${response.id}");
    
          } catch (error) {
            print("Error creating customer: $error");
    
          }
    ...

Testing the Integration

  1. Run on iOS Simulator or Device:

    • Ensure that all capabilities and permissions are correctly set.

    • Monitor the Xcode console for any runtime errors.

  2. Run on Android Emulator or Device:

    • Check that all permissions are granted.

    • Use adb logcat to view logs and debug issues.

  3. Validate createCustomer Functionality:

    • Verify that customers are being created successfully.

    • Handle any errors gracefully.

For more detailed information on SDK features and methods, please refer to the official Cloud4Wi SDK documentation:

Useful references:

Last updated