Monday, July 20, 2020

Flutter Firebase || FireStore || Phone Auth

.................................................................................................................................................................................................................................
Example :#1[Adding Real-Time Database to Flutter Firebase]

>keytool -list -v -alias androiddebugkey -keystore C:\Users\sapan\.android\debug.keystore



.............................................................................................................................................................................................................................

  firebase_database: ^3.1.6

.............................................................................................................................................................................................................................
Example : #2

import 'package:firebase_database/firebase_database.dart';

import 'package:flutter/material.dart';

void main()=>runApp(MyApp());
class MyApp extends StatefulWidget{
 @override
 _MyAppState createState()=>_MyAppState();
 }

class _MyAppState extends State<MyApp>{ 
final DatabaseReference databaseReference = FirebaseDatabase.instance.reference().child("path");

void sendData(){ 
databaseReference.push().set({ 
"first_name":"Sapan",
 "last_name":"Das" 
}); 
@override

Widget build(BuildContext context){ 
return MaterialApp(
title: 'Home'
theme: ThemeData(
primaryColor: Colors.purple[900] ), 
home: Scaffold
appBar: AppBar
title: Text('Firebase connection Demo'), 
centerTitle: true, ), 

body: Center
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)), 
onPressed: ()
sendData();
 }, 
color: Colors.red
splashColor: Colors.pink
child: Text('Firebase Demo'), 
       ), 
   ), 
  ), 
 ); 
}


Happy Coding :)
.............................................................................................................................................................................................................................
Example : #3 [Firestore]

Firestore is a web based datastore, with mobile and web SDKs which, when used, are automatically updated as content is pushed to the store. What this means for me generating dynamic content, is that once I have integrated a screen into my application, the flutter UI updates automatically.

.............................................................................................................................................................................................................................
Example : #4 [ Installation]

https://firebase.flutter.dev/docs/migration

flutter clean
Inside Android/app/build.gradle
        multiDexEnabled true


Installing your Firebase configuration file

First, add the 'google-services' plugin as a dependency inside of the android/build.gradle file:
classpath 'com.google.gms:google-services:4.3.3'


Within the /android/app/build.gradle file
apply plugin: 'com.android.application'


ssss
Code#
Note.dart

class Note { final String title; final String descriptions; final String id; Note({this.title, this.descriptions, this.id}); Note.fromMap(Map<String, dynamic> data, String id): title = data['title'], descriptions = data['descriptions'], id = id; }
..................
FirestoreService.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:helloworld/data/data.dart';

class FirestoreService {
static final FirestoreService _firestoreService = FirestoreService._internal();
FirebaseFirestore _db = FirebaseFirestore.instance;
FirestoreService._internal();

factory FirestoreService(){
return _firestoreService;
}
Stream<List<Note>> getNotes() {
return _db.collection('notes').snapshots().map(
(snapshot) => snapshot.docs.map(
(doc) => Note.fromMap(doc.data(), doc.id),
).toList(),
);
}
}
.......................
main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:helloworld/data/data.dart';
import 'package:helloworld/data/firestore_service.dart';
import 'dart:async';


void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();

runApp(
MaterialApp(
theme:
ThemeData(
primaryColor: Colors.
pink),
home:
MyApp()));

}

class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cloud Firestore"),
),
body: StreamBuilder(
stream: FirestoreService().getNotes(),
builder: (context, AsyncSnapshot<List<Note>> snapshot) {
if (snapshot.hasError || !snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
Note note = snapshot.data[index];
return ListTile(
title: Text(note.title),
subtitle: Text(note.descriptions),
);
},
);
},
));
}
}
Some Basic Step





Happy Coding :)
.............................................................................................................................................................................................................................
Example : #5 [Firebase Auth ]

The plugins needed for this project are:

1. firebase_core (for initializing Firebase)
2. firebase_auth (for Firebase authentication)
3. google_sign_in (to implement Google Sign-In)


https://pub.dev/packages/firebase_core/install
  firebase_core: ^0.5.0

https://pub.dev/packages/firebase_auth
  firebase_auth: ^0.18.0+1
https://pub.dev/packages/google_sign_in/install
  google_sign_in: ^4.5.3


Happy Coding :)
.............................................................................................................................................................................................................................
Example : #6 [ Firebase phone authentication]
Setup
https://console.firebase.google.com/

1.


2
.

3.


4.


5.


6.


7.cd android && gradlew signingReport


8.

9.  

10.


11.


12.

13.


14.


15.



Almost Done

Now open the pubspec.yaml file, and added Firebase Authentication plugin and Firebase core plugin.
for Example
https://pub.dev/packages/firebase_core/install
  firebase_core: ^0.5.2

https://pub.dev/packages/firebase_auth/install
  firebase_auth: ^0.18.3

............................................Code here...........................................
phoneauth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class PhoneAuth extends StatefulWidget {
  @override
  _PhoneAuthState createState() => _PhoneAuthState();
}

class _PhoneAuthState extends State<PhoneAuth> {
  TextEditingController phoneController = TextEditingController();

  Future<void> phoneValidations() async {
    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phoneController.text.toString(),
        timeout: Duration(seconds: 60),
        verificationCompleted: (PhoneAuthCredential credential) async {
          await FirebaseAuth.instance.signInWithCredential(credential);
        },
        verificationFailed: (FirebaseAuthException e) {
          if (e.code == 'invalid-phone-number') {
            print('The provided phone number is not valid.');
          }
        },
        codeSent: (String verificationId, int resendToken) async {
          String smsCode ='xxxx';
          PhoneAuthCredential phoneAuthCredential =
              PhoneAuthProvider.credential(
                  verificationId: verificationId, smsCode: smsCode);
          await FirebaseAuth.instance.signInWithCredential(phoneAuthCredential);
        },
        codeAutoRetrievalTimeout: (String verificationId) {
          print(verificationId);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Column(children: [
            TextField(
              controller: phoneController,
              keyboardType: TextInputType.phone,
            ),
            Padding(
              padding: EdgeInsets.all(20.0),
              child: RaisedButton(
                color: Colors.amber,
                onPressed: () {
                  phoneValidations();
                },
              ),
            )
          ]),
        ),
      ),
    );
  }
}
.......................................................
main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:phoneverify/screens/phoneAuth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PhoneAuth(),
    );
  }
}



Happy Coding :)
.............................................................................................................................................................................................................................
Example : #7


.............................................................................................................................................................................................................................
Example : #8

No comments:

Post a Comment