Flutter Twitter登录插件twitter_login的使用
Flutter Twitter登录插件twitter_login的使用
twitter_login #
Flutter Twitter Login Plugin
Requirements #
- Dart sdk: “>=2.12.0-0 <3.0.0”
- flutter: “>=1.25.0-8.1.pre”
- Android: minSdkVersion 17 and add support for androidx
- iOS: --ios-language swift, Xcode version >= 11
Twitter Configuration #
创建TwitterApp需要在Twitter Developer注册应用。
此插件需要设置回调URL。请在Twitter Developers中注册一个不同的回调URL:
app_name://
如果API未设置为获取电子邮件,电子邮件可能为空。如果您想使用电子邮件,请开启“Request email address from users”。
Android Configuration #
Add intent filters for incoming links #
您需要替换scheme为Callback URLs。
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "example://gizmos” -->
<!-- Registered Callback URLs in TwitterApp -->
<data android:scheme="example"
android:host="gizmos" /> <!-- host is option -->
</intent-filter>
Supporting the new Android plugins APIs #
如果您的项目是在Flutter版本1.12之前创建的,则需要确保更新项目以使用新的Java嵌入API。请确保启用了flutter_embedding v2。在清单文件中添加以下代码:
<meta-data
android:name="flutterEmbedding"
android:value="2" />
iOS Configuration #
Add URLScheme #
您需要替换示例中的Callback URLs。
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array>
<!-- Registered Callback URLs in TwitterApp -->
<string>example</string>
</array>
</dict>
</array>
Example code #
完整示例应用程序请参见twitter_login/example。
Usage #
要在您的项目中使用此插件,请将twitter_login
作为依赖项添加到pubspec.yaml
文件中。
示例代码 #
import 'package:flutter/material.dart';
import 'package:twitter_login/twitter_login.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final String apiKey = 'S9GzajUq5r5V4VIvT0V0M1HrP';
final String apiSecretKey = 'U6NhHZxqRahi2StQYLz6mVhMZEow1HsaZ6igkNgJa47dfQ4fhI';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('twitter_login example app'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: ListView(
children: [
const SizedBox(height: 24),
const Text(
'Twitter API v1.1 is not available when creating a new application in twitter developer from November 15, 2021.\n'
'Check the Twitter Developer to see if it supports v1.1 or v2.',
),
const SizedBox(height: 24),
Image.asset(
'assets/twitter_dashboard.png',
width: double.infinity,
),
const SizedBox(height: 24),
Center(
child: TextButton(
child: const Text('use Twitter API v1.1'),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty.all<Color>(Colors.blueAccent),
minimumSize: MaterialStateProperty.all<Size>(const Size(160, 48)),
),
onPressed: () async {
await login();
},
),
),
const SizedBox(height: 24),
Center(
child: TextButton(
child: const Text('use Twitter API v2.0'),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty.all<Color>(Colors.blueAccent),
minimumSize: MaterialStateProperty.all<Size>(const Size(160, 48)),
),
onPressed: () async {
await loginV2();
},
),
),
],
),
),
),
);
}
/// Use Twitter API v1.1
Future login() async {
final twitterLogin = TwitterLogin(
/// Consumer API keys
apiKey: apiKey,
/// Consumer API Secret keys
apiSecretKey: apiSecretKey,
/// Registered Callback URLs in TwitterApp
/// Android is a deeplink
/// iOS is a URLScheme
redirectURI: 'example://',
);
/// Forces the user to enter their credentials
/// to ensure the correct users account is authorized.
/// If you want to implement Twitter account switching, set [force_login] to true
/// login(forceLogin: true);
final authResult = await twitterLogin.login();
switch (authResult.status) {
case TwitterLoginStatus.loggedIn:
// success
print('====== Login success ======');
print(authResult.authToken);
print(authResult.authTokenSecret);
break;
case TwitterLoginStatus.cancelledByUser:
// cancel
print('====== Login cancel ======');
break;
case TwitterLoginStatus.error:
case null:
// error
print('====== Login error ======');
break;
}
}
/// Use Twitter API v2.
Future loginV2() async {
final twitterLogin = TwitterLogin(
/// Consumer API keys
apiKey: apiKey,
/// Consumer API Secret keys
apiSecretKey: apiSecretKey,
/// Registered Callback URLs in TwitterApp
/// Android is a deeplink
/// iOS is a URLScheme
redirectURI: 'example://',
);
/// Forces the user to enter their credentials
/// to ensure the correct users account is authorized.
/// If you want to implement Twitter account switching, set [force_login] to true
/// login(forceLogin: true);
final authResult = await twitterLogin.loginV2();
switch (authResult.status) {
case TwitterLoginStatus.loggedIn:
// success
print('====== Login success ======');
break;
case TwitterLoginStatus.cancelledByUser:
// cancel
print('====== Login cancel ======');
break;
case TwitterLoginStatus.error:
case null:
// error
print('====== Login error ======');
break;
}
}
}
更多关于Flutter Twitter登录插件twitter_login的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Twitter登录插件twitter_login的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter应用中使用twitter_login
插件来实现Twitter登录功能的代码示例。这个插件允许你通过Twitter进行身份验证并获取用户的OAuth令牌。
步骤 1: 添加依赖
首先,在你的pubspec.yaml
文件中添加twitter_login
插件的依赖:
dependencies:
flutter:
sdk: flutter
twitter_login: ^1.1.4 # 请检查最新版本号
步骤 2: 配置Twitter应用
- 前往Twitter开发者门户并创建一个新的应用。
- 获取API密钥(API Key)和API密钥秘密(API Key Secret)。
- 在Twitter开发者门户中,设置回调URL(Callback URL)。对于Flutter应用,这通常是一个占位符,如
http://localhost
,因为实际的回调处理将在你的应用中完成。
步骤 3: 配置Android
在你的android/app/src/main/AndroidManifest.xml
文件中,添加以下权限和Twitter SDK的配置:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
... >
<meta-data
android:name="com.twitter.sdk.android.CONSUMER_KEY"
android:value="YOUR_TWITTER_API_KEY"/>
<meta-data
android:name="com.twitter.sdk.android.CONSUMER_SECRET"
android:value="YOUR_TWITTER_API_SECRET"/>
<activity
android:name="com.twitter.sdk.android.core.identity.OAuthActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<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="twitterkitYOUR_TWITTER_API_KEY" android:host="callback"/>
</intent-filter>
</activity>
</application>
确保将YOUR_TWITTER_API_KEY
和YOUR_TWITTER_API_SECRET
替换为你从Twitter开发者门户获取的实际值,并将twitterkitYOUR_TWITTER_API_KEY
中的YOUR_TWITTER_API_KEY
替换为你的API密钥(去掉前缀twitterkit
)。
步骤 4: 配置iOS
在你的ios/Runner/Info.plist
文件中,添加以下配置:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>twitterkit-YOUR_TWITTER_API_KEY</string>
<string>twitterkitYOUR_TWITTER_API_KEY</string> <!-- 注意这个格式也需要添加 -->
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twitter</string>
<string>twitterauth</string>
</array>
同样,将YOUR_TWITTER_API_KEY
替换为你的实际API密钥。
步骤 5: 编写Flutter代码
在你的Flutter应用中,使用twitter_login
插件进行Twitter登录。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:twitter_login/twitter_login.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TwitterLoginScreen(),
);
}
}
class TwitterLoginScreen extends StatefulWidget {
@override
_TwitterLoginScreenState createState() => _TwitterLoginScreenState();
}
class _TwitterLoginScreenState extends State<TwitterLoginScreen> {
final TwitterLogin _twitterLogin = TwitterLogin(
apiKey: "YOUR_TWITTER_API_KEY",
apiSecretKey: "YOUR_TWITTER_API_SECRET",
redirectURI: "http://localhost"
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Twitter Login Example"),
),
body: Center(
child: ElevatedButton(
onPressed: _handleLogin,
child: Text("Login with Twitter"),
),
),
);
}
void _handleLogin() async {
final result = await _twitterLogin.logIn();
switch (result.status) {
case TwitterLoginStatus.loggedIn:
String sessionId = result.sessionId;
String userId = result.userId;
String userName = result.userName;
print("User ID: $userId");
print("User Name: $userName");
print("Session ID: $sessionId");
// 在这里处理登录后的逻辑,比如将用户信息发送到服务器
break;
case TwitterLoginStatus.cancelledByUser:
print("Login cancelled by user.");
break;
case TwitterLoginStatus.error:
print("Error occurred: ${result.errorMessage}");
break;
}
}
}
确保将YOUR_TWITTER_API_KEY
和YOUR_TWITTER_API_SECRET
替换为你的实际API密钥和密钥秘密。
结论
以上代码展示了如何在Flutter应用中使用twitter_login
插件来实现Twitter登录功能。这包括添加依赖、配置Twitter应用、配置Android和iOS项目以及编写Flutter代码来处理登录逻辑。