How to authentication user for uploading video in youtube channel flutter? - flutter

I want to authenticate user for uploading video in their channel ,required parameter is just authentication successful or not, currently i am working with these 3 plugins google_sign_in, googleapis extension_google_sign_in_as_googleapis_auth , by these i can only able to sign in into google account of user with the help of firebase.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
import 'package:googleapis/youtube/v3.dart';
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: <String>[
'email',
//'https://www.googleapis.com/auth/youtube.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) async {
setState(() {
_currentUser = account;
});
if (_currentUser != null) {
_handleGetChannels();
}
});
_googleSignIn.signInSilently();
}
Future<void> _handleGetChannels() async {
setState(() {
_contactText = 'Loading subscription info...';
});
var httpClient = (await _googleSignIn.authenticatedClient())!;
print("hello${httpClient.credentials.accessToken}");
var youTubeApi = YouTubeApi(httpClient);
var favorites = await youTubeApi.playlistItems.list(
['snippet'],
playlistId: 'LL', // Liked List
);
print("hey $favorites");
// final youtubeApi = YouTubeApi(await _googleSignIn.authenticatedClient());
// final response = await youtubeApi.subscriptions.list('snippet', mine: true);
setState(() {
if (favorites.items!.isNotEmpty) {
final channels =
favorites.items!.map((sub) => sub.snippet!.title).join(', ');
_contactText = 'I see you follow: ${channels}!';
} else {
_contactText = 'No channels to display.';
}
});
}
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<void> _handleSignOut() => _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: _handleGetChannels,
),
],
);
} 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(),
));
}
}
if i pass 'https://www.googleapis.com/auth/youtube.readonly' in scopes it shows loading only, and from email scopes i got the error Unhandled Exception: Access was denied (www-authenticate header was: Bearer realm="https://accounts.google.com/", error="insufficient_scope"
kindly help , i just want to authenticate user for their you tube channel.

The YouTube Data API supports the OAuth 2.0 protocol for authorizing access to private user data.
insufficient_scope
Means that the access token you sent was not authorized with the scope needed by the method you are calling.
For example video.insert requires authorization with one of the following scopes
You should check Google apis dart client library

Related

Error: Facebook auth is invalid for this user. Flutter using Back4App

I'm trying to make a login method via Facebook using Back4App
and I've been following this instructions and I did everything as provided, but when I try to test this, it throws an error Status Code: 101 Error: Facebook auth is invalid for this user. my code: (it's the same as the code provided in the example)
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final keyApplicationId = 'WHv1tAs6CNFngWtEG6zgX6LrwFCB*******';
final keyClientKey = 'qn7DXL5FHSFJOYRzQLVJ0K4xl1fwS1*******';
final keyParseServerUrl = 'https://parseapi.back4app.com';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, debug: true);
if (kIsWeb) {
// initialiaze the facebook javascript SDK
FacebookAuth.i.webInitialize(
appId: "22079360*******", //<-- YOUR APP_ID
cookie: true,
xfbml: true,
version: "v9.0",
);
}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter - Sign In with Facebook',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isLoggedIn = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter - Sign In with Facebook'),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: 200,
child: Image.network(
'http://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
),
Center(
child: const Text('Flutter on Back4App',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 100,
),
Container(
height: 50,
child: ElevatedButton(
child: const Text('Sign In with Facebook'),
onPressed: isLoggedIn ? null : () => doSignInFacebook(),
),
),
SizedBox(
height: 16,
),
Container(
height: 50,
child: OutlinedButton(
child: const Text('Logout'),
onPressed: !isLoggedIn ? null : () => doUserLogout(),
),
)
],
),
),
));
}
void showSuccess(String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success!"),
content: Text(message),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void showError(String errorMessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Error!"),
content: Text(errorMessage),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void doSignInFacebook() async {
try {
//Check if the user is logged.
final AccessToken? currentAccessToken =
await FacebookAuth.instance.accessToken;
if (currentAccessToken != null) {
//Logout
await FacebookAuth.instance.logOut();
}
//Make a Login request
final LoginResult result = await FacebookAuth.instance.login();
if (result.status != LoginStatus.success) {
showError(result.message!);
return;
}
final AccessToken accessToken = result.accessToken!;
//https://docs.parseplatform.org/parse-server/guide/#facebook-authdata
//According to the documentation, we must send a Map with user authentication data.
final Map<String, dynamic> authData = <String, dynamic>{};
authData['id'] = accessToken.userId;
authData['token'] = accessToken.token;
authData['expiration_date'] = accessToken.expires.toString();
final userData = await FacebookAuth.instance.getUserData();
//Make sign in with Facebook
final parseResponse = await ParseUser.loginWith('facebook', authData);
if (parseResponse.success) {
final ParseUser parseUser = parseResponse.result as ParseUser;
//Additional Information in User
if (userData.containsKey('email')) {
parseUser.emailAddress = userData['email'];
}
if (userData.containsKey('name')) {
parseUser.set<String>('name', userData['name']);
}
if (userData["picture"]["data"]["url"] != null) {
parseUser.set<String>('photoURL', userData["picture"]["data"]["url"]);
}
await parseUser.save();
showSuccess("User was successfully with Sign In Facebook!");
setState(() {
isLoggedIn = true;
});
} else {
showError(parseResponse.error!.message);
}
} on Exception catch (e) {
print(e.toString());
showError(e.toString());
}
}
void doUserLogout() async {
final user = await ParseUser.currentUser() as ParseUser;
var response = await user.logout();
if (response.success) {
showSuccess("User was successfully logout!");
setState(() {
isLoggedIn = false;
});
} else {
showError(response.error!.message);
}
}
}
debug console:
I/flutter ( 9901):
I/flutter ( 9901): https://parseapi.back4app.com/users
I/flutter ( 9901): ╰--
I/flutter ( 9901): ╭-- Parse Response
I/flutter ( 9901): Class: _User
I/flutter ( 9901): Function: ParseApiRQ.loginWith
I/flutter ( 9901): Status Code: 101
I/flutter ( 9901): Type: ObjectNotFound
I/flutter ( 9901): Error: Facebook auth is invalid for this user.
I/flutter ( 9901): ╰--
flutter version : 2.2.2.
parse_server_sdk: ^3.1.0
flutter_facebook_auth: ^3.5.0
the code provided in back4app's documentation had a problem, you can find the right method for sending the information to the parse server in the package's documentation
before:
final parseResponse = await ParseUser.loginWith('facebook', authData);
after:
final parseResponse = await ParseUser.loginWith('facebook',
facebook(accessToken.token, accessToken.userId, accessToken.expires));

How to get state changed value after widget build?

I have simple application where I work with user location. On first app open I will ask from user to allow location and then save to var. But when I try check inside widget location allow status it is return old value instance of changed value.
Code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yandex_mapkit/yandex_mapkit.dart';
import 'package:permission_handler/permission_handler.dart';
class PlacesListScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return _Map();
}
}
class _Map extends StatefulWidget {
#override
_MapState createState() => _MapState();
}
class _MapState extends State<_Map> {
YandexMapController controller;
PermissionStatus _permissionStatus = PermissionStatus.undetermined;
#override
void initState() {
super.initState();
_requestPermission();
}
Future<void> _requestPermission() async {
Map<Permission, PermissionStatus> permissions =
await [Permission.location].request();
setState(() {
_permissionStatus = permissions[Permission.location];
});
}
void _showMessage(BuildContext context, Text text) {
final ScaffoldState scaffold = Scaffold.of(context);
scaffold.showSnackBar(
SnackBar(
content: text,
action: SnackBarAction(
label: 'OK', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('App Name'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: null,
),
],
),
body: Text('App Content'),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FloatingActionButton(
onPressed: () async {
if (_permissionStatus == PermissionStatus.granted) {
await Future.wait([
controller.moveToUser(),
controller.showUserLayer(
iconName: 'lib/assets/arrow.png',
arrowName: 'lib/assets/user_location1.png',
accuracyCircleFillColor: Colors.green.withOpacity(0.5),
)
]);
} else {
_showMessage(context, const Text('Permission Denied'));
}
},
child: Icon(Icons.place, color: Colors.white),
backgroundColor: Colors.green,
heroTag: 'showUserLocation',
),
],
),
);
}
}
Using FloatingActionButton I tried check Permission status in my code. But my var _permissionStatus doesn't updated when user allowed location. How to fix this problem and get changed value from state?
You can use this package: https://pub.dev/packages/location
and then you can read the permission status:
Location location = new Location();
PermissionStatus _permissionGranted;
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
another way:
location.hasPermision().then(PermissionStatus status){
if (_permissionGranted == PermissionStatus.denied){
location.requestPermission().then((PermissionStatus requestStatus){
// save the value
}
);
}
});
You need to know when user grand the permission then you know it, you must use the wrap your widget with FocusScope like this:
first define this:
final _focusNode = FocusScopeNode();
then wrap it with this:
return FocusScope(
node: _focusNode,
child: WillPopScope(
onWillPop: () async {
_requestPermission();
},.....

_googleSignIn.signInSilently() is not working

I have copy pasted the whole code from https://pub.dev/packages/google_sign_in#-example-tab- but still I am getting the following error on _googleSignIn.signInSilently()
Exception has occurred.
PlatformException (PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.)))
Please have a look into below mentioned code snippet for main.dart file
// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
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<void> _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<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<void> _handleSignOut() => _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(),
));
}
}
I want to user firebase as my backend. But before doing so this itself is not working for me.
I could see Flutter google sign in stay logged in : here also they are using the same technique.
According to the package requirements:
To access Google Sign-In, you'll need to make sure to register your application (with firebase).
You don't need to include the google-services.json file in your app unless you are using Google services that require it. You do need to enable the OAuth APIs that you want, using the Google Cloud Platform API manager. For example, if you want to mimic the behavior of the Google Sign-In sample app, you'll need to enable the Google People API.
Make sure you've filled out all required fields in the console for OAuth consent screen. Otherwise, you may encounter APIException errors.
That error means there are no auth token in the keychain, I faced it once and solve with this answer, I copy and send the code I used below, also you can check other solutions from that thread.
if GIDSignIn.sharedInstance().hasAuthInKeychain() == true{
GIDSignIn.sharedInstance().signInSilently()
}
else{
GIDSignIn.sharedInstance().signIn()
}

share link on social media via several buttons in android and ios with flutter

These are three social media buttons.
I just want to share a link on social media via these buttons in Android as well as ios.
I used flutter_share_me plugin. but there are two problems with this plugin.
1.)This plugin is defined for only Android devices, not for ios.
2.)it isn't defined for Instagram.
CODE:
For Facebook:
IconButton(
icon: Image.asset("assets/icons/facebook_logo.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
FlutterShareMe().shareToFacebbok(url: appUrl, msg: "Babilok");
}
),
For Twitter:
IconButton(
icon: Image.asset("assets/icons/twitter_logo1.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
FlutterShareMe().shareToTwitter(url: appUrl, msg: "Babilok");
}
),
For Instagram:
IconButton(
icon: Image.asset("assets/icons/instagram_logo.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
?????????.....
}
),
You can use this plugin flutter_social_content_share
This plugin works fine both on iOS & Android as well.
/// SHARE ON FACEBOOK CALL
shareOnFacebook() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.facebookWithoutImage,
url: "https://www.apple.com",
quote: "captions");
print(result);
}
/// SHARE ON INSTAGRAM CALL
shareOnInstagram() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.instagramWithImageUrl,
imageUrl:
"https://post.healthline.com/wp-content/uploads/2020/09/healthy-eating-ingredients-732x549-thumbnail-732x549.jpg");
print(result);
}
/// SHARE ON WHATSAPP CALL
shareWatsapp() async {
String result = await FlutterSocialContentShare.shareOnWhatsapp(
number: "xxxxxx", text: "Text appears here");
print(result);
}
/// SHARE ON EMAIL CALL
shareEmail() async {
String result = await FlutterSocialContentShare.shareOnEmail(
recipients: ["xxxx.xxx#gmail.com"],
subject: "Subject appears here",
body: "Body appears here",
isHTML: true); //default isHTML: False
print(result);
}
/// SHARE ON SMS CALL
shareSMS() async {
String result = await FlutterSocialContentShare.shareOnSMS(
recipients: ["xxxxxx"], text: "Text appears here");
print(result);
}
///Build Context
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Text('Running on: $_platformVersion\n'),
RaisedButton(
child: Text("Share to facebook button"),
color: Colors.red,
onPressed: () {
shareOnFacebook();
},
),
RaisedButton(
child: Text("Share to instagram button"),
color: Colors.red,
onPressed: () {
shareOnInstagram();
},
),
RaisedButton(
child: Text("Share to whatsapp button"),
color: Colors.red,
onPressed: () {
shareWatsapp();
},
),
RaisedButton(
child: Text("Share to email button"),
color: Colors.red,
onPressed: () {
shareEmail();
},
),
RaisedButton(
child: Text("Share to sms button"),
color: Colors.red,
onPressed: () {
shareSMS();
},
),
],
),
),
);
}
You can use package https://pub.dev/packages/social_share_plugin
package description forget to mention include twitter now
full example code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:social_share_plugin/social_share_plugin.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await SocialSharePlugin.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text('Share to Instagram'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedInstagram("image/*", file.path);
},
),
RaisedButton(
child: Text('Share to Facebook'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedFacebook('test', file.path);
},
),
RaisedButton(
child: Text('Share to Facebook Link'),
onPressed: () async {
String url = 'https://flutter.dev/';
final quote =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToFeedFacebookLink(
quote: quote,
url: url,
onSuccess: (postId) {
print('FACEBOOK SUCCESS $postId');
return;
},
onCancel: () {
print('FACEBOOK CANCELLED');
return;
},
onError: (error) {
print('FACEBOOK ERROR $error');
return;
},
);
print(result);
},
),
RaisedButton(
child: Text('Share to Twitter'),
onPressed: () async {
String url = 'https://flutter.dev/';
final text =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToTwitter(
text: text,
url: url,
onSuccess: (_) {
print('TWITTER SUCCESS');
return;
},
onCancel: () {
print('TWITTER CANCELLED');
return;
});
print(result);
},
),
],
),
),
);
}
}
You can use pack Share social media plugin
final twitterLogin = new ShareSocialMediaPlugin(
consumerKey: "consumerKey",
consumerSecret: 'consumerSecret');
RaisedButton(
child: Text(titleTwitterButton, style: TextStyle(fontSize: 20)),
onPressed: () async {
//Platform in Android
if (Platform.isAndroid) {
var result = await twitterLogin.shareTwitter("conectado desde plugin");
print(result);
if(result != null){
if (result == "success"){
print("success!");
}else{
print("fail");
}
}
}
//Platform in iOS
else if (Platform.isIOS) {
var sessionTwitter = await twitterLogin.currentSessionIOS();
var tweet = await twitterLogin.shareTwitteriOS(
sessionTwitter["outhToken"],
sessionTwitter["oauthTokenSecret"],
"test cpmplete future",
twitterLogin.consumerKey,
twitterLogin.consumerSecret);
final response = json.decode(tweet.body);
if (response['text'] != null) {
print("success");
}else{
print("fail");
}
}
},
),
That plugin have support for instagram, twitter, line

Flutter: I am unable to logout my app with google sign in library. How to do this?

I have tried below google sign in example , it is working fine. But when I moved _handleSignOut() function to another screen , it is not signing out. My requirement is after login success, my homepage is visible. On the top of homepage , there is a logout button. on the click of which , I want to logout my app with google.
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<void> _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<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<void> _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(),
));
}
}
Use signOut() instead. If you are using FirebaseAuth, you need to log out from both
Future<void> _handleSignOut() async {
await FirebaseAuth.instance.signOut();
await _googleSignIn.signOut();
}
I found solution for this. I was creating again an object of googlesignin in logout screen.
It was my mistake.
Using same object of googlesignin as declared above
GoogleSignIn _googleSignIn = GoogleSignIn(....) in Logout screen will work. I just need to call this object like _googleSignIn.signOut().