【问题标题】:The property 'length' can't be unconditionally accessed because the receiver can be 'null'属性\'length\'不能被无条件访问,因为receiver可以是\'null\'
【发布时间】:2022-08-20 20:03:39
【问题描述】:

product_list_screen.dart

import \'package:flutter/material.dart\';

import \'../blocs/cart_bloc.dart\';
import \'../models/cart.dart\';

class ProductListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(\"eCommerce\"),
        actions: [
          IconButton(
            icon: Icon(Icons.shopping_cart),
            onPressed: () => Navigator.pushNamed(context, \"/cart\"),
          )
        ],
      ),
      body: buildProductList(),
    );
  }

  buildProductList() {
    return StreamBuilder(
      initialData: productBloc.getAll(),
      stream: productBloc.getStream,
      builder: (context, snapshot) {
        return snapshot.data.length > 0 //error
            ? buildProductListItems(snapshot)
            : Center(
                child: Text(\"No data\"),
              );
      },
    );
  }

  buildProductListItems(AsyncSnapshot<Object?> snapshot) {
    return ListView.builder(
        itemCount: snapshot.data.length, //error
        itemBuilder: (BuildContext context, index) {
          var list = snapshot.data;
          return ListTile(
            title: Text(list[index].name), //error
            subtitle: Text(list[index].price.toString()), //error
            trailing: IconButton(
              icon: Icon(Icons.add_shopping_cart),
              onPressed: () {
                cartBloc.addToCart(Cart(List[index], 1)); //error
              },
            ),
          );
        });
  }
}

属性 \'length\' 不能被无条件访问,因为接收者可以是 \'null\'。 (文档)尝试使访问有条件(使用 \'?.\')或向目标添加空检查(\'!\')。

我使用了 \'!\' 或 \'?\' 但它没有用。你能帮助我吗?谢谢。

  • 这有什么好运气吗?

标签: flutter dart


【解决方案1】:

您可以尝试使用 null 感知运算符:

snapshot.data?.length ?? 0

【讨论】:

  • 它不起作用
【解决方案2】:

不使用流生成器利用未来建造者例子:

FutureBuilder<Object?>(
    future: _fetchNetworkCall, // async work
    builder: (BuildContext context, AsyncSnapshot<Object?>snapshot) {
       switch (snapshot.connectionState) {
         case ConnectionState.waiting: return Text('Loading....');
         default:
           if (snapshot.hasError)
              return Text('Error: ${snapshot.error}');
           else
          return Text('Result: ${snapshot.data}');
        }
      },
    )

【讨论】:

  • 它不起作用。
【解决方案3】:

尝试按 ctrl。在 Windows 或命令 o 上。在 Mac 上从您的代码中获取建议 这将在 90% 的时间内有效

【讨论】:

    猜你喜欢
    • 2022-08-15
    • 1970-01-01
    • 2022-08-15
    • 2022-08-15
    • 2022-08-15
    • 2021-08-05
    • 2021-08-12
    • 2021-06-14
    • 2021-12-01
    相关资源
    最近更新 更多