How to access methods in one class an call it in another classes method in flutter (dart)

0

I have a method called handleSignIn. I want to call it inside a class that handles sign in when the screen orientantion is mobile. How can I access the method from one class to another class?

this is my first class

class _SignInState extends State<SignIn> {

  @override
  void initState() {
    super.initState();
    MsalMobile.create('assets/auth_config.json', authority).then((client) {
      setState(() {
        msal = client;
      });
      refreshSignedInStatus();
    });
  }

  /// Signs a user in
  void handleSignIn() async {
    await msal.signIn(null, [SCOPE]).then((result) {
      // ignore: unnecessary_statements
      refreshSignedInStatus();
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        final ex = exception as Exception;
        print('exception occurred');
        print(ex.toString());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        backgroundColor: Color(0xff392850),
        body: Responsive(
          mobile: _HomeScreenMobile(
          ),
         // desktop: _HomeScreenDesktop(),
        ),
      ),
    );
  }
}

my _HomeScreenMobile class

class _HomeScreenMobile extends StatelessWidget{
  bool isSignedIn = false;

  Widget build(BuildContext context) {
   ProgressDialog progressDialog  = ProgressDialog(context, type:ProgressDialogType.Normal, isDismissible: false, );
    progressDialog.style(message: "Signing you in ...");
    return Scaffold(
      body: Builder(
        builder: (context) => Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Image.asset('assets/landing.webp',
                  fit: BoxFit.fill,
                  color: Color.fromRGBO(255, 255, 255, 0.6),
                  colorBlendMode: BlendMode.modulate),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                SizedBox(height: 10.0),
                Container(
                  width: 130.0,
                  child: Align(
                      alignment: Alignment.center,
                      child: RaisedButton(
                          shape: RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30.0)),
                          color: Color(0xffffffff),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Icon(
                                FontAwesomeIcons.microsoft,
                                color: Color(0xFF01A6F0),
                              ),
                              // Visibility(
                              //   visible: !isSignedIn,
                              SizedBox(width: 10.0),
                              Visibility(
                                visible: !isSignedIn,
                                child: Text(
                                  'Sign in',
                                  style: TextStyle(
                                      color: Colors.black, fontSize: 18.0),
                                ),
                              ),
                            ],
                          ),
                          onPressed: () => {
                            progressDialog.show(),
                            handleSignIn(),
                     
                          })),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

how can I access handleSign from _HomeScreenMobile without it throwing the error The method 'handleSignIn' isn't defined for the type '_HomeScreenMobile'.. Have tried going through the example shared no luck

flutter
dart
asked on Stack Overflow Dec 13, 2020 by blackbird

2 Answers

1

HomeScreenMobile could get its reference as a parameter and call it whenever it's necessary.

class _HomeScreenMobile extends StatelessWidget{
  bool isSignedIn = false;
  _HomeScreenMobile({this.handleSignInReference});
  final Future<void> Function() handleSignInReference;
...
  onPressed: () => {
     progressDialog.show(),
     handleSignInReference(),
  }
}

Finally, where you call this class:

Responsive(
  mobile: _HomeScreenMobile(
      handleSignInReference:handleSignIn
  ),
)
answered on Stack Overflow Dec 13, 2020 by Luis Utrera
0

You could create a handle_signin.dart file:

  void handleSignIn() async {
    await msal.signIn(null, [SCOPE]).then((result) {
      refreshSignedInStatus();
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        final ex = exception as Exception;
        print('exception occurred');
        print(ex.toString());
      }
    });
  }

Import it wherever you need it:

import './handle_signin.dart`;

And use it:

@override
Widget build() {
 return Scaffold(body: Center(GestureDetector(onTap: () async { await handleSignIn(); })));
}

Important note: while the code above might work for your case, it's highly recommended that you consider more sophisticated approaches to state management and Widget communication, such as BLoC.

answered on Stack Overflow Dec 13, 2020 by Stefano A.

User contributions licensed under CC BY-SA 3.0