Flutter Facebook登录集成插件flutter_facebook_pro的使用
Flutter Facebook登录集成插件flutter_facebook_pro的使用
Facebook SDK For Flutter
flutter_facebook_pro 允许你获取 深度链接 和 延迟深度链接,并记录 Facebook 应用事件。
该插件是使用最新的 Facebook SDK 创建的,以支持 iOS 14。目前该插件支持 iOS 和 Android 的应用事件和深度链接。
前置条件
首先,如果你还没有一个 Facebook 开发者账号,你需要在 Facebook 开发者平台创建一个应用,并获取你的应用 ID(以下称为 [APP_ID])。
对于 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/>
对于 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-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。
完整示例代码
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_facebook_pro/flutter_facebook_pro.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _deepLinkUrl = 'Unknown';
FlutterFacebookPro? facebookDeepLinks;
bool isAdvertisingTrackingEnabled = false;
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
// 平台消息是异步的,所以我们初始化在一个异步方法中。
Future<void> initPlatformState() async {
String? deepLinkUrl;
// 平台消息可能会失败,所以我们使用 try/catch 来捕获 PlatformException。
try {
facebookDeepLinks = FlutterFacebookPro();
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](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Center(
child: Column(
children: [
Text('运行在: $_deepLinkUrl\n'),
TextButton(onPressed: () async => await logViewContent(), child: Text("触发查看内容")),
TextButton(onPressed: () async => await logActivateApp(), child: Text("触发激活应用")),
TextButton(onPressed: () async => await logAddToCart(), child: Text("触发添加到购物车")),
TextButton(onPressed: () async => await logAddToWishlist(), child: Text("触发添加到愿望清单")),
TextButton(
onPressed: () async => await logCompleteRegistration(), child: Text("触发完成注册")),
TextButton(onPressed: () async => await logPurchase(), child: Text("触发购买")),
TextButton(onPressed: () async => await logSearch(), child: Text("触发搜索")),
TextButton(onPressed: () async => await logInitiateCheckout(), child: Text("触发发起结账")),
TextButton(
onPressed: () async => await logEvent(
eventName: "button_clicked",
parameters: {
'button_id': 'the_clickme_button',
},
),
child: Text("触发按钮点击")),
TextButton(
onPressed: () async => await logEvent(
eventName: "fb_mobile_add_payment_info",
valueToSum: 55,
parameters: {
'SUCCESS': "true",
},
),
child: Text("触发支付信息点击")),
Platform.isIOS
? TextButton(
onPressed: () async => await setAdvertiserTracking(),
child: isAdvertisingTrackingEnabled
? Text("禁用广告跟踪")
: Text("启用广告跟踪"))
: Container(),
],
),
),
),
);
}
}
更多关于Flutter Facebook登录集成插件flutter_facebook_pro的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Facebook登录集成插件flutter_facebook_pro的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用中集成Facebook登录功能,可以使用 flutter_facebook_auth 插件。flutter_facebook_auth 是一个非常常用的插件,用于在Flutter应用中实现Facebook登录功能。以下是如何在Flutter应用中使用 flutter_facebook_auth 插件的步骤。
1. 添加依赖
首先,在 pubspec.yaml 文件中添加 flutter_facebook_auth 插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_facebook_auth: ^4.4.1+1
然后,运行 flutter pub get 来安装依赖。
2. 配置 Facebook 开发者平台
在 Facebook 开发者平台上创建一个应用,并获取应用的 App ID 和 App Secret。
- 进入 Facebook 开发者平台。
- 创建一个新的应用。
- 在
设置 > 基本中获取App ID和App Secret。
3. 配置 Android 项目
在 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>
在 android/app/src/main/AndroidManifest.xml 文件中添加以下内容:
<application android:label="Your App Name" ...>
<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="Your 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>
4. 配置 iOS 项目
在 ios/Runner/Info.plist 文件中添加以下内容:
<key>CFBundleURLTypes</key>
<array>
<dict>
<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>Your App Name</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
5. 实现 Facebook 登录功能
在 Flutter 代码中实现 Facebook 登录功能:
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: FacebookLoginDemo(),
);
}
}
class FacebookLoginDemo extends StatefulWidget {
[@override](/user/override)
_FacebookLoginDemoState createState() => _FacebookLoginDemoState();
}
class _FacebookLoginDemoState extends State<FacebookLoginDemo> {
Map<String, dynamic>? _userData;
Future<void> _login() async {
final LoginResult result = await FacebookAuth.instance.login();
if (result.status == LoginStatus.success) {
final AccessToken accessToken = result.accessToken!;
final userData = await FacebookAuth.instance.getUserData();
setState(() {
_userData = userData;
});
} else {
print(result.status);
print(result.message);
}
}
Future<void> _logOut() async {
await FacebookAuth.instance.logOut();
setState(() {
_userData = null;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Facebook Login Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_userData != null
? Text('Logged in as ${_userData!['name']}')
: Text('Not logged in'),
SizedBox(height: 20),
ElevatedButton(
onPressed: _login,
child: Text('Login with Facebook'),
),
SizedBox(height: 20),
_userData != null
? ElevatedButton(
onPressed: _logOut,
child: Text('Logout'),
)
: Container(),
],
),
),
);
}
}


LinkedIn
GitHub