Home > Enterprise >  How can i use ref in flutter static widget without using ConsumerStatefulWidget
How can i use ref in flutter static widget without using ConsumerStatefulWidget

Time:11-01

I want to use ref.read() in the widget I created. But it requires ConsumerStatefulWidget to use. how can i use ref.read() in widget below.

    class LoginWidget{
  static SizedBox buildLogin(BuildContext context,TextEditingController email,TextEditingController password){
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          const SizedBox(height: 50),
          emailTextField(),
          const SizedBox(height: 15),
          passwordTextField(),
          const SizedBox(height: 15),
          loginButton(context),
          const SizedBox(height: 15),
          buildBoldText("Or",Colors.black),
          const SizedBox(height: 15),
          icons(context),
          const SizedBox(height: 15),
          buildBoldText("Forgot your password?", Colors.blue),
          const SizedBox(height: 45),
        ],
      ),
    );
  }

CodePudding user response:

Hmmm you have some options but the best is not use a static method because is a bad practice.

Anyway the solutions are:

  1. Pass the WidgetRef into the buildLogin
  2. Convert your LoginWidget into a provider
  3. Convert the widget into a ConsumerWidget or ConsumerStatefulWidget (best option)

CodePudding user response:

you can wrap your Column with Consumer widget like so to get access to the ref object.

    class LoginWidget{
  static SizedBox buildLogin(BuildContext context,TextEditingController email,TextEditingController password){
    return SizedBox(
          width: MediaQuery.of(context).size.width,
          child: Consumer(
            builder: (_, ref, __) {
              // you can now access the ref object here.
            //  Ex. final provider = ref.watch(testProvider);
              return Column(
                children: [
                  const SizedBox(height: 50),
                  emailTextField(),
                  const SizedBox(height: 15),
                  passwordTextField(),
                  const SizedBox(height: 15),
                  loginButton(context),
                  const SizedBox(height: 15),
                  buildBoldText("Or",Colors.black),
                  const SizedBox(height: 15),
                  icons(context),
                  const SizedBox(height: 15),
                  buildBoldText("Forgot your password?", Colors.blue),
                  const SizedBox(height: 45),
                ],
              );
            }
          ),
        );
   
  }

  • Related