首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >主体可能正常完成的错误,导致返回'null‘,但是返回类型'Widget’是一个潜在的不可空类型。

主体可能正常完成的错误,导致返回'null‘,但是返回类型'Widget’是一个潜在的不可空类型。
EN

Stack Overflow用户
提问于 2022-04-19 13:33:11
回答 1查看 131关注 0票数 0
代码语言:javascript
运行
复制
 Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: widget.auth.authStateChanges(),
      builder: (context, snapshot) { 
      // showing Error in this part(The body might complete normally, causing 
      // 'null' to be returned, but the return type, 'Widget', 
      // is a potentially non-nullable type. Also showing
      // type '_AsBroadcastStream<User?>' is not a subtype of type 'Stream<User>?')

          if (snapshot.connectionState == ConnectionState.active) {
              User? user = snapshot.Data;
              if (_user == null) {
                return LoginScreen(
                  onSignIn: _updateUser,
                  auth: widget.auth,
                );
              }
              return Home(
                onSignOut: () => _updateUser(null!),
                auth: widget.auth,
              );
            }
          },
        );
      }

在本部分中显示错误:

主体可能正常完成,导致返回'null‘,但是返回类型'Widget’是一个潜在的不可空类型.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-19 13:54:38

问题是在所有情况下,构建器都需要返回一个小部件。当if (snapshot.connectionState == ConnectionState.active)不是真的时,它就不会这么做。例如,你可以这样做

代码语言:javascript
运行
复制
Widget build(BuildContext context) {
  return StreamBuilder<User>(
    stream: widget.auth.authStateChanges(),
    builder: (context, snapshot) {
      // showing Error in this part(The body might complete normally, causing
      // 'null' to be returned, but the return type, 'Widget',
      // is a potentially non-nullable type. Also showing
      // type '_AsBroadcastStream<User?>' is not a subtype of type 'Stream<User>?')

      if (snapshot.connectionState == ConnectionState.active) {
        User? user = snapshot.Data;
        if (_user == null) {
          return LoginScreen(
            onSignIn: _updateUser,
            auth: widget.auth,
          );
        }
        return Home(
          onSignOut: () => _updateUser(null!),
          auth: widget.auth,
        );
      }
      return SizedBox(); //you need to return some widget here. this is an example
    },
  );
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71925864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档