YiXu Zhang

YiXu Zhang

1579746900

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:

Adding Sign In With Apple capability

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

Set Code Signing options

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:

Apple Sign In Button

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:

Apple Sign In Settings prompt

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!

#firebase #flutter #mobile-app #dart #security

What is GEEK

Buddha Community

Apple Sign In with Flutter & Firebase Authentication

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Kaia  Schmitt

Kaia Schmitt

1627200000

Firebase Authentication in Flutter | Flutter Firebase - Part 2 | Google Auth

Firebase Authentication in Flutter | Flutter Firebase - Part 2 | Google Authentication | #FlutterStudio

#google auth #flutter #firebase #flutter firebase #firebase authentication

Punith Raaj

1644991598

The Ultimate Guide To Tik Tok Clone App With Firebase - Ep 2

The Ultimate Guide To Tik Tok Clone App With Firebase - Ep 2
In this video, I'm going to show you how to make a Cool Tik Tok App a new Instagram using Flutter,firebase and visual studio code.

In this tutorial, you will learn how to Upload a Profile Pic to Firestore Data Storage.

🚀 Nice, clean and modern TikTok Clone #App #UI made in #Flutter⚠️

Starter Project : https://github.com/Punithraaj/Flutter_Tik_Tok_Clone_App/tree/Episode1

► Timestamps 
0:00 Intro 0:20 
Upload Profile Screen 
16:35 Image Picker
20:06 Image Cropper 
24:25 Firestore Data Storage Configuration.

⚠️ IMPORTANT: If you want to learn, I strongly advise you to watch the video at a slow speed and try to follow the code and understand what is done, without having to copy the code, and then download it from GitHub.

► Social Media 
GitHub: https://github.com/Punithraaj/Flutter_Tik_Tok_Clone_App.git
LinkedIn: https://www.linkedin.com/in/roaring-r...
Twitter: https://twitter.com/roaringraaj
Facebook: https://www.facebook.com/flutterdartacademy

► Previous Episode : https://youtu.be/QnL3fr-XpC4
► Playlist: https://youtube.com/playlist?list=PL6vcAuTKAaYe_9KQRsxTsFFSx78g1OluK

I hope you liked it, and don't forget to like,comment, subscribe, share this video with your friends, and star the repository on GitHub!
⭐️ Thanks for watching the video and for more updates don't forget to click on the notification. 
⭐️Please comment your suggestion for my improvement. 
⭐️Remember to like, subscribe, share this video, and star the repo on Github :)

Hope you enjoyed this video!
If you loved it, you can Buy me a coffee : https://www.buymeacoffee.com/roaringraaj

LIKE & SHARE & ACTIVATE THE BELL Thanks For Watching :-)
 
https://youtu.be/F_GgZVD4sDk

#flutter tutorial - tiktok clone with firebase #flutter challenge @tiktokclone #fluttertutorial firebase #flutter firebase #flutter pageview #morioh #flutter

Punith Raaj

1640672627

Flutter Hotel Booking UI - Book your Stay At A New Hotel With Flutter - Ep1

https://youtu.be/-tHUmjIkGJ4
Flutter Hotel Booking UI - Book your Stay At A New Hotel With Flutter - Ep1
#flutter #fluttertravelapp #hotelbookingui #flutter ui design 

In this video, I'm going to show you how to make a Cool Hotel Booking App using Flutter and visual studio code. 

In this tutorial, you will learn how to create a Splash Screen and Introduction Screen, how to implement a SmoothPageIndicator in Flutter. 

🚀 Nice, clean and modern Hotel Booking #App #UI made in #Flutter 

⚠️ IMPORTANT: If you want to learn, I strongly advise you to watch the video at a slow speed and try to follow the code and understand what is done, without having to copy the code, and then download it from GitHub. 

► Social Media 

    GitHub: https://github.com/Punithraaj 

    LinkedIn: https://www.linkedin.com/in/roaring-r...

    Twitter: https://twitter.com/roaringraaj

    Facebook: https://www.facebook.com/flutterdartacademy

I hope you liked it, and don't forget to like,comment, subscribe, share this video with your friends, and star the repository on GitHub! 

⭐️ Thanks for watching the video and for more updates don't forget to click on the notification.⭐️Please comment your suggestion for my improvement. ⭐️Remember to like, subscribe, share this video, and star the repo on Github :)Hope you enjoyed this video! If you loved it, you can Buy me a coffee : https://www.buymeacoffee.com/roaringraaj

#flutter riverpod #flutter travel app #appointment app flutter #morioh