flutter - 在构建Builder时引发了以下_TypeError(脏,相关性:[MediaQuery]): 'Future<Null>'类型不是 'Widget'类型的子类型

标签 flutter dart

内容:
我正在使用azure广告构建一个简单的登录应用程序,该应用程序可以正常登录并获取 token ,然后可以重定向到下一页,但是在重定向之前会引发错误
错误:

The following _TypeError was thrown 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. (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)


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,
                                  ),
                          ],
                        ),
                      )),
                )
              ],
            ),
          ],
        ),
      ),
    ));
  }
}
我不知道如何解决这个问题

最佳答案

您正在传递函数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小部件隐藏/显示“登录”按钮,并使用bool isSignedIn来处理导航代码。
Visibility(
  visible: !isSignedIn,
  child: RaisedButton(
    child: Text("Sign In"),
    onPressed: handleSignIn,
  ),
),
您应该在initStateStatefulWidget方法内部处理导航,如下所示:
@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()));
  }
}

关于flutter - 在构建Builder时引发了以下_TypeError(脏,相关性:[MediaQuery]): 'Future<Null>'类型不是 'Widget'类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64746332/

相关文章:

firebase - Google Cloud Firestore 'in' 运算符(operator)解决方法

Flutter:我可以在 ListView 构建器中启用/禁用 InkWell 吗?

image - Flutter Navigation 和同时对 dispose() 的要求

flutter - 如何解决此错误在 flutter 中找不到路由 RouteSettings ("Welcome", null) 的生成器

testing - 尝试测试 html 文件对象时,它不会让我用示例图像预填充它吗?

json - Dart- 'String'类型不是 'Iterable<dynamic>'类型的子类型

intellij-idea - Flutter - 在 IntelliJ 中使用 Atom 语法高亮

flutter - 为什么只在 `setState`的子类中使用 `framework.dart`?

flutter - 此 ValueListenableBuilder 小部件无法标记为需要构建

DART 寄存器元素