Я использовал [google_sign_in 3.2.1] [1], вход и выход из Google, когда они находятся на одной странице (в одном классе).Может ли кто-нибудь объяснить, как перенести функциональность выхода из системы на другую страницу (имеющую другой класс), предпочтительнее на примере.
Мое меню навигации может направить пользователя на две страницы: «Домашняя страница», «Страница профиля».
Предположим, что пользователь сначала переходит на "Домашнюю страницу" со страницы аутентификации после успешного входа в Google.Затем пользователь использует «Меню навигации» на «Домашней странице», чтобы перейти на «Страницу профиля», где у него есть опция «Выйти»
Как мне заставить работать функцию «Выход из Google» - _handleSignOut ()на моей странице профиля.
1.Страница аутентификации
import 'dart:async';
import 'dart:convert' show json;
import "package:http/http.dart" as http;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
void main() {
runApp(
MaterialApp(
title: 'Google Sign In',
home: SignInDemo(),
),
);
}
class SignInDemo extends StatefulWidget {
@override
State createState() => SignInDemoState();
}
class SignInDemoState extends State<SignInDemo> {
GoogleSignInAccount _currentUser;
String _contactText;
@override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
setState(() {
_currentUser = account;
});
if (_currentUser != null) {
_handleGetContact();
}
});
_googleSignIn.signInSilently();
}
Future<Null> _handleGetContact() async {
setState(() {
_contactText = "Loading contact info...";
});
final http.Response response = await http.get(
'https://people.googleapis.com/v1/people/me/connections'
'?requestMask.includeField=person.names',
headers: await _currentUser.authHeaders,
);
if (response.statusCode != 200) {
setState(() {
_contactText = "People API gave a ${response.statusCode} "
"response. Check logs for details.";
});
print('People API ${response.statusCode} response: ${response.body}');
return;
}
final Map<String, dynamic> data = json.decode(response.body);
final String namedContact = _pickFirstNamedContact(data);
setState(() {
if (namedContact != null) {
_contactText = "I see you know $namedContact!";
} else {
_contactText = "No contacts to display.";
}
});
}
String _pickFirstNamedContact(Map<String, dynamic> data) {
final List<dynamic> connections = data['connections'];
final Map<String, dynamic> contact = connections?.firstWhere(
(dynamic contact) => contact['names'] != null,
orElse: () => null,
);
if (contact != null) {
final Map<String, dynamic> name = contact['names'].firstWhere(
(dynamic name) => name['displayName'] != null,
orElse: () => null,
);
if (name != null) {
return name['displayName'];
}
}
return null;
}
Future<Null> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<Null> _handleSignOut() async {
_googleSignIn.disconnect();
}
Widget _buildBody() {
if (_currentUser != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
leading: GoogleUserCircleAvatar(
identity: _currentUser,
),
title: Text(_currentUser.displayName),
subtitle: Text(_currentUser.email),
),
const Text("Signed in successfully."),
Text(_contactText),
RaisedButton(
child: const Text('SIGN OUT'),
onPressed: _handleSignOut,
),
RaisedButton(
child: const Text('REFRESH'),
onPressed: _handleGetContact,
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text("You are not currently signed in."),
RaisedButton(
child: const Text('SIGN IN'),
onPressed: _handleSignIn,
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
)
bottomNavigationBar: new BottomNavigator(),
);
}
}
2.Домашняя страница
import 'package:streaming_entertainment/movie_detail_navigation.dart';
class HomePage extends StatefulWidget {
HomePage({
Key key,
}) : super(key: key);
@override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
}
Widget welcomeMessage(){
return new Container(
width: 100.0,
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new Text(
"This is the the Home Page",
textAlign: TextAlign.center,
style: new TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
maxLines: 3,
textScaleFactor: 1.0
),
),
);
}
Widget homeUI(){
return new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
welcomeMessage(),
],
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomPadding: false,
body: new Container(
child : new Center(
child : homeUI(),
),
),
bottomNavigationBar: new BottomNavigator(),
);
}
}
2.Страница профиля
class ProfilePage extends StatefulWidget {
ProfilePage({
Key key,
}) : super(key: key);
@override
_ProfilePageState createState() => new _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
@override
void initState() {
super.initState();
}
_signOutFromGoogle() async {
// Google Sign Out
}
Widget welcomeMessage(){
return new Container(
width: 100.0,
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new Text(
"This is the the Profile Page",
textAlign: TextAlign.center,
style: new TextStyle(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
maxLines: 3,
textScaleFactor: 1.0
),
),
);
}
Widget logoutButton(){
return new FlatButton(
onPressed: (){
_signOutFromGoogle();
},
child: new Text('Sign Out'),
);
}
Widget profileUI(){
return new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
welcomeMessage(),
logoutButton(),
],
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomPadding: false,
body: new Container(
child : new Center(
child : profileUI(),
),
),
bottomNavigationBar: new BottomNavigator(),
);
}
}
2.Нижняя панель навигации
class BottomNavigator extends StatefulWidget {
BottomNavigator({
Key key,
}) : super(key: key);
@override
_BottomNavigatorState createState() => new _BottomNavigatorState();
}
class _BottomNavigatorState extends State<BottomNavigator> {
Widget navigationOptions(String imageUrl, var route, String optionName){
return new Container(
height: 40.0,
child: new GestureDetector(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
new Container(
padding: const EdgeInsets.all(1.0),
child: new Image.asset(
imageUrl,
color: Colors.black,
fit: BoxFit.cover,
width: 20.0,
height: 20.0,
),
),
new Container(
padding: const EdgeInsets.all(1.0),
child: new Text(
optionName,
textAlign: TextAlign.right,
style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
textScaleFactor: 0.75,
),
),
]
),
onTap: (){
print ("Move to Selected Page");
Navigator.of(context).push(route);
},
),
);
}
Widget universalNavigationBar(){
var routeHome = new MaterialPageRoute(builder: (BuildContext context) => new HomePage());
var routeProfile = new MaterialPageRoute(builder: (BuildContext context) => new ProfilePage());
return new BottomAppBar(
color: Colors.white, // new Color(0xFFFFB500)
child: new Container(
padding: const EdgeInsets.all(5.0),
child: new Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
navigationOptions("images/home.png", routeHome, "home"),
navigationOptions("images/profile.png", routeProfile, "profile"),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return universalNavigationBar();
}
}