Flutter外掛開發例子分享到facebook和twitter

WLDNick發表於2019-04-09

請看原文更詳細:tryenough.com/flutter-plu…

這個活生生的例子會教你開發flutter外掛,功能是封裝Android和iOS端的分享到facebook和twitter的flutter介面。使用的分別是兩端的系統分享功能,不需要整合facebook和twitter 的 sdk。

例子外掛網址:pub.dartlang.org/packages/fl…

展示一下樣式:

ios 中分享到facebook:

Flutter外掛開發例子分享到facebook和twitter

android中分享到facebook

Flutter外掛開發例子分享到facebook和twitter

請看原文更詳細:tryenough.com/flutter-plu…

開始開發外掛

步驟一:建立外掛專案

這裡用的Android studio建立的專案,可以直接建立flutter plugin專案,你也可以用命令建立:

flutter create --org com.example --template=plugin "plugin_name"
複製程式碼

將上面的“plugin_name”換成你的外掛名字就行了,我這個外掛名字叫flutter_share_go,所以命令就是:

flutter create --org com.example --template=plugin flutter_share_go
複製程式碼

這裡沒有支援swift和kotlin,原因是使用外掛的很多專案可能並不支援,以免造成不必要的麻煩,但是你仍然可以選擇支援,命令如下:

flutter create --template=plugin -i swift -a kotlin flutter_share_go
複製程式碼

檢視建立好的專案結構:

Flutter外掛開發例子分享到facebook和twitter

**Android資料夾中:**Android端原生的程式碼 **iOS資料夾中:**iOS端原生的程式碼 **example檔案:**是方便測試你的外掛的例子程式碼 **lib檔案:**外掛對原生介面的封裝,也就是直接在dart程式碼中呼叫的介面

分別在Android studio和xcode中編輯Android和iOS程式碼

先在Android studio中編寫Android部分程式碼

用Android studio開啟專案中的android資料夾,因為此時缺少flutter庫依賴,需要配置一下:

在專案根目錄建立一個libs資料夾,用來存放flutter庫,flutter庫可以到你電腦的flutter sdk路徑中尋找:

/bin/cache/artifacts/engine
複製程式碼

在engine路徑下有很多的android支援庫,隨便拷貝一個Android平臺的庫到libs資料夾下,右鍵flutter.jar,彈出選單選擇Add As Library...。這裡不用擔心,我們等下設定一下讓它只是編譯時使用,不會打包進來。

Flutter外掛開發例子分享到facebook和twitter

然後點選選單File/Project Structure...,找到flutter_text_plugin的Dependencies中,將flutter庫的Scope從Implementation改成Compile Only。

Flutter外掛開發例子分享到facebook和twitter

開始新增Android程式碼 新增如下兩個檔案:

PackageUtils.java 工具類

package com.doglobal.flutter_share_go;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

public class PackageUtils {

    public static boolean isPkgInstalled(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        android.content.pm.ApplicationInfo info = null;
        try {
            info = context.getPackageManager().getApplicationInfo(packageName, 0);
            return info != null;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void goDownloadPage(Context context, String pkgName) {
        Context app = context.getApplicationContext();
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=" + pkgName));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            app.startActivity(intent);
        } catch (android.content.ActivityNotFoundException anfe) {
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=" + pkgName));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            app.startActivity(intent);
        }
    }
}

複製程式碼

ShareHelper.java 工具類

package com.doglobal.flutter_share_go;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

public class ShareHelper {

    public static final String CHANNEL_FACEBOOK_PKG_NAME = "com.facebook.katana";
    public static final String CHANNEL_TWITTER_PKG_NAME = "com.twitter.android";

    public static void shareMain(Activity activity, String shareText) {
        shareText(activity, null, null, shareText, null, "");
    }

    public static void shareTextToChannel(Activity activity,String pkgName, String shareText,
                                          String shareUrl) {
        if (PackageUtils.isPkgInstalled(activity, pkgName)) {
            shareText(activity, null, null, shareText, pkgName, shareUrl);
        } else {
            PackageUtils.goDownloadPage(activity, pkgName);
        }
    }

    /**
     * @param dlgTitle 選擇彈框標題
     * @param subject  分享主題
     * @param shareText  分享內容
     */
    public static void shareText(Activity activity, String dlgTitle, String subject,
                                 String shareText, String pkgName, String shareUrl) {
        if (shareText == null || "".equals(shareText)) {
            return;
        }
        String content = shareText + ": " + shareUrl + " .";
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("text/plain");
        if (!TextUtils.isEmpty(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }

        intent.putExtra(Intent.EXTRA_TEXT, content);

        if (!TextUtils.isEmpty(pkgName)) {
            intent.setPackage(pkgName);
        }

        // 設定彈出框標題
        if (TextUtils.isEmpty(dlgTitle)) { // 自定義標題
            Intent chooser = Intent.createChooser(intent, dlgTitle);
            chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(chooser);
        } else { // 系統預設標題
            activity.startActivity(intent);
        }
    }
}

複製程式碼

然後在FlutterShareGoPlugin.java檔案中新增呼叫邏輯。 這個檔案就是java端對dart端的呼叫介面。我們先來看下程式碼,再進行解析:

package com.doglobal.flutter_share_go;

import android.app.Activity;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** FlutterShareGoPlugin */
public class FlutterShareGoPlugin implements MethodCallHandler {

  private Activity mActivity; //分析一
  private FlutterShareGoPlugin(Activity context) {
    mActivity = context;
  }

  /** Plugin registration. */
  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_share_go");
    channel.setMethodCallHandler(new FlutterShareGoPlugin(registrar.activity()));
  }

  @Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("shareToFBPlatform")) {  //分析二
      String content = call.argument("shareContent");
      String shareUrl = call.argument("shareUrl");
      ShareHelper.shareTextToChannel(mActivity, ShareHelper.CHANNEL_FACEBOOK_PKG_NAME, content, shareUrl);
    } else if (call.method.equals("shareToTwitterPlatform")) {
      String content = call.argument("shareContent");
      String shareUrl = call.argument("shareUrl");
      ShareHelper.shareTextToChannel(mActivity, ShareHelper.CHANNEL_TWITTER_PKG_NAME, content, shareUrl);
    }
    else {
      result.notImplemented();
    }
  }

}

複製程式碼

請看原文更詳細:tryenough.com/flutter-plu…

  • 分析一 我們新增一個構造方法,用來儲存activity

  • 分析二 在方法onMethodCall中根據dart傳遞過來的方法名呼叫java端不同的程式碼邏輯

至此,Android端程式碼就告一段落了。

iOS端開發,在xcode中開發

Flutter外掛開發例子分享到facebook和twitter

如圖,我們在Android studio中開啟一個iOS檔案,在右上角會有用xcode開啟的按鈕,我們點選開啟就可以用xcode編輯了。

Flutter外掛開發例子分享到facebook和twitter

開啟專案新增上圖中的檔案:

FlutterShareGoPlugin.m檔案

#import "FlutterShareGoPlugin.h"
#import "ShareHelper.h"
#import <Social/Social.h>


@interface FlutterShareGoPlugin()
@property (nonatomic, strong)UIViewController * rootViewController;
@end

@implementation FlutterShareGoPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_share_go"
            binaryMessenger:[registrar messenger]];
  FlutterShareGoPlugin* instance = [[FlutterShareGoPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {

  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  }
  else if ([@"shareToFBPlatform" isEqualToString:call.method]) {
      NSDictionary *arguments = [call arguments];
      NSString * shareContent = arguments[@"shareContent"];
      NSString * shareUrl = arguments[@"shareUrl"];
      [ShareHelper shareToPlatformType:SLServiceTypeFacebook withContent:shareContent withShareUrl:shareUrl];
      result(nil);
  }
  else if ([@"shareToTwitterPlatform" isEqualToString:call.method]) {
      NSDictionary *arguments = [call arguments];
      NSString * shareContent = arguments[@"shareContent"];
      NSString * shareUrl = arguments[@"shareUrl"];
      [ShareHelper shareToPlatformType:SLServiceTypeTwitter withContent:shareContent withShareUrl:shareUrl];
      result(nil);
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}
@end

複製程式碼

PackageUtil.h


#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface PackageUtil : NSObject

// Is intalled specific app or not
+ (BOOL)isInstalledWithUrlScheme:(NSString *)urlScheme;

@end

NS_ASSUME_NONNULL_END
複製程式碼

PackageUtil.m

#import "PackageUtil.h"

@implementation PackageUtil

+ (BOOL)isInstalledWithUrlScheme:(NSString *)urlScheme {
    if (urlScheme == nil || urlScheme.length == 0) {
        return false;
    }
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlScheme]];
}


@end

複製程式碼

ShareHelper.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface ShareHelper : NSObject
+(void)shareToPlatformType:(NSString *)platformType withContent:(NSString *)content withShareUrl:(NSString*)url;
@end

NS_ASSUME_NONNULL_END

複製程式碼

ShareHelper.m


#import "ShareHelper.h"
#import <Social/Social.h>
#import "PackageUtil.h"

@implementation ShareHelper

/*
 SOCIAL_EXTERN NSString *const SLServiceTypeTwitter NS_AVAILABLE(10_8, 6_0);//Twitter
 SOCIAL_EXTERN NSString *const SLServiceTypeFacebook NS_AVAILABLE(10_8, 6_0);//Facebook
 SOCIAL_EXTERN NSString *const SLServiceTypeSinaWeibo NS_AVAILABLE(10_8, 6_0);
 SOCIAL_EXTERN NSString *const SLServiceTypeTencentWeibo NS_AVAILABLE(10_9, 7_0);
 SOCIAL_EXTERN NSString *const SLServiceTypeLinkedIn NS_AVAILABLE(10_9, NA);
 */
+(void)shareToPlatformType:(NSString *)platformType withContent:(NSString *)content withShareUrl:(NSString*)url{
    if (platformType == nil || platformType.length == 0) {
        NSLog(@"unspecified platform");
        return;
    }
    if([platformType isEqualToString:SLServiceTypeFacebook] && ![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id284882215"]];
        NSLog(@"UnInstall facebook");
        return;
    }
    if([platformType isEqualToString:SLServiceTypeTwitter] && ![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"twitter://"]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id333903271"]];
        NSLog(@"UnInstall twitter");
        return;
    }
    // create controller for ServiceType
    SLComposeViewController *composeVC = [SLComposeViewController composeViewControllerForServiceType:platformType];
    // image
    // [composeVC addImage:[UIImage imageNamed:@"Nameless"]];
    // content
    [composeVC setInitialText:content];
    // share url
    [composeVC addURL:[NSURL URLWithString:url]];
    // share controller
    if([[[UIApplication sharedApplication] keyWindow].rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *vc = (UINavigationController *)[[UIApplication sharedApplication] keyWindow].rootViewController;
        [vc pushViewController:composeVC animated:YES];
    } else {
        UINavigationController *vc = (UINavigationController *)[[UIApplication sharedApplication] keyWindow].rootViewController;
        [vc presentViewController:composeVC animated:YES completion:nil];
    }
    // callback user hanlder
    composeVC.completionHandler = ^(SLComposeViewControllerResult result){
        if (result == SLComposeViewControllerResultDone) {
        }
        else if (result == SLComposeViewControllerResultCancelled) {
        }
    };
}

@end
複製程式碼

請看原文更詳細:tryenough.com/flutter-plu…

最後需要我們在plist檔案中新增白名單,用於iOS9適配,檢視是否安裝了facebook和twitter:

Flutter外掛開發例子分享到facebook和twitter

iOS 部分程式碼到此也告一段落了。

新增flutter介面,供dart程式碼呼叫

開啟專案中lib資料夾下的flutter_share_go檔案

Flutter外掛開發例子分享到facebook和twitter

FlutterShareGo.dart

import 'dart:async';

import 'package:flutter/services.dart';

class FlutterShareGo {
  static const MethodChannel _channel =
      const MethodChannel('flutter_share_go');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<void> shareToFBPlatform(String shareContent, String shareUrl) async {
    assert(shareContent != null);
    assert(shareContent.isNotEmpty);
    final Map<String, dynamic> params = <String, dynamic> {
      'shareContent': shareContent,
      'shareUrl':shareUrl,
    };
    await _channel.invokeMethod("shareToFBPlatform", params);
  }

  static Future<void> shareToTwitterPlatform(String shareContent, String shareUrl) async {
    assert(shareContent != null);
    assert(shareContent.isNotEmpty);
    final Map<String, dynamic> params = <String, dynamic> {
      'shareContent': shareContent,
      'shareUrl':shareUrl,
    };
    await _channel.invokeMethod("shareToTwitterPlatform", params);
  }
}

複製程式碼

flutter端程式碼就告一段落了。

測試外掛:

開啟專案中example檔案下的main.dart:

Flutter外掛開發例子分享到facebook和twitter

main.dart

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

import 'package:flutter/services.dart';
import 'package:flutter_share_go/flutter_share_go.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await FlutterShareGo.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Text('Running on: $_platformVersion\n'),
            RaisedButton(
              child: Text("分享到facebook按鈕"),
              color: Colors.red,
              onPressed: () {
                FlutterShareGo.shareToFBPlatform("test share to fb content", "http://tryenough.com");
              },
            )
          ],
        ),
      ),
    );
  }
}

複製程式碼

執行就會出現文章最上面的效果了。祝你順利。

最後釋出可以參照如下步驟:

執行命令,並解決所有出現的問題:

 flutter packages pub publish --dry-run
複製程式碼

問題解決完就可以釋出了,命令:

 flutter packages pub publish 
複製程式碼

請看原文更詳細:tryenough.com/flutter-plu…

相關文章