how to make an otp time countdown by saving the time if the otp time has not run out

0

I want to make an application that has registration in it. but i have difficulty in making otp verification. someone can tell me to create an otp like whatsapp, so if I have filled in the mulir form and pressed next, it will send the otp code and the application displays the form to enter the otp while waiting for otp there will be a timecountdown for 15 minutes. what I am asking is how when less than 15 minutes press it again, the application will come out and when it opens again within 15 it has not run out then it will return to the OTP page, and when the OTP time has run out, it will be moved to the registration page.

I have created the registration page and the OTP verification page.

this is what I have tried and failed.

lass RegistrasiOTP extends StatefulWidget {
  final String noTelp;
  RegistrasiOTP({
    this.noTelp,
    this.token,
  });
  TokenModel token;

  @override
  _RegistrasiOTPState createState() => _RegistrasiOTPState();
}

class _RegistrasiOTPState extends State<RegistrasiOTP> {
  Timer _timer;
  int seconds;
  var otp1 = TextEditingController();
  var otp2 = TextEditingController();
  var otp3 = TextEditingController();
  var otp4 = TextEditingController();
  String tokenSF = "";
  bool kirimUlang = true;
  String _nama;
  String _noHp;
  String _pin;
  String _deviceId;

  Future getToken() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    tokenSF = pref.getString('token');
  }

  String strukturWaktu(int seconds) {
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    return formatTime(minute) + ":" + formatTime(second);
  }

  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  Future setWaktuReg(String value) async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.setString("waktuReg", value);
  }

  Future removeWaktu() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.remove("waktuReg");
  }

  @override
  void initState() {
    super.initState();
    var now = DateTime.now();
    var twoHours = now.add(Duration(minutes: 15)).difference(now);
    seconds = twoHours.inSeconds;
    startTimer();

    getNamaReg().then((value) {
      setState(() {
        _nama = value;
      });
    });

    getNoHpReg().then((value) {
      setState(() {
        _noHp = value;
      });
    });

    getPinReg().then((value) {
      setState(() {
        _pin = value;
      });
    });

    getDeviceId().then((value) {
      setState(() {
        _deviceId = value;
      });
    });
  }

  void startTimer() {
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      setState(() {
        seconds--;
        if (seconds == 0) {
          setState(() {
            kirimUlang = !kirimUlang;
          });
          cancelTimer();
        }
      });
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        child: Stack(children: <Widget>[
          SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      margin: EdgeInsets.fromLTRB(0, 80, 0, 10),
                      child: Image.asset('assets/images/img_otp.png')),
                ),
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: Text(
                        'Verifikasi OTP',
                        style: TextStyle(
                            fontFamily: 'Roboto',
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                            fontSize: 20),
                      )),
                ),
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: Text(
                        'Kode OTP telah dikirimkan ke nomor',
                        style: TextStyle(
                          color: Colors.black,
                          fontFamily: 'Roboto',
                          fontSize: 13,
                        ),
                      )),
                ),
                Align(
                  child: Container(
                    margin: EdgeInsets.fromLTRB(40, 10, 40, 10),
                    child: TextField(
                      readOnly: true,
                      textAlign: TextAlign.center,
                      decoration: InputDecoration(
                        hintText: widget.noTelp,
                        contentPadding: EdgeInsets.all(10),
                        hintStyle: TextStyle(
                          fontSize: 20.0,
                          color: Color(0xFF000000),
                          fontWeight: FontWeight.bold,
                        ),
                        fillColor: Color(0xFFFFFFFF),
                        filled: true,
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: Color(0xFF39CE65)),
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: Color(0xFF39CE65)),
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: Text(
                        'Salah Nomor Telepon?',
                        style: TextStyle(
                          color: Color(0xFF00913F),
                          fontFamily: 'Roboto',
                          fontSize: 13,
                        ),
                      )),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 40, 0, 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 50,
                        height: 50,
                        child: Card(
                          elevation: 5,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10)),
                          child: Stack(
                            children: <Widget>[
                              Center(
                                child: Icon(
                                  Icons.fiber_manual_record,
                                  size: 10,
                                  color: Colors.grey,
                                ),
                              ),
                              Container(
                                margin: EdgeInsetsDirectional.only(bottom: 7),
                                child: TextField(
                                  controller: otp1,
                                  keyboardType: TextInputType.number,
                                  textInputAction: TextInputAction.next,
                                  onEditingComplete: () =>
                                      FocusScope.of(context).nextFocus(),
                                  textAlign: TextAlign.center,
                                  maxLength: 1,
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    counterText: '',
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        width: 50,
                        height: 50,
                        child: Card(
                          elevation: 5,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10)),
                          child: Stack(
                            children: <Widget>[
                              Center(
                                child: Icon(
                                  Icons.fiber_manual_record,
                                  size: 10,
                                  color: Colors.grey,
                                ),
                              ),
                              Container(
                                margin: EdgeInsetsDirectional.only(bottom: 7),
                                child: TextField(
                                  controller: otp2,
                                  keyboardType: TextInputType.number,
                                  textInputAction: TextInputAction.next,
                                  onEditingComplete: () =>
                                      FocusScope.of(context).nextFocus(),
                                  textAlign: TextAlign.center,
                                  maxLength: 1,
                                  decoration: InputDecoration(
                                      border: InputBorder.none,
                                      counterText: ''),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        width: 50,
                        height: 50,
                        child: Card(
                          elevation: 5,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10)),
                          child: Stack(
                            children: <Widget>[
                              Center(
                                child: Icon(
                                  Icons.fiber_manual_record,
                                  size: 10,
                                  color: Colors.grey,
                                ),
                              ),
                              Container(
                                margin: EdgeInsetsDirectional.only(bottom: 7),
                                child: TextField(
                                  controller: otp3,
                                  keyboardType: TextInputType.number,
                                  textInputAction: TextInputAction.next,
                                  onEditingComplete: () =>
                                      FocusScope.of(context).nextFocus(),
                                  textAlign: TextAlign.center,
                                  maxLength: 1,
                                  decoration: InputDecoration(
                                      border: InputBorder.none,
                                      counterText: ''),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        width: 50,
                        height: 50,
                        child: Card(
                          elevation: 5,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10)),
                          child: Stack(
                            children: <Widget>[
                              Center(
                                child: Icon(
                                  Icons.fiber_manual_record,
                                  size: 10,
                                  color: Colors.grey,
                                ),
                              ),
                              Container(
                                margin: EdgeInsetsDirectional.only(bottom: 7),
                                child: TextField(
                                  controller: otp4,
                                  onChanged: (text) async {
                                    await getToken();

                                    print('tes hit otp');
                                    print('otp : ');
                                    print(otp1.text +
                                        otp2.text +
                                        otp3.text +
                                        otp4.text);
                                    print('no telp : ');
                                    print(widget.noTelp);
                                    print('token : ');
                                    print(tokenSF);

                                    TokenBloc tokenBloc = new TokenBloc();
                                    tokenBloc.getverOTPRegistrasi(
                                        widget.token.token,
                                        widget.noTelp,
                                        otp1.text +
                                            otp2.text +
                                            otp3.text +
                                            otp4.text);

                                    print('finish hit ver OTP');
                                    tokenBloc.verOTPRegistrasi.listen((event) {
                                      if (event.rc == '00') {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) =>
                                                RegistrasiSukses(),
                                          ),
                                        );
                                      } else {
                                        showToast(context, event.rcDesc);
                                        print("OTP yang anda masukan salah");
                                      }
                                    });
                                  },
                                  keyboardType: TextInputType.number,
                                  textInputAction: TextInputAction.next,
                                  onEditingComplete: () =>
                                      FocusScope.of(context).nextFocus(),
                                  textAlign: TextAlign.center,
                                  maxLength: 1,
                                  decoration: InputDecoration(
                                      border: InputBorder.none,
                                      counterText: ''),
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
                  child: Align(
                    alignment: Alignment.center,
                    child: Container(
                        margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        child: GestureDetector(
                          onTap: () {
                            if (seconds != 0) {
                              showToast(
                                  context,
                                  "Silahkan Menunggu " +
                                      strukturWaktu(seconds) +
                                      " Lagi !");
                            } else if (seconds == 0) {
                              setState(() {
                                kirimUlang = !kirimUlang;
                              });

                              var now = DateTime.now();
                              var twoHours = now
                                  .add(Duration(minutes: 15))
                                  .difference(now);
                              seconds = twoHours.inSeconds;
                              startTimer();
                              TokenBloc tokenBloc = new TokenBloc();
                              tokenBloc.daftar(widget.token.token, _noHp,
                                  _deviceId, _nama, _pin);
                              print("Otp Baru Telah Dikirim...");
                              print(widget.token.token);
                              print(_noHp);
                              print(_deviceId);
                              print(_nama);
                              print(_pin);
                              startTimer();
                            }
                          },
                          child: Text(
                            'KIRIM ULANG' + '(' + strukturWaktu(seconds) + ')',
                            style: TextStyle(
                              color: (kirimUlang)
                                  ? Color(0xFFCCCCCC)
                                  : Colors.green,
                              fontFamily: 'Roboto',
                              fontSize: 13,
                            ),
                          ),
                        )),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: 70,
            color: Colors.white,
            child: Align(
              alignment: Alignment.topLeft,
              child: Container(
                  margin: EdgeInsets.fromLTRB(40, 30, 0, 0),
                  child: GestureDetector(
                    onTap: () {
                      if (seconds != 0) {
                        setState(() async {
                          setWaktuReg(strukturWaktu(seconds));
                          print("aktivitas telah di simpan " +
                              strukturWaktu(seconds));
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => MyLandingPage()));
                        });
                      }
                      // else if (seconds == 0) {
                      //   Navigator.pop(context);
                      // }
                    },
                    child: Icon(
                      Icons.keyboard_arrow_left,
                      color: Colors.black,
                      size: 30,
                    ),
                  )),
            ),
          ),
        ]),
      ),
    );
  }
}

flutter
flutter-layout
flutter-dependencies
flutter-test
asked on Stack Overflow Oct 5, 2020 by Irvan Thole

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0