Flutter社交媒体集成插件flutter_facebook_sdk的使用
Flutter社交媒体集成插件flutter_facebook_sdk的使用
Facebook Sdk For Flutter
facebook_sdk_flutter
允许您获取深度链接、延迟深度链接并记录Facebook应用程序事件。此插件是使用最新的Facebook SDK创建的,以支持iOS 14。目前,该插件支持iOS和Android的应用程序事件和深度链接。
Prerequisites(先决条件)
首先,如果您还没有,请务必在Facebook开发者平台创建一个应用:https://developers.facebook.com/。获取您的应用ID(下文中的[APP_ID])。
For IOS(针对iOS)
如果您的代码中没有CFBundleURLTypes,在最终元素前添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb[APP_ID]</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>[APP_ID]</string>
<key>FacebookDisplayName</key>
<string>[DISPLAY_NAME]</string>
<key>FacebookAutoLogAppEventsEnabled</key>
<true/>
<key>FacebookAdvertiserIDCollectionEnabled</key>
<true/>
For Android(针对Android)
向strings.xml文件中添加以下内容:
<string name="facebook_app_id">[APP_ID]</string>
<string name="fb_login_protocol_scheme">fb[APP_ID]</string>
向AndroidManifest.xml文件中的application元素添加以下meta标签:
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
在AndroidManifest.xml中添加以下元素:
<uses-permission android:name="android.permission.INTERNET"/>
不要忘了将[APP_ID]替换为您的应用程序ID。
示例代码
以下是使用flutter_facebook_sdk
的完整示例demo:
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_facebook_sdk/flutter_facebook_sdk.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _deepLinkUrl = 'Unknown';
FlutterFacebookSdk? facebookDeepLinks;
bool isAdvertisingTrackingEnabled = false;
@override
void initState() {
super.initState();
initPlatformState();
}
// 平台消息是异步的,因此我们在异步方法中初始化。
Future<void> initPlatformState() async {
String? deepLinkUrl;
try {
facebookDeepLinks = FlutterFacebookSdk();
facebookDeepLinks!.onDeepLinkReceived!.listen((event) {
setState(() {
_deepLinkUrl = event;
});
});
deepLinkUrl = await facebookDeepLinks!.getDeepLinkUrl;
setState(() {
_deepLinkUrl = deepLinkUrl!;
});
} on PlatformException {}
if (!mounted) return;
}
Future<void> logViewContent() async {
await facebookDeepLinks!.logViewedContent(
contentType: "Product",
contentData: "Nestle Milkpak",
contentId: "NST135",
currency: "PKR",
price: 160);
}
Future<void> logAddToCart() async {
await facebookDeepLinks!.logAddToCart(
contentType: "Product",
contentData: "Nestle Milkpak",
contentId: "NST135",
currency: "PKR",
price: 160);
}
Future<void> logAddToWishlist() async {
await facebookDeepLinks!.logAddToWishlist(
contentType: "Product",
contentData: "Nestle Milkpak",
contentId: "NST135",
currency: "PKR",
price: 160);
}
Future<void> logPurchase() async {
await facebookDeepLinks!.logPurhcase(amount: 669, currency: "PKR", params: {
'content-type': "product_group",
'num-items': 56,
});
}
Future<void> logCompleteRegistration() async {
await facebookDeepLinks!
.logCompleteRegistration(registrationMethod: "Number");
}
Future<void> logActivateApp() async {
await facebookDeepLinks!.logActivateApp();
}
Future<void> logSearch() async {
await facebookDeepLinks!.logSearch(
contentType: "Product",
contentData: "Nestle Milkpak",
contentId: "NST135",
searchString: "Habeeb",
success: false);
}
Future<void> logInitiateCheckout() async {
await facebookDeepLinks!.logInitiateCheckout(
contentType: "Product",
contentData: "Nestle Milkpak",
contentId: "NST135",
currency: "PKR",
numItems: 12,
paymentInfoAvailable: false,
totalPrice: 560,
);
}
Future<void> logEvent(
{required String eventName,
double? valueToSum,
dynamic? parameters}) async {
await facebookDeepLinks!.logEvent(
eventName: eventName, parameters: parameters, valueToSum: valueToSum);
}
Future<void> setAdvertiserTracking() async {
await facebookDeepLinks!
.setAdvertiserTracking(isEnabled: !isAdvertisingTrackingEnabled);
setState(() {
isAdvertisingTrackingEnabled = !isAdvertisingTrackingEnabled;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: [
Text('Running on: $_deepLinkUrl\n'),
TextButton(
onPressed: () async => await logViewContent(),
child: Text("Trigger View Content")),
TextButton(
onPressed: () async => await logActivateApp(),
child: Text("Trigger Activate App")),
TextButton(
onPressed: () async => await logAddToCart(),
child: Text("Trigger Add to cart")),
TextButton(
onPressed: () async => await logAddToWishlist(),
child: Text("Trigger Add to Wishlist")),
TextButton(
onPressed: () async => await logCompleteRegistration(),
child: Text("Trigger Complete Registration")),
TextButton(
onPressed: () async => await logPurchase(),
child: Text("Trigger Purchase")),
TextButton(
onPressed: () async => await logSearch(),
child: Text("Trigger Search")),
TextButton(
onPressed: () async => await logInitiateCheckout(),
child: Text("Trigger Initiate Checkout")),
TextButton(
onPressed: () async => await logEvent(
eventName: "button_clicked",
parameters: {
'button_id': 'the_clickme_button',
},
),
child: Text("Trigger Button Clicked")),
TextButton(
onPressed: () async => await logEvent(
eventName: "fb_mobile_add_payment_info",
valueToSum: 55,
parameters: {
'SUCCESS': "true",
},
),
child: Text("Trigger Payment Info Click")),
Platform.isIOS
? TextButton(
onPressed: () async => await setAdvertiserTracking(),
child: isAdvertisingTrackingEnabled
? Text("Disable Advertiser Tracking")
: Text("Enable Advertiser Tracking"))
: Container(),
],
),
),
),
);
}
}
以上代码展示了如何在Flutter项目中使用flutter_facebook_sdk
插件来实现各种Facebook事件的日志记录功能,并处理深度链接。您可以根据需要调整参数和逻辑,以适应您的具体应用场景。
更多关于Flutter社交媒体集成插件flutter_facebook_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter社交媒体集成插件flutter_facebook_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter应用中使用flutter_facebook_sdk
插件来实现Facebook登录功能的代码示例。这个示例将涵盖基本的初始化、登录流程以及获取用户数据。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加flutter_facebook_sdk
依赖:
dependencies:
flutter:
sdk: flutter
flutter_facebook_sdk: ^3.0.0 # 请检查最新版本号
然后运行flutter pub get
来安装依赖。
2. 配置Android和iOS
Android配置
在android/app/src/main/AndroidManifest.xml
中添加以下权限和Facebook的meta-data:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<!-- 其他配置 -->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="yourapp"
android:icon="@mipmap/ic_launcher">
<!-- Facebook SDK配置 -->
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
</manifest>
在android/app/src/main/res/values/strings.xml
中添加你的Facebook App ID:
<resources>
<string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
<string name="fb_login_protocol_scheme">fbYOUR_FACEBOOK_APP_ID</string>
</resources>
iOS配置
在ios/Runner/Info.plist
中添加以下配置:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>fbYOUR_FACEBOOK_APP_ID</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string>
<key>FacebookDisplayName</key>
<string>YourAppDisplayName</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
3. 初始化Facebook SDK
在你的main.dart
文件中初始化Facebook SDK:
import 'package:flutter/material.dart';
import 'package:flutter_facebook_sdk/flutter_facebook_sdk.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FacebookAppId.configure(appId: 'YOUR_FACEBOOK_APP_ID');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FacebookLoginPage(),
);
}
}
4. 实现登录功能
创建一个新的页面FacebookLoginPage
来处理登录逻辑:
import 'package:flutter/material.dart';
import 'package:flutter_facebook_sdk/flutter_facebook_sdk.dart';
import 'package:fluttertoast/fluttertoast.dart'; // 用于显示Toast消息
class FacebookLoginPage extends StatefulWidget {
@override
_FacebookLoginPageState createState() => _FacebookLoginPageState();
}
class _FacebookLoginPageState extends State<FacebookLoginPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Facebook Login'),
),
body: Center(
child: ElevatedButton(
onPressed: _loginWithFacebook,
child: Text('Login with Facebook'),
),
),
);
}
Future<void> _loginWithFacebook() async {
final result = await FacebookLogin.logInWithReadPermissions(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final accessToken = result.accessToken!;
// 使用accessToken获取用户信息
_getUserData(accessToken.token);
break;
case FacebookLoginStatus.cancelledByUser:
Fluttertoast.showToast(msg: 'Login cancelled by user.');
break;
case FacebookLoginStatus.error:
Fluttertoast.showToast(msg: result.error!.errorMessage);
break;
}
}
Future<void> _getUserData(String accessToken) async {
final graphResponse = await http.get(
Uri.parse('https://graph.facebook.com/me?fields=id,name,email&access_token=$accessToken'),
);
if (graphResponse.statusCode == 200) {
final userData = jsonDecode(graphResponse.body);
Fluttertoast.showToast(msg: 'User ID: ${userData['id']}, Name: ${userData['name']}, Email: ${userData['email']}');
} else {
Fluttertoast.showToast(msg: 'Error fetching user data.');
}
}
}
注意:上面的代码示例使用了http
包来发送GET请求,你需要在pubspec.yaml
中添加http
依赖:
dependencies:
http: ^0.13.3 # 请检查最新版本号
总结
这个示例展示了如何在Flutter应用中集成并使用flutter_facebook_sdk
插件来实现Facebook登录功能。这包括了依赖添加、Android和iOS的配置、Facebook SDK的初始化以及登录和获取用户数据的实现。确保你已经正确配置了Facebook开发者应用,并使用了正确的App ID。