Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 9.31 KB | None | 0 0
  1. ===================================================== main.dart =====================================================================
  2. import 'package:flutter/material.dart';
  3. import 'HomePage.dart';
  4. import 'PhoneAuth.dart';
  5. import 'package:shared_preferences/shared_preferences.dart';
  6. import 'package:firebase_auth/firebase_auth.dart';
  7.  
  8. bool sdg_msk=false;
  9. String no_hp;
  10. void Savemasuk() async {
  11.   SharedPreferences pref = await SharedPreferences.getInstance();
  12.   pref.setBool("lg_msk", sdg_msk);
  13.   pref.setString("nomorhp", no_hp);
  14. }
  15.  
  16. Future<bool> get_login() async {
  17.   SharedPreferences pref = await SharedPreferences.getInstance();
  18. pref.getBool("lg_msk") == null ? false : true;}
  19.  
  20. Future<String> get_akun() async { // = 'tidak ada nama'
  21.   SharedPreferences pref = await SharedPreferences.getInstance();
  22.   return pref.getString("nomorhp") ?? "tidak ada nomor hp";
  23. }
  24.  
  25. void main() {
  26.   runApp(new MyApp());
  27. }
  28.  
  29. class MyApp extends StatefulWidget {
  30.   @override
  31.   _MyAppState createState() => _MyAppState();
  32. }
  33. FirebaseUser user;
  34. class _MyAppState extends State<MyApp> {
  35.   bool loggedIn = false;
  36.   @override
  37.   Widget build(BuildContext context) {
  38.     return FutureBuilder<bool>(
  39.       future: get_login(),
  40.       builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
  41.         if (snapshot.data== false){
  42.           return MaterialApp(home: PhoneAuth(),);
  43.         }else{
  44.           return MaterialApp(home: HomePage(user),);
  45.         }
  46.       },
  47.     );
  48.   }
  49. }
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63. ======================================== PhoneAuth.dart ======================================
  64. import 'package:country_pickers/country.dart';
  65. import 'package:flutter/material.dart';
  66. import 'package:country_pickers/country_pickers.dart';
  67. import 'package:firebase_auth/firebase_auth.dart';
  68. import 'HomePage.dart';
  69. import 'package:shared_preferences/shared_preferences.dart';
  70. import 'main.dart';
  71.  
  72.  
  73. class PhoneAuth extends StatefulWidget {
  74.   @override
  75.   _PhoneAuthState createState() => _PhoneAuthState();
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83. class _PhoneAuthState extends State<PhoneAuth> {
  84.  
  85. String name;
  86.  
  87.   Country _selectedDialogCountry =
  88.       CountryPickerUtils.getCountryByPhoneCode('62');
  89.  
  90.   final TextEditingController _phoneController = new TextEditingController();
  91.   final TextEditingController _smsController = new TextEditingController();
  92.   String _phoneCode = '62';
  93.  
  94.   String verificationId;
  95.   FirebaseUser user;
  96.   var _keyField = GlobalKey<FormFieldState>();
  97.  
  98.   Widget _buildDialogItem(Country country) => Row(
  99.         children: <Widget>[
  100.           CountryPickerUtils.getDefaultFlagImage(country),
  101.           SizedBox(width: 8.0),
  102.           Text("+${country.phoneCode}"),
  103.           SizedBox(width: 8.0),
  104.           Flexible(child: Text(country.name))
  105.         ],
  106.       );
  107.  
  108.   void _openCountryPickerDialog() => showDialog(
  109.         context: context,
  110.         builder: (context) => Theme(
  111.             data: Theme.of(context).copyWith(primaryColor: Colors.orange),
  112.             child: CountryPickerDialog(
  113.               titlePadding: EdgeInsets.all(8.0),
  114.               searchCursorColor: Colors.orange,
  115.               searchInputDecoration: InputDecoration(hintText: 'Search...'),
  116.               isSearchable: true,
  117.               title: Text('Select your phone code'),
  118.               onValuePicked: (Country country) {
  119.                 print("${country.name}");
  120.                 print("${country.phoneCode}");
  121.                 print(_selectedDialogCountry);
  122.                 setState(() {
  123.                   _selectedDialogCountry = country;
  124.                   this._phoneCode = country.phoneCode;
  125.                   itemBuilder:
  126.                   _buildDialogItem;
  127.                 });
  128.               },
  129.             )),
  130.       );
  131.  
  132.   Future<void> verifyPhone(BuildContext context) async {
  133.     try {
  134.       final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
  135.         this.verificationId = verId;
  136.       };
  137.  
  138.       final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
  139.         this.verificationId = verId;
  140.         smsCodeDialog(context).then((value) {
  141.           print('Signed in');
  142.         });
  143.       };
  144.  
  145.       final PhoneVerificationCompleted verifiedSuccess = (FirebaseUser user) {
  146.            
  147.         if (user != null) {
  148.                         sdg_msk=true;
  149.           print("Successful verification user is: +${_phoneCode + _phoneController.text.trim()}");
  150.           no_hp= "+${_phoneCode + _phoneController.text.trim()}";
  151.           Navigator.push(
  152.               context, MaterialPageRoute(builder: (context) => HomePage(user)));
  153.         } else {
  154.           print("user is null");
  155.         }
  156.       };
  157.  
  158.       final PhoneVerificationFailed veriFailed = (AuthException exception) {
  159.         print('Failed verification: ${exception.message}');
  160.       };
  161. String temp = "${_phoneCode + _phoneController.text.trim()}";
  162.  
  163.       await FirebaseAuth.instance.verifyPhoneNumber(
  164.          phoneNumber : (temp == null) ? "" : temp,
  165.           codeAutoRetrievalTimeout: autoRetrieve,
  166.           codeSent: smsCodeSent,
  167.           timeout: const Duration(seconds: 5),
  168.           verificationCompleted: verifiedSuccess,
  169.           verificationFailed: veriFailed);
  170.     } catch (e) {
  171.       print("error: $e");
  172.     }
  173.   }
  174.  
  175.   Future<bool> smsCodeDialog(BuildContext context) {
  176.     return showDialog(
  177.         context: context,
  178.         barrierDismissible: false,
  179.         builder: (BuildContext context) {
  180.           return new AlertDialog(
  181.             title: Text('Enter sms Code'),
  182.             content: TextField(
  183.               keyboardType: TextInputType.number,
  184.               controller: _smsController,
  185.             ),
  186.             contentPadding: EdgeInsets.all(10.0),
  187.             actions: <Widget>[
  188.               new FlatButton(
  189.                 child: Text('Done'),
  190.                 onPressed: () async {
  191.                   AuthCredential credential = PhoneAuthProvider.getCredential(
  192.                     verificationId: this.verificationId,
  193.                     smsCode: _smsController.text.trim(),
  194.                   );
  195.  
  196.                   user = await FirebaseAuth.instance
  197.                       .signInWithCredential(credential)
  198.                       .then((user) {
  199.                     if (user != null) {
  200.                       Navigator.of(context).pop();
  201.                       Navigator.push(
  202.                           context,
  203.                           MaterialPageRoute(
  204.                               builder: (context) => HomePage(user)));
  205.                     } else {
  206.                       print("Failed verification");
  207.                     }
  208.                   }).catchError((e) {
  209.                     print("error: $e");
  210.                   });
  211.                 },
  212.               )
  213.             ],
  214.           );
  215.         });
  216.   }
  217.  
  218.   // login shared prefs
  219.   bool alreadyLogin = false;
  220.   @override
  221.   Widget build(BuildContext context) {
  222.     return MaterialApp(
  223. home: Scaffold(
  224.       body: SafeArea(
  225.         child: Center(
  226.             child: SingleChildScrollView(
  227.                 child: Center(
  228.           child: Column(
  229.             crossAxisAlignment: CrossAxisAlignment.center,
  230.             mainAxisAlignment: MainAxisAlignment.center,
  231.             children: <Widget>[
  232.               FractionallySizedBox(
  233.                 widthFactor: 0.7,
  234.                 child: Column(
  235.                   crossAxisAlignment: CrossAxisAlignment.center,
  236.                   children: <Widget>[
  237.                     ListTile(
  238.                         onTap: _openCountryPickerDialog,
  239.                         title: _buildDialogItem(_selectedDialogCountry)),
  240.                     Container(
  241.                       width: 170,
  242.                       child: TextFormField(
  243.                         key: _keyField,
  244.                         controller: _phoneController,
  245.                         keyboardType: TextInputType.phone,
  246.                         decoration: InputDecoration(
  247.                           labelText: "Nomor Telepon",
  248.                           prefixText: "+${_phoneCode} ",
  249.                           counterText: 'masukkan tanpa angka 0',
  250.                         ),
  251.                         validator: (val) {
  252.                           if (val.isEmpty) {
  253.                             return "this field cannot be empty";
  254.                           }
  255.                         },
  256.                       ),
  257.                     )
  258.                   ],
  259.                 ),
  260.               ),
  261.               new RaisedButton(
  262.                 child: new Text("Verifikasi"),
  263.                 color: Colors.orange.shade800,
  264.                 textColor: Colors.white,
  265.                 onPressed: () async {
  266.                   if (_phoneCode != null) {
  267.                     if (_keyField.currentState.validate()) {
  268.                       name="+${_phoneCode + _phoneController.text.trim()}";
  269.                       print(name);
  270.                       verifyPhone(context);
  271.                      
  272.                      
  273.                                            }
  274.                                          }
  275.                                        },
  276.                                      ),
  277.                                    ],
  278.                                  ),
  279.                                ))),
  280.                            
  281.                              ),
  282.                        ),
  283.                            ); }
  284.                        
  285.                          
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement