Home > Enterprise >  Best way to use the setState in a method for two classes in Flutter
Best way to use the setState in a method for two classes in Flutter

Time:09-23

I have a doubt, i am new in Flutter and i want to know if there is a better way to do what i want, please see the next example of code.

This is my screen and i have to classes, one is for when the device height is less than 800 and the other when is higher

class MyPageExample extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    var screenSize = MediaQuery.of(context).size;
    
    return Scaffold(
      body: SafeArea(
        child: screenSize.height > 800
                ? SignupLarge()
                : SignupSmall()
      )
    );
  }
}

This are my two StatefulWidgets

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

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

class _SingupLargeState extends State<SignupLarge> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Wome widgets...
        ElevatedButton(
          onPressed: () => signupToFirebase(),
          child: Text('Click me')
        )
      ],
    );
  }
}

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

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

class _SignupSmallState extends State<SignupSmall> {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        // Wome widgets...
        ElevatedButton(
          onPressed: () => signupToFirebase(),
          child: Text('Click me')
        )
      ],
    );
  }
}


signupToFirebase(){
  // I need to use setState here to show the loading widget
  // await Firebase.instance.signupWithEmailAndPassword... 
  // I need to use setState here to hide the loading widget
}

What i want to do is use the method in my classes using the setState, actually i cant because my method is not inside my classes but if i put my method inside i cant use the same method in both classes.

the above code is just an example of how my code looks like, im tryng to show a loading when a user is signed up.

Someone knows the right way to use the setState for my method using the both classes?

CodePudding user response:

You can give that function another function for it to call.

void signupToFirebase(void Function() whenDone) {
  //...
  whenDone();
}

...
  // caller
  signupToFirebase(() {
    setState(() {

    });
  });
...


Or even better, you can have that function return a Future if what you wanted to do is to act once it's done.

Future<void> signupToFirebase() {
  await FirebaseAuth.instance... signup() kind of function that returns a Future
}

...
  // caller
  await signupToFirebase();
  setState(() {

  });
...

  • Related