Apple Sign In with Flutter & Firebase Authentication

Apple Sign In with Flutter & Firebase Authentication

In this tutorial we'll see how to add Apple Sign In to our Flutter apps from scratch. Learn how to implement Apple Sign In with Flutter & Firebase Authentication (from scratch), and give your iOS users a convenient way of signing into your app. Apple Sign In with Flutter & Firebase Authentication.

In this tutorial we'll see how to add Apple Sign In to our Flutter apps from scratch.

Apple Sign In is a new authentication method that is available on iOS 13 and above.

It is very convenient, as your iOS users already have an Apple ID, and can use it to sign in with your app.

So just as you would offer Google Sign In on Android, it makes sense to offer Apple Sign In on iOS.

We will use the Apple Sign In Flutter plugin available on pub.dev.

Note: this plugin supports iOS only, and you can only use this on devices running iOS 13 and above.

Prerequisites

  • Xcode 11 installed
  • An Apple Developer Account
  • An iOS 13.x device or simulator, signed in with an Apple ID
Project Setup

After creating a new Flutter project, add the following dependencies to your pubspec.yaml file:

dependencies:
  firebase_auth: ^0.15.3
  apple_sign_in: ^0.1.0
  provider: ^4.0.1

Note: we will use Provider for dependency injection, but you can use something else if you prefer.

Next, we need add Firebase to our Flutter app. Follow this guide for how to do this:

After we have followed the required steps, the GoogleService-Info.plist file should be added to our Xcode project.

And while in Xcode 11, select the Signing & Capabilities tab, and add "Sign In With Apple" as a new Capability:

Once this is done, ensure to select a team on the Code Signing section:

This will generate and configure an App ID in the "Certificates, Identifiers & Profiles" section of the Apple Developer portal. If you don't do this, sign-in won't work.

As a last step, we need to enable Apple Sign In in Firebase. This can be done under Authentication -> Sign-in method:

This completes the setup for Apple Sign In, and we can dive into the code.

Checking if Apple Sign In is available

Before we add the UI code, let's write a simple class to check if Apple Sign In is available:

import 'package:apple_sign_in/apple_sign_in.dart';

class AppleSignInAvailable {
  AppleSignInAvailable(this.isAvailable);
  final bool isAvailable;

  static Future<AppleSignInAvailable> check() async {
    return AppleSignInAvailable(await AppleSignIn.isAvailable());
  }
}

Then, in our main.dart file, let's modify the entry point:

void main() async {
  // Fix for: Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
  WidgetsFlutterBinding.ensureInitialized();
  final appleSignInAvailable = await AppleSignInAvailable.check();
  runApp(Provider<AppleSignInAvailable>.value(
    value: appleSignInAvailable,
    child: MyApp(),
  ));
}

The first line prevents an exception that occurs if we attempt to send messages across the platform channels before the binding is initialized.

Then, we check if Apple Sign In is available by using the class we just created.

And we use Provider to make this available as a value to all widgets in our app.

Note: this check is done upfront so that appleSignInAvailable is available synchronously to the entire widget tree. This avoids using a FutureBuilder in widgets that need to perform this check.

Adding the UI code

Instead of the default counter app, we want to show a Sign In Page with a button:

import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:apple_sign_in_firebase_flutter/apple_sign_in_available.dart';
import 'package:apple_sign_in_firebase_flutter/auth_service.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SignInPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appleSignInAvailable =
        Provider.of<AppleSignInAvailable>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text('Sign In'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(6.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [            
            if (appleSignInAvailable.isAvailable)
              AppleSignInButton(
                style: ButtonStyle.black, // style as needed
                type: ButtonType.signIn, // style as needed
                onPressed: () {},
              ),
          ],
        ),
      ),
    );
  }
}

Note: we use a collection-if to only show the AppleSignInButton if Apple Sign In is available. See this video for UI-as-code operators in Dart.

Back to our main.dart file, we can update our root widget to use the SignInPage:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Apple Sign In with Firebase',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: SignInPage(),
    );
  }
}

At this stage, we can run the app on an iOS 13 simulator and get the following:

Adding the authentication code

Here is the full authentication service that we will use to sign in with Apple (explained below):

import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';

class AuthService {
  final _firebaseAuth = FirebaseAuth.instance;

  Future<FirebaseUser> signInWithApple({List<Scope> scopes = const []}) async {
    // 1\. perform the sign-in request
    final result = await AppleSignIn.performRequests(
        [AppleIdRequest(requestedScopes: scopes)]);
    // 2\. check the result
    switch (result.status) {
      case AuthorizationStatus.authorized:
        final appleIdCredential = result.credential;
        final oAuthProvider = OAuthProvider(providerId: 'apple.com');
        final credential = oAuthProvider.getCredential(
          idToken: String.fromCharCodes(appleIdCredential.identityToken),
          accessToken:
              String.fromCharCodes(appleIdCredential.authorizationCode),
        );
        final authResult = await _firebaseAuth.signInWithCredential(credential);
        final firebaseUser = authResult.user;
        if (scopes.contains(Scope.fullName)) {
          final updateUser = UserUpdateInfo();
          updateUser.displayName =
              '${appleIdCredential.fullName.givenName} ${appleIdCredential.fullName.familyName}';
          await firebaseUser.updateProfile(updateUser);
        }
        return firebaseUser;
      case AuthorizationStatus.error:
        print(result.error.toString());
        throw PlatformException(
          code: 'ERROR_AUTHORIZATION_DENIED',
          message: result.error.toString(),
        );

      case AuthorizationStatus.cancelled:
        throw PlatformException(
          code: 'ERROR_ABORTED_BY_USER',
          message: 'Sign in aborted by user',
        );
    }
    return null;
  }
}

First, we pass a List<Scope> argument to our method. Scopes are the kinds of contact information that can be requested from the user (email and fullName).

Then, we make a call to AppleSignIn.performRequests and await for the result.

Finally, we parse the result with a switch statement. The three possible cases are authorized, error and cancelled.

Authorized

If the request was authorized, we create an OAuthProvider credential with the identityToken and authorizationCode we received.

We then pass this to _firebaseAuth.signInWithCredential(), and get an AuthResult that we can use to extract the FirebaseUser.

And if we requested the full name, we can update the profile information of the FirebaseUser object with the fullName from the Apple ID credential.

Error or Cancelled

If authentication failed or was cancelled by the user, we throw a PlatformException that can be handled by at the calling site.

Using the authentication code

Now that our auth service is ready, we can add it to our app via Provider like so:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Provider<AuthService>(
      create: (_) => AuthService(),
      child: MaterialApp(
        title: 'Apple Sign In with Firebase',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: SignInPage(),
      ),
    );
  }
}

Then, in our SignInPage, we can add a method to sign-in and handle any errors:

Future<void> _signInWithApple(BuildContext context) async {
  try {
    final authService = Provider.of<AuthService>(context, listen: false);
    final user = await authService.signInWithApple(
        requestEmail: true, requestFullName: true);
    print('uid: ${user.uid}');
  } catch (e) {
    // TODO: Show alert here
    print(e);
  }
}

Finally, we remember to call this on the callback of the AppleSignInButton:

AppleSignInButton(
  style: ButtonStyle.black,
  type: ButtonType.signIn,
  onPressed: () => _signInWithApple(context),
)
Testing things

Our implementation is complete, and we can run the app.

If we press the sign-in button and an Apple ID is not configured on our simulator or device, we will get the following:

After signing in with our Apple ID, we can try again, and we will get this:

After continuing, we are prompted to enter the password for our Apple ID (or use touch ID/face ID if enabled on the device). If we have requested full name and email access, the user will have a chance edit the name, and choose to share or hide the email:

After confirming this, the sign-in is complete and the app is authenticated with Firebase.

Note: if the sign-in screen is not dismissed after authenticating, it's likely because you forgot to set the team in the code signing options in Xcode.

The next logical step is to move away from the SignInPage and show the home page instead. This can be done by adding a widget above the SignInPage, to decide which page to show depending on the onAuthStateChaged stream of FirebaseAuth.

Congratulations, you have now enabled Apple Sign In in your Flutter app! Your iOS users are grateful. 🙏

Full Source Code is here on GitHub.

Happy coding!

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates.

Know about Top ECommerce Mobile App Development Company

Flutter for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart

Flutter for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart

Flutter tutorial for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart. Flutter Introduction for Beginners: Get Started with Flutter and learn how to build an iOS and Android app with Flutter! What is Flutter? How Flutter & Dart Code Gets Compiled? Why Choose Flutter? Flutter is Google's UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

Free Flutter Introduction for Beginners: Get Started with Flutter and learn how to build an iOS and Android app with Flutter!


Content:

  • Introduction 00:03
  • What is Flutter 01:50
  • Flutter's Architecture 07:44
  • How Flutter & Dart Code Gets Compiled
  • To Native Apps 12:31
  • Understanding Flutter Versions 15:44
  • Flutter macOS Setup 18:34
  • macOS Development Environment 37:24
  • Flutter Windows Setup 41:32
  • Windows Development Environment 01:00:48
  • Flutter & Material Design 01:04:34
  • Flutter Alternatives 01:05:49
  • Course Outline 01:11:56
  • How To Get The Most Out Of The
  • Course 01:18:36
  • Module Introduction 01:21:17
  • Creating a New Project 01:23:42
  • An Overview of the Generated Files &
  • Folders 01:35:57
  • Analyzing the Default App 01:44:18
  • Dart Basics 01:49:50
  • More Dart Basics 02:07:08
  • Building an App From Scratch 02:20:15
  • Running the App on an Emulator 02:31:18
  • Class Constructors & Named
  • Arguments 02:34:43
  • First Summary & Additional Syntax 02:43:13
  • Building a Widget Tree 02:51:24
  • Visible (Input / Output) & Invisible
  • (Layout / Control) Widgets 02:59:04
  • Adding Layout Widgets 03:02:17
  • Connecting Functions & Buttons 03:09:09
  • Anonymous Functions 03:16:40
  • Updating Widget Data (Or: Using
  • StatelessWidget Incorrectly) 03:20:01
  • Updating Correctly with Stateful
  • Widgets 03:26:38
  • A Brief Look Under The Hood 03:38:36
  • Using Private Properties 03:41:04
  • Creating a New, Custom Widget 03:46:21
  • First Styling & Layouting Steps 03:58:11
  • Enums & Multiple Constructors 04:06:12
  • Official Docs & The Widget Catalog 04:10:19
  • Passing Callback Functions Around 04:12:59
  • Introducing Maps 04:23:37
  • Mapping Lists to Widgets 04:29:30
  • final vs const 04:39:54
  • Introducing "if" Statements 04:50:45
  • [DART DEEP DIVE] More on "if"
  • Statements 04:57:36
  • [DART DEEP DIVE] The "null" Value 05:08:52
  • Outputting Widgets Conditionally 05:10:55
  • Splitting the App Into Widgets 05:13:16
  • Calculating a Total Score 05:23:13
  • Getters & "else-if" 05:30:59
  • Resetting the Quiz 05:37:34
  • Wrap Up 05:42:28

Top Mobile App Development Agency in Massachusetts

Top Mobile App Development Agency in Massachusetts

**Looking for Top Mobile App Development Agency at reasonable rates?** AppClues Studio is one of the top Mobile App Development Agencies in Massachusetts. We offer user-oriented mobile solutions to our clients globally. We offer Mobile app...

Looking for Top Mobile App Development Agency at reasonable rates?

AppClues Studio is one of the top Mobile App Development Agencies in Massachusetts. We offer user-oriented mobile solutions to our clients globally.

We offer Mobile app development services like iOS app development, Android app development, M-commerce development, Cross-Platform mobile app development, AR & VR app development, IoT app development, Wallet app development, Hybrid app development etc.

Why Choose AppClues Studio?
• Domain Expertise
• On-time Delivery
• 24/7 Support
• Aesthetic Designs
• Agile Development
• Smooth Handover

If you looking for your mobile application development, then get in touch with us!
Visit: https://appcluesstudio.com/mobile-applications-development-company-massachusetts
Email: [email protected]
Contact No.: +1-978-309-9910