Home > Software engineering >  I can't get a function to work from another file
I can't get a function to work from another file

Time:10-07

I have a function start timer that requires a stateful widget and I need it to be called in another Class which is also a stateful widget class, I have tried making an object of the class PhoneAuthState phone = PhoneAuthState() and taping it into the function but the timer wouldn't start counting down after pressing the send button,

Here is the first class

`class PhoneAuth extends StatefulWidget {
 const PhoneAuth({Key? key}) : super(key: key);

  @override
  State<PhoneAuth> createState() => PhoneAuthState();
}

class PhoneAuthState extends State<PhoneAuth> {
  int start = 30;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     ReusableTField(),
     RichText(
        text: TextSpan(children: [
          TextSpan(
            text: "Send OTP again in",
            style: TextStyle(color: Colors.orange, fontSize: 17),
          ),
          TextSpan(
            text: " 00:$start",
            style: TextStyle(color: Colors.redAccent, fontSize: 17),
          ),
          TextSpan(
            text: "sec",
            style: TextStyle(color: Colors.orange, fontSize: 17),
          ),
        ]),
      ),
      


  **Here is the function below**

  void startTimer() {
    const onsec = Duration(seconds: 1);
    Timer timer = Timer.periodic(onsec, (timer) {
      if (start == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          start--;
        });
      }
    });

     `

Then this is the class(in another file) that needs the function to start counting down when the send button is tapped nothing happens on the emulator, even after the startTimer contains setState

  class ReusableTField extends StatefulWidget {

  @override
  State<ReusableTField> createState() => _ReusableTFieldState();

}

class _ReusableTFieldState extends State<ReusableTField> {
   @override
  Widget build(BuildContext context) {

    return Container(
     suffixIcon: InkWell(
            onTap: () {} // Here is where I called the function with  PhoneAuthState phone = 
                         // PhoneAuthState()... phone.startTimer() but the code does not work,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 14),
               child: Text(),
            ),
          )

CodePudding user response:

if you want to use the same code on multiple classes define a static class and write this method as a static method and call it from anywhere.

CodePudding user response:

I think you function is at wrong place keep it out of build method and then call.

  • Related