flutter Azure AD 身份验证 : How to display the user email and name retrieved during login to another screen

标签 flutter dart

我是 Flutter 新手,我已成功从 Azure AD Auth 检索到用户电子邮件和用户名。但我想在主屏幕的文本小部件中显示它。如何将登录类中的用户名发送到主屏幕并显示名称?
登入

class _SignInState extends State<SignIn> {
  MsalMobile msal;
  bool isSignedIn = false;

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

  /// Updates the signed in state
  refreshSignedInStatus() {
    msal.getSignedIn().then((loggedIn) {
      print('refreshing');
      setState(() {
        isSignedIn = loggedIn;

        if(isSignedIn) {
          // Your navigation code
          Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                  builder: (context) => NavScreen()));
        }
      });
    });
  }

  /// Signs a user in
  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());
      }
    }
    );
  }

  logMsalMobileError(MsalMobileException exception) {
    print('${exception.errorCode}: ${exception.message}');
    if (exception.innerException != null) {
      print(
          'inner exception = ${exception.innerException.errorCode}: ${exception.innerException.message}');
    }
  }

  /// Signs a user out.
  handleSignOut() async {
    try {
      print('signing out');
      await msal.signOut();
      print('signout done');
      refreshSignedInStatus();
    } on MsalMobileException catch (exception) {
      logMsalMobileError(exception);
    }
  }

  /// Gets the current and prior accounts.
  handleGetAccount() async {
    await msal.getAccount().then((result) {
      if (result.currentAccount != null) {
        return result.currentAccount.username;
      } else {
        print('no account found');
      }
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        print('exception occurred');
      }
    });
  }
主屏幕
class _HomeScreenDesktop extends StatelessWidget {
  final SignIn handleGetAccount;
  final TrackingScrollController scrollController;
  const _HomeScreenDesktop({Key key, this.scrollController, this.handleGetAccount}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Flexible(
          flex: 2,
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: MoreOptionsList(currentUser: currentUser),
            ),
          ),
        ),
        const Spacer(),
        Container(
          height: 1000.0,
            width: 600.0,
            child: ListView(
              controller: scrollController,
              children: <Widget>[
                SizedBox(
                  height: 30,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 16, right: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            "Show Retrieved username from azure account",
                            style: GoogleFonts.openSans(
                                textStyle: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold)),
                          ),
                          SizedBox(
                            height: 4,
                          ),
                        ],
                      ),
                      IconButton(
                        alignment: Alignment.topRight,
                        icon: Image.asset(
                          "assets/notification.png",
                          width: 24,
                        ),
                        onPressed: () => {},
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                GridDashboardwe()
              ],
            )),
        const Spacer(),
        Flexible(
          flex: 2,
          child: Container(
            color: Color(0xff392850) ,
          ),
        )
      ],
    );
  }
}
我在登录屏幕上使用此方法来获取帐户详细信息
/// Gets the current and prior accounts.
  handleGetAccount() async {
    await msal.getAccount().then((result) {
      if (result.currentAccount != null) {
        return result.currentAccount.username;
      } else {
        print('no account found');
      }
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        print('exception occurred');
      }
    });
  }

最佳答案

您需要通过 SignIn 中的参数传递用户对象类到_HomeScreenDesktop小部件。此外,您应该将主屏幕小部件设为公开而不是私有(private)。在类名前使用下划线表示它是私有(private)的,即使用 HomeScreenDesktop而不是 _HomeScreenDesktop .
还请指定方法的返回类型,这将非常有帮助。
更新 handleGetAccount方法:

Future<dynamic> handleGetAccount() async { // <-- Replace dynamic with type of currentAccount
    await msal.getAccount().then((result) {
      if (result.currentAccount != null) {
        return result.currentAccount;
      } else {
        print('no account found');
        return null;
      }
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        print('exception occurred');
        return null;
      }
    });
调用方法handleGetAccount获取当前登录用户,然后您可以将此用户对象传递给 HomeScreenWidget ,看起来像这样:
/// Updates the signed in state
  refreshSignedInStatus() {
    msal.getSignedIn().then((loggedIn) {
      print('refreshing');
      setState(() {
        isSignedIn = loggedIn;

        if(isSignedIn) {

          dynamic currentAccount = await handleGetAccount();

          Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                  builder: (context) => NavScreen(
                    currentAccount: currentAccount, // <--- Passing required named parameter "currentAccount" in NavScreen widget. 
                  ),
              ),
          );
        }
      });
    });
  }
NavScreen小部件也将通过创建构造函数来更新,如下所示:
NavScreen({
  @required this.currentAccount, // Required currentUser parameter 
});

final dynamic currentAccount; // Replace dynamic with the type of currentUser
来自 NavScreen ,我猜你一定是在导航到 HomeScreenDesktop不知何故,但是在执行此操作时,您需要通过 currentAccount反对HomeScreenDesktop & 创建与 NavScreen 中相同的构造函数和参数小部件(像这样):
HomeScreenDesktop({
  @required this.currentAccount, // Required currentUser parameter 
});

final dynamic currentAccount; // Replace dynamic with the type of currentUser
您还必须通过 currentAccount导航时的对象。
它看起来像这样:
Navigator.of(context).pushReplacement(
  MaterialPageRoute(
    builder: (context) => HomeScreenDesktop(
      currentAccount: currentAccount,
    ),
  ),
);

关于 flutter Azure AD 身份验证 : How to display the user email and name retrieved during login to another screen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64766470/

相关文章:

dart - Flutter:在小部件测试中测试异常

Dart、try.dart 使用 Mixins 时出错

flutter - 限制Map中MapEntries的数量: Dart

dart - Flutter 在真机上运行报错

android - 单击Flutter ListView导航到另一个屏幕

android - 实现下拉菜单项切换复选框

mobile - 如何发出经过身份验证的 http 请求并返回带有 dart 的对象流?

flutter - 如何在flutter上使用dio包获取原始请求

flutter - 返回主页时如何设置首选方向

Dart:为什么常量变量不能是实例变量?