Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ===================================================== main.dart =====================================================================
- import 'package:flutter/material.dart';
- import 'HomePage.dart';
- import 'PhoneAuth.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:firebase_auth/firebase_auth.dart';
- bool sdg_msk=false;
- String no_hp;
- void Savemasuk() async {
- SharedPreferences pref = await SharedPreferences.getInstance();
- pref.setBool("lg_msk", sdg_msk);
- pref.setString("nomorhp", no_hp);
- }
- Future<bool> get_login() async {
- SharedPreferences pref = await SharedPreferences.getInstance();
- pref.getBool("lg_msk") == null ? false : true;}
- Future<String> get_akun() async { // = 'tidak ada nama'
- SharedPreferences pref = await SharedPreferences.getInstance();
- return pref.getString("nomorhp") ?? "tidak ada nomor hp";
- }
- void main() {
- runApp(new MyApp());
- }
- class MyApp extends StatefulWidget {
- @override
- _MyAppState createState() => _MyAppState();
- }
- FirebaseUser user;
- class _MyAppState extends State<MyApp> {
- bool loggedIn = false;
- @override
- Widget build(BuildContext context) {
- return FutureBuilder<bool>(
- future: get_login(),
- builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
- if (snapshot.data== false){
- return MaterialApp(home: PhoneAuth(),);
- }else{
- return MaterialApp(home: HomePage(user),);
- }
- },
- );
- }
- }
- ======================================== PhoneAuth.dart ======================================
- import 'package:country_pickers/country.dart';
- import 'package:flutter/material.dart';
- import 'package:country_pickers/country_pickers.dart';
- import 'package:firebase_auth/firebase_auth.dart';
- import 'HomePage.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'main.dart';
- class PhoneAuth extends StatefulWidget {
- @override
- _PhoneAuthState createState() => _PhoneAuthState();
- }
- class _PhoneAuthState extends State<PhoneAuth> {
- String name;
- Country _selectedDialogCountry =
- CountryPickerUtils.getCountryByPhoneCode('62');
- final TextEditingController _phoneController = new TextEditingController();
- final TextEditingController _smsController = new TextEditingController();
- String _phoneCode = '62';
- String verificationId;
- FirebaseUser user;
- var _keyField = GlobalKey<FormFieldState>();
- Widget _buildDialogItem(Country country) => Row(
- children: <Widget>[
- CountryPickerUtils.getDefaultFlagImage(country),
- SizedBox(width: 8.0),
- Text("+${country.phoneCode}"),
- SizedBox(width: 8.0),
- Flexible(child: Text(country.name))
- ],
- );
- void _openCountryPickerDialog() => showDialog(
- context: context,
- builder: (context) => Theme(
- data: Theme.of(context).copyWith(primaryColor: Colors.orange),
- child: CountryPickerDialog(
- titlePadding: EdgeInsets.all(8.0),
- searchCursorColor: Colors.orange,
- searchInputDecoration: InputDecoration(hintText: 'Search...'),
- isSearchable: true,
- title: Text('Select your phone code'),
- onValuePicked: (Country country) {
- print("${country.name}");
- print("${country.phoneCode}");
- print(_selectedDialogCountry);
- setState(() {
- _selectedDialogCountry = country;
- this._phoneCode = country.phoneCode;
- itemBuilder:
- _buildDialogItem;
- });
- },
- )),
- );
- Future<void> verifyPhone(BuildContext context) async {
- try {
- final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
- this.verificationId = verId;
- };
- final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
- this.verificationId = verId;
- smsCodeDialog(context).then((value) {
- print('Signed in');
- });
- };
- final PhoneVerificationCompleted verifiedSuccess = (FirebaseUser user) {
- if (user != null) {
- sdg_msk=true;
- print("Successful verification user is: +${_phoneCode + _phoneController.text.trim()}");
- no_hp= "+${_phoneCode + _phoneController.text.trim()}";
- Navigator.push(
- context, MaterialPageRoute(builder: (context) => HomePage(user)));
- } else {
- print("user is null");
- }
- };
- final PhoneVerificationFailed veriFailed = (AuthException exception) {
- print('Failed verification: ${exception.message}');
- };
- String temp = "${_phoneCode + _phoneController.text.trim()}";
- await FirebaseAuth.instance.verifyPhoneNumber(
- phoneNumber : (temp == null) ? "" : temp,
- codeAutoRetrievalTimeout: autoRetrieve,
- codeSent: smsCodeSent,
- timeout: const Duration(seconds: 5),
- verificationCompleted: verifiedSuccess,
- verificationFailed: veriFailed);
- } catch (e) {
- print("error: $e");
- }
- }
- Future<bool> smsCodeDialog(BuildContext context) {
- return showDialog(
- context: context,
- barrierDismissible: false,
- builder: (BuildContext context) {
- return new AlertDialog(
- title: Text('Enter sms Code'),
- content: TextField(
- keyboardType: TextInputType.number,
- controller: _smsController,
- ),
- contentPadding: EdgeInsets.all(10.0),
- actions: <Widget>[
- new FlatButton(
- child: Text('Done'),
- onPressed: () async {
- AuthCredential credential = PhoneAuthProvider.getCredential(
- verificationId: this.verificationId,
- smsCode: _smsController.text.trim(),
- );
- user = await FirebaseAuth.instance
- .signInWithCredential(credential)
- .then((user) {
- if (user != null) {
- Navigator.of(context).pop();
- Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => HomePage(user)));
- } else {
- print("Failed verification");
- }
- }).catchError((e) {
- print("error: $e");
- });
- },
- )
- ],
- );
- });
- }
- // login shared prefs
- bool alreadyLogin = false;
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- home: Scaffold(
- body: SafeArea(
- child: Center(
- child: SingleChildScrollView(
- child: Center(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- FractionallySizedBox(
- widthFactor: 0.7,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- ListTile(
- onTap: _openCountryPickerDialog,
- title: _buildDialogItem(_selectedDialogCountry)),
- Container(
- width: 170,
- child: TextFormField(
- key: _keyField,
- controller: _phoneController,
- keyboardType: TextInputType.phone,
- decoration: InputDecoration(
- labelText: "Nomor Telepon",
- prefixText: "+${_phoneCode} ",
- counterText: 'masukkan tanpa angka 0',
- ),
- validator: (val) {
- if (val.isEmpty) {
- return "this field cannot be empty";
- }
- },
- ),
- )
- ],
- ),
- ),
- new RaisedButton(
- child: new Text("Verifikasi"),
- color: Colors.orange.shade800,
- textColor: Colors.white,
- onPressed: () async {
- if (_phoneCode != null) {
- if (_keyField.currentState.validate()) {
- name="+${_phoneCode + _phoneController.text.trim()}";
- print(name);
- verifyPhone(context);
- }
- }
- },
- ),
- ],
- ),
- ))),
- ),
- ),
- ); }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement