Created
May 4, 2020 13:57
-
-
Save ravindu9701/b4ee7fd603296837d4ecf0a6aaae4e64 to your computer and use it in GitHub Desktop.
Flutter Facebook Login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_facebook_login/flutter_facebook_login.dart'; | |
import 'package:http/http.dart' as http; | |
import 'dart:convert'; | |
import 'package:flutter_auth_buttons/flutter_auth_buttons.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() { | |
// TODO: implement createState | |
return _MyAppState(); | |
} | |
} | |
class _MyAppState extends State<MyApp> { | |
bool _isLoggedIn = false; | |
Map userDetails; | |
final facebookLogin = FacebookLogin(); | |
_loginWithFB() async { | |
final result = await facebookLogin.logIn(['email']); | |
switch (result.status) { | |
case FacebookLoginStatus.loggedIn: | |
final token = result.accessToken.token; | |
final graphResponse = await http.get( | |
'https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}'); | |
final details = jsonDecode(graphResponse.body); | |
print(details); | |
setState(() { | |
userDetails = details; | |
_isLoggedIn = true; | |
}); | |
break; | |
case FacebookLoginStatus.cancelledByUser: | |
setState(() => _isLoggedIn = false); | |
break; | |
case FacebookLoginStatus.error: | |
setState(() => _isLoggedIn = false); | |
break; | |
} | |
} | |
_logout() { | |
facebookLogin.logOut(); | |
setState(() { | |
_isLoggedIn = false; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
// TODO: implement build | |
return MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: _isLoggedIn | |
? Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Image.network( | |
userDetails["picture"]["data"]["url"], | |
height: 50.0, | |
width: 50.0, | |
), | |
Text(userDetails["name"]), | |
FlatButton( | |
color: Colors.blue[600], | |
child: Text("Logout"), | |
onPressed: () { | |
_logout(); | |
}, | |
) | |
], | |
) | |
: Center( | |
child: FacebookSignInButton( | |
onPressed: () { | |
_loginWithFB(); | |
}, | |
), | |
)), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment