To begin, you need to have a Facebook account. Then,
go to pub.dev, get the flutter_facebook_login
package, and add it to your pubspec.yaml
. Now, this tutorial will be split in half, with one section for Android and another one for iOS. The main reason is that the installation of Facebook SDK will be different for both users.
Visit Facebook for Developer’s Android Quickstart and complete all
Create a new file under android/app/src/main/res/values
named strings.xml
and add the following values:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">App Name</string>
<string name="facebook_app_id">XXXXXXXXXXXX</string>
<string name="fb_login_protocol_scheme">fbXXXXXXXXXXXX</string>
</resources>
Replace the app name, Facebook App ID, and your Facebook Login Protocol Scheme with your retrieved details from the Facebook Developer Console.
Since the AppDelegate connection is a part of Swift and SwiftUI, we do not need that.
For any issues and troubleshooting, visit the pub.dev
page for the package.
Now, import the package into your dart file, and create a login function:
void fbLogin() async {
var facebookLogin = FacebookLogin();
var facebookLoginResult = await facebookLogin.logInWithReadPermissions(['email']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
onLoginStatusChanged(false);
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
onLoginStatusChanged(false);
break;
case FacebookLoginStatus.loggedIn:
print("LoggedIn");
onLoginStatusChanged(true);
break;
}
}
The onLoginStatusChanged is used to update the UI using setState()
when the user logs in to handle the UI a little better:
bool isLoggedIn = false;
void onLoginStatusChanged(bool isLoggedIn) {
setState(() {
this.isLoggedIn = isLoggedIn;
});
}
Now, simply go ahead and call the fbLogin()
function inside of a
Once signed in, you can also get your user image and name:
var userDetails = await http.get(Uri.parse('https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email,picture.height(200)&access_token=${facebookLoginResult.accessToken.token}'));
Note:
http
is imported from the http package that is available here. This package allows users to create HTTP requests, so you can import it as the following:import 'package:http/http.dart' as HTTP;
Now, parse the response and decode the JSON value:
var profile = json.decode(graphResponse.body);
print(profile.toString());
Once you print the profile, you’ll be able to see a response inside your console. Within this response, you can see parameters like the name.
If you want to use the name, simply go ahead and use it as:
Text(profile['name'])
For global access, create a variable, assign it to profile
, and check out for null safety to ensure there is no user-end crash.
To access the image, you can use NetworkImage and parse the URL as:
profile['picture']['data']['url']
If you need any assistance, check out the example code by the package maintainers here.