简体   繁体   English

以下 _TypeError 被抛出 building Builder(dirty, dependencies: [MediaQuery]): type &#39;Future<Null> &#39; 不是 &#39;Widget&#39; 类型的子类型

[英]The following _TypeError was thrown building Builder(dirty, dependencies: [MediaQuery]): type 'Future<Null>' is not a subtype of type 'Widget'

Context:语境:

I am building a simple login app with azure ad, the app logins just fine and gets the token and redirects to the next page just fine, but before it redirects it throws an error我正在使用 azure ad 构建一个简单的登录应用程序,该应用程序登录正常并获取令牌并重定向到下一页就好了,但在重定向之前它会引发错误

Error:错误:

The following _TypeError was thrown building Builder(dirty, dependencies: [MediaQuery]): type 'Future' is not a subtype of type 'Widget'以下 _TypeError 被抛出 building Builder(dirty, dependencies: [MediaQuery]): type 'Future' is not a subtype of type 'Widget'

The relevant error-causing widget was: Builder file:///D:/Projects/flutter/aims_mobile/lib/screens/authentication/signin.dart:101:17 When the exception was thrown, this was the stack: #0 _SignInState.build.相关的导致错误的小部件是:Builder file:///D:/Projects/flutter/aims_mobile/lib/screens/authentication/signin.dart:101:17 抛出异常时,这是堆栈:#0 _SignInState 。建造。 (package:aims_mobile/screens/authentication/signin.dart:133:25) #1 Builder.build (package:flutter/src/widgets/basic.dart:7185:48) #2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4749:28) #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:15) #4 Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5) (package:aims_mobile/screens/authentication/signin.dart:133:25) #1 Builder.build (package:flutter/src/widgets/basic.dart:7185:48) #2 StatelessElement.build (package:flutter/src /widgets/framework.dart:4749:28) #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:15) #4 Element.rebuild (package:flutter/src/widgets/framework.dart :4369:5)

Code代码

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

I don't know how to resolve this issue我不知道如何解决这个问题

You are passing a function Future instead of Widget which is causing this error.您正在传递导致此错误的函数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,
    ),

Instead of doing this, you can use the Visibility widget to hide/show your "Sign In" button & using the bool isSignedIn , you can handle the navigation code.您可以使用Visibility小部件隐藏/显示“登录”按钮并使用bool isSignedIn来处理导航代码,而不是这样做。

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

You should handle the navigation inside the initState method of your StatefulWidget which would look something like this:您应该在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()));
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决“在构建Builder(dirty)时引发了以下断言:输入&#39;Future <dynamic> “不是&#39;ProduktList&#39;类型的子类型” - How to fix “The following assertion was thrown building Builder(dirty): type 'Future<dynamic>' is not a subtype of type 'ProduktList'” _TypeError 在构建 NotesListView(dirty) 时被抛出:“Null”类型不是“String”类型的子类型 - _TypeError was thrown building NotesListView(dirty) : type 'Null' is not a subtype of type 'String' 在构建 Home(dirty, state: _HomeState#f907f) 时抛出了以下 _TypeError: type 'Null' is not a subtype of type 'bool' - The following _TypeError was thrown building Home(dirty, state: _HomeState#f907f): type 'Null' is not a subtype of type 'bool' 以下 _TypeError 被抛出构建:类型'MappedListIterable<akcijedokument, widget> ' 不是 'Widget' 类型的子类型</akcijedokument,> - The following _TypeError was thrown building: type 'MappedListIterable<AkcijeDokument, Widget>' is not a subtype of type 'Widget' 抛出以下 _TypeError building TestClass(dirty, dependencies: - The following _TypeError was thrown building TestClass(dirty, dependencies: 输入&#39;未来<Null> &#39; 不是类型 &#39;Widget&#39; 问题的子类型 - type 'Future<Null>' is not a subtype of type 'Widget' Problem 在构建 ScopedModelDescendant 时引发了以下 _TypeError<productsmodel> (脏,依赖:[_InheritedModel<productsmodel> ]):</productsmodel></productsmodel> - The following _TypeError was thrown building ScopedModelDescendant<ProductsModel>(dirty, dependencies: [_InheritedModel<ProductsModel>]): _CastError 在构建 Builder 时被抛出:类型“Null”不是类型转换中“String”类型的子类型 - _CastError was thrown building Builder: type 'Null' is not a subtype of type 'String' in type cast _TypeError(类型“Null”不是“Widget”类型的子类型) - _TypeError (type 'Null' is not a subtype of type 'Widget') 发生异常。 ListView.builder 上的 _TypeError(类型“Null”不是“Widget”类型的子类型) - Exception has occurred. _TypeError (type 'Null' is not a subtype of type 'Widget') on ListView.builder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM