【发布时间】:2021-02-10 09:17:29
【问题描述】:
Flutter - 如何使用 Gmail Api 阅读电子邮件?
我正在研究 googleapis https://pub.dev/packages/googleapis,但没有关于它是如何完成的文档。
谁能给我一个例子或教程?
【问题讨论】:
标签: flutter
Flutter - 如何使用 Gmail Api 阅读电子邮件?
我正在研究 googleapis https://pub.dev/packages/googleapis,但没有关于它是如何完成的文档。
谁能给我一个例子或教程?
【问题讨论】:
标签: flutter
这是一个完整的例子:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:zapit/models/appState.dart';
import 'package:googleapis/gmail/v1.dart' as gMail;
class GmailApiScreen extends StatefulWidget {
@override
_GmailApiScreenState createState() => _GmailApiScreenState();
}
class _GmailApiScreenState extends State<GmailApiScreen> {
gMail.GmailApi gmailApi;
List<gMail.Message> messagesList = [];
Future waitForInit;
@override
void initState() {
super.initState();
waitForInit = init();
}
init() async {
final authHeaders = await AppState.state.googleUser.authHeaders;
final authenticateClient = GoogleAuthClient(authHeaders);
gmailApi = gMail.GmailApi(authenticateClient);
gMail.ListMessagesResponse results =
await gmailApi.users.messages.list("me");
for (gMail.Message message in results.messages) {
gMail.Message messageData =
await gmailApi.users.messages.get("me", message.id);
messagesList.add(messageData);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("email")),
body: buildFutureBuilder(),
);
}
FutureBuilder buildFutureBuilder() {
return FutureBuilder(
future: waitForInit,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
List<Widget> messageTxt = [];
for (var m in messagesList) {
messageTxt.add(Text(m.snippet));
}
return Column(
children:messageTxt,
);
} else {
// Otherwise, display a loading indicator.
return Center(child: CircularProgressIndicator());
}
});
}
}
class GoogleAuthClient extends http.BaseClient {
final Map<String, String> _headers;
final http.Client _client = new http.Client();
GoogleAuthClient(this._headers);
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _client.send(request..headers.addAll(_headers));
}
}
googleUser 是通过在以下代码中调用 ensureLoggedInOnStartUp 创建的:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/gmail/v1.dart' as gMail;
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn.standard(scopes: [gMail.GmailApi.GmailReadonlyScope]);
Future<GoogleSignInAccount> ensureLoggedInOnStartUp() async {
// That class has a currentUser if there's already a user signed in on
// this device.
try {
GoogleSignInAccount googleSignInAccount = googleSignIn.currentUser;
if (googleSignInAccount == null) {
// but if not, Google should try to sign one in whos previously signed in
// on this phone.
googleSignInAccount = await googleSignIn.signInSilently();
if (googleSignInAccount == null) return null;
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final User currentUser = await _auth.currentUser;
assert(user.uid == currentUser.uid);
return googleSignInAccount;
}
} catch (e) { //on PlatformException
print(e);
}
return null;
}
Future<GoogleSignInAccount> signInWithGoogle() async {
try {
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
// throws FirebaseException when no internet connection
final UserCredential authResult = await _auth.signInWithCredential(credential);
final User user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final User currentUser = await _auth.currentUser;
assert(user.uid == currentUser.uid);
return googleSignInAccount;
} catch (e,s) {
print(e);
print(s);
return null;
}
}
void signOutGoogle() async {
await googleSignIn.signOut();
print("User Sign Out");
}
【讨论】: