Flutter

Setting up Facebook login on your Flutter app using Parse

Introduction

Parse Server supports 3rd party authentication. In this guide you will learn how to setup Facebook authentication/login on your Flutter app using Parse.

Prerequisites

To complete this tutorial, you will need:

Goal

To add Facebook login on your Flutter app using Parse Server

Step 1 - Configure Facebook Login for Android - Quickstart

Step 2 - Configure Facebook Login for Android - Quickstart

Step 3 - Set up Parse Auth for Facebook

Go to Back4App website, log in and then find your app. After that, click on Server Settings and search for the Facebook Login block and select Settings.

The Facebook Login section looks like this:

ID

Now, you just need to paste your Facebook appId in the field below and click on the button to save.

ID

In case you face any trouble while integrating Facebook Login, please contact our team via chat!

Step 4 - Add the Sign In with Facebook

Now that you have the project set up, we can get the user data and sign in to Parse.

According to the documentation, we must send a Map with user authentication data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
      //Make a Login request
      final LoginResult result = await FacebookAuth.instance.login();

      if (result.status != LoginStatus.success) {
        Message.showError(context: context, message: 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.

      //Make sign in with Facebook
      final parseResponse = await ParseUser.loginWith('facebook',
          facebook(accessToken.token, accessToken.userId, accessToken.expires));

Step 5 - Sign in with Facebook from Flutter

Let’s now use our example for Sign in with Facebook in Flutter App, with a simple interface.

Open your Flutter project, go to the main.dart file, clean up all the code, and replace it with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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_flutter/parse_server_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final keyApplicationId = 'YOUR_APP_ID_HERE';
  final keyClientKey = 'YOUR_CLIENT_KEY_HERE';
  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: "YOUR_FACEBOOK_APP_ID", //<-- YOUR APP_ID
      cookie: true,
      xfbml: true,
      version: "v9.0",
    );
  }

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  Future<bool> hasUserLogged() async {
    ParseUser? currentUser = await ParseUser.currentUser() as ParseUser?;
    if (currentUser == null) {
      return false;
    }
    //Checks whether the user's session token is valid
    final ParseResponse? parseResponse =
        await ParseUser.getCurrentUserFromServer(currentUser.sessionToken!);

    if (parseResponse?.success == null || !parseResponse!.success) {
      //Invalid session. Logout
      await currentUser.logout();
      return false;
    } else {
      return true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter - Sign In with Facebook',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: FutureBuilder<bool>(
          future: hasUserLogged(),
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return Scaffold(
                  body: Center(
                    child: Container(
                        width: 100,
                        height: 100,
                        child: CircularProgressIndicator()),
                  ),
                );
              default:
                if (snapshot.hasData && snapshot.data!) {
                  return UserPage();
                } else {
                  return HomePage();
                }
            }
          }),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @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: () => doSignInFacebook(),
                  ),
                ),
                SizedBox(
                  height: 16,
                ),
              ],
            ),
          ),
        ));
  }

  void doSignInFacebook() async {
    late ParseResponse parseResponse;
    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) {
        Message.showError(context: context, message: 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.

      //Make sign in with Facebook
      parseResponse = await ParseUser.loginWith('facebook',
          facebook(accessToken.token, accessToken.userId, accessToken.expires));

      if (parseResponse.success) {
        final ParseUser parseUser = await ParseUser.currentUser() as ParseUser;

        //Get user data from Facebook
        final userData = await FacebookAuth.instance.getUserData();

        //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 FacebookAuth.instance.logOut();
        parseResponse = await parseUser.save();

        if (parseResponse.success) {
          Message.showSuccess(
              context: context,
              message: 'User was successfully with Sign In Facebook!',
              onPressed: () async {
                Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(builder: (context) => UserPage()),
                  (Route<dynamic> route) => false,
                );
              });
        } else {
          Message.showError(
              context: context, message: parseResponse.error!.message);
        }
      } else {
        Message.showError(
            context: context, message: parseResponse.error!.message);
      }
    } on Exception catch (e) {
      print(e.toString());
      Message.showError(context: context, message: e.toString());
    }
  }
}

class UserPage extends StatelessWidget {
  Future<ParseUser?> getUser() async {
    return await ParseUser.currentUser() as ParseUser?;
  }

  @override
  Widget build(BuildContext context) {
    void doUserLogout() async {
      final currentUser = await ParseUser.currentUser() as ParseUser;
      var response = await currentUser.logout();
      if (response.success) {
        Message.showSuccess(
            context: context,
            message: 'User was successfully logout!',
            onPressed: () {
              Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => HomePage()),
                (Route<dynamic> route) => false,
              );
            });
      } else {
        Message.showError(context: context, message: response.error!.message);
      }
    }

    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter - Sign In with Facebook'),
        ),
        body: FutureBuilder<ParseUser?>(
            future: getUser(),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                case ConnectionState.waiting:
                  return Center(
                    child: Container(
                        width: 100,
                        height: 100,
                        child: CircularProgressIndicator()),
                  );
                default:
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Center(
                            child: Text(
                                'Hello, ${snapshot.data!.get<String>('name')}')),
                        SizedBox(
                          height: 16,
                        ),
                        Container(
                          height: 50,
                          child: ElevatedButton(
                            child: const Text('Logout'),
                            onPressed: () => doUserLogout(),
                          ),
                        ),
                      ],
                    ),
                  );
              }
            }));
  }
}

class Message {
  static void showSuccess(
      {required BuildContext context,
      required String message,
      VoidCallback? onPressed}) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Success!"),
          content: Text(message),
          actions: <Widget>[
            new ElevatedButton(
              child: const Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
                if (onPressed != null) {
                  onPressed();
                }
              },
            ),
          ],
        );
      },
    );
  }

  static void showError(
      {required BuildContext context,
      required String message,
      VoidCallback? onPressed}) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Error!"),
          content: Text(message),
          actions: <Widget>[
            new ElevatedButton(
              child: const Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
                if (onPressed != null) {
                  onPressed();
                }
              },
            ),
          ],
        );
      },
    );
  }
}

Find your Application Id and Client Key credentials navigating to your app Dashboard at Back4App Website.

Update your code in main.dart with the values of your project’s ApplicationId and ClientKey in Back4app.

  • keyApplicationId = App Id
  • keyClientKey = Client Key

Run the project, and the app will load as shown in the image.

flutter-back4app-associations

Conclusion

At this stage, you are able to use Sign in with Facebook in Flutter on Back4app.