Flutter null 安全:无法无条件调用方法“[]”,因为接收者可以为“null”

时间:2021-07-05 10:57:34

标签: flutter riverpod null-check

我正在尝试从具有索引值的 GridView 构建器传递数据,但出现以下错误:

The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!').

在这一行:

itemBuilder: (BuildContext ctxt, int index) {
   return ProductCard(
     product: productsProvider.data[index],
   );
}),

但是,如果我放置空检查运算符(!),它会显示另一个错误:

itemBuilder: (BuildContext ctxt, int index) {
   return ProductCard(
      product: productsProvider.data![index],
   );
}),


The operator '[]' isn't defined for the type 'AsyncData<ProductCategoryDetailsModel>'.
Try defining the operator '[]'.

我曾尝试将空安全运算符(? 和 !)放置在每个可能的位置,但找不到任何方法。请帮忙!

@override
Widget build(BuildContext context, ScopedReader watch) {
  AsyncValue<ProductCategoryDetailsModel>? productsProvider =
    watch(productCategoryDetailsProvider);

return Scaffold(
 
  body: Center(
    child: SingleChildScrollView(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          productsProvider!.when(
              data: (data) {
                return SingleChildScrollView(
                  child: Column(
                    children: [
                    
                      Container(
                        margin: EdgeInsets.all(20),
                        child: GridView.builder(
                            itemCount: data.data!.data!.length,
                            physics: BouncingScrollPhysics(),
                            gridDelegate:
                                SliverGridDelegateWithMaxCrossAxisExtent(
                                    maxCrossAxisExtent: 180,
                                    childAspectRatio: 3 / 4,
                                    crossAxisSpacing: 10,
                                    mainAxisSpacing: 10),
                            shrinkWrap: true,
                            itemBuilder: (BuildContext ctxt, int index) {
                              return ProductCard(
                                product: productsProvider.data[index],
                              );
                            }),
                      ),
                    ],
                  ),
                );
              },
              loading: () => Center(
                    child: CircularProgressIndicator(),
                  ),
              error: (error, stack) => Text(error.toString())),
          ],
        ),
      ),
    ),
  );
 }
}

2 个答案:

答案 0 :(得分:0)

尝试使用运算符 List?['property'] 访问地图

itemBuilder: (BuildContext ctxt, int index) {
   return ProductCard(
      product: productsProvider.data?[index],
        //edit in the above line data![index] to data?[index]
   );
}),

答案 1 :(得分:0)

哦!我传递了错误的信息。正确的代码是:

 itemBuilder: (BuildContext ctxt, int index) {
     return ProductCard(
       product: data.data!.data![index],
     );
 }),