【问题标题】:How to access methods in one class an call it in another classes method in flutter (dart)如何访问一个类中的方法并在flutter(dart)中的另一个类方法中调用它
【发布时间】:2021-03-24 08:49:32
【问题描述】:

我有一个名为 handleSignIn 的方法。我想在一个处理屏幕方向移动时登录的类中调用它。如何从一个类访问另一个类的方法?

这是我的第一堂课

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(),
        ),
      ),
    );
  }
}

我的 _HomeScreenMobile 类

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(),
                     
                          })),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

如何从 _HomeScreenMobile 访问 handleSign 而不会引发错误 The method 'handleSignIn' isn't defined for the type '_HomeScreenMobile'.。已尝试通过示例共享没有运气

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以创建一个handle_signin.dart 文件:

      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 './handle_signin.dart`;
    

    并使用它:

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

    重要提示:虽然上面的代码可能适用于您的情况,但强烈建议您考虑更复杂的状态管理和Widget 通信方法,例如BLoC

    【讨论】:

    • 如果我只想从主文件访问它而不是创建另一个文件?并在按钮单击时访问 handleSignIn()?
    【解决方案2】:

    HomeScreenMobile 可以将其引用作为参数并在需要时调用它。

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

    最后,你在哪里调用这个类:

    Responsive(
      mobile: _HomeScreenMobile(
          handleSignInReference:handleSignIn
      ),
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      相关资源
      最近更新 更多