提问者:小点点

抛出以下_TypeError构建Builder(脏,依赖项:[MediaQuery]):type'Future<Null>'不是'Widget'类型的子类型


背景:

我正在使用azure广告构建一个简单的登录应用程序,该应用程序登录很好,并获得令牌并重定向到下一页很好,但在重定向之前,它会抛出一个错误

错误:

抛出以下_TypeError构建Builder(脏,依赖项:[MediaQuery]):type'Future'不是'Widget'类型的子类型

相关的导致错误的小部件是:Builder file:///D:/Projects/flutter/aims_mobile/lib/屏幕/身份验证/sign. dart:101:17当异常被抛出时,这是堆栈:#0_SignInState.build。(包:aims_mobile/屏幕/身份验证/signin.dart:133:25)#1Builder.build(包:flutter/src/widget/base.dart:7185:48)#2StatelessElement.build(包:flutter/src/widget/frame.dart:4749:28)#3 ComponentElement.performRebuild(包:flutter/src/widget/frame.dart:4675:15)#4元素重建(包:flutter/src/widget/frame.dart:4369:5)

代码

class _SignInState extends State<SignIn> {
  static const String SCOPE ='';
  static const String TENANT_ID = 'organizations';
  static String authority = "";

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

  /// 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) {
        print('current account id: ${result.currentAccount.id}');
        print('current account id: ${result.currentAccount.username}');
      } else {
        print('no account found');
      }
    }).catchError((exception) {
      if (exception is MsalMobileException) {
        logMsalMobileError(exception);
      } else {
        print('exception occurred');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: new 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>[
                            isSignedIn
                                ? Future.delayed(Duration.zero, () {
                                    Navigator.of(context).pushReplacement(
                                        MaterialPageRoute(
                                            builder: (context) => NavScreen()));
                                  })
                                : RaisedButton(
                                    child: Text("Sign In"),
                                    onPressed: handleSignIn,
                                  ),
                          ],
                        ),
                      )),
                )
              ],
            ),
          ],
        ),
      ),
    ));
  }
}

我不知道如何解决这个问题


共1个答案

匿名用户

您正在传递一个函数Future而不是导致此错误的Widget

isSignedIn
      ? Future.delayed(Duration.zero, () {  // <---- This is not a widget
            Navigator.of(context).pushReplacement(
                MaterialPageRoute(
            builder: (context) => NavScreen()));
        })
        : RaisedButton(
        child: Text("Sign In"),
        onPressed: handleSignIn,
    ),

您可以使用可见性小部件来隐藏/显示您的“登录”按钮,而不是这样做

Visibility(
  visible: !isSignedIn,
  child: RaisedButton(
    child: Text("Sign In"),
    onPressed: handleSignIn,
  ),
),

您应该在StatefulWidgetinitState方法中处理导航,该方法如下所示:

@override
void initState() {
  super.initState();
  signInNavigation();
}

Future<void> signInNavigation() async {
  // isSignedIn = await yourMethodWhichReturnsSignInStatus(); <-- Replace this with your method

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