无安全辅助的Flutter运行时间错误

b91juud3  于 2023-03-03  发布在  Flutter
关注(0)|答案(3)|浏览(114)

我一直在跟随一个早期版本的flutter教程,现在有了null safety,错误一直困扰着我,虽然它帮助我学习了更多关于null safety的知识,但我被卡住了。我需要帮助。
下面是来自类模型的代码

class Category {
  late final int categoryId;
  late final String categoryName;
  late final String categoryDesc;
  late final int parent;
  late Image image;

  Category(
      {required this.categoryId,
      required this.categoryName,
      required this.categoryDesc,
      required this.image});

  Category.fromJson(Map<String, dynamic> json) {
    categoryId = json['id'];
    categoryName = json['name'];
    categoryDesc = json['description'];
    parent = json['parent'];
    image = (json['image'] != null ? Image.fromJson(json['image']) : null)!;
  }
}

class Image {
  late String url;

  Image({
    required this.url,
  });

  Image.fromJson(Map<String, dynamic> json) {
    url = json['src'];
  }
}

以及我的分类代码

import 'package:flutter/material.dart';
import 'package:kemd/api_service.dart';
import 'package:kemd/models/category.dart' as category;
import 'package:kemd/models/category.dart' as categoryModel;

class WidgetCategories extends StatefulWidget {
  const WidgetCategories({super.key});

  @override
  State<WidgetCategories> createState() => _WidgetCategoriesState();
}

class _WidgetCategoriesState extends State<WidgetCategories> {
  late APIService apiService;

  @override
  void initState() {
    apiService = APIService();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: const [
              Padding(
                padding: EdgeInsets.only(left: 16, top: 10),
                child: Text(
                  'All Products',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 16, top: 10, right: 10),
                child: Text(
                  'View All',
                  style: TextStyle(fontSize: 18, color: Color.fromRGBO(249, 168, 37, 1)),
                ),
              ),
            ],
          ),
          _categoriesList()
        ],
      ),
    );
  }

  Widget _categoriesList() {
    return FutureBuilder(
      future: apiService.getCategories(),
      builder: (
        BuildContext context,
        AsyncSnapshot<List<categoryModel.Category>> model,
      ) {
        if (model.hasData) {
          return _buildCategoryList(model.data!);
        }
        return const Center(
          child: CircularProgressIndicator(
            color: Color.fromRGBO(249, 168, 37, 1),
          ),
        );
      },
    );
  }

  Widget _buildCategoryList(List<category.Category> catgories) {
    return Container(
      height: 50,
      alignment: Alignment.center,
      child: ListView.builder(
        shrinkWrap: true,
        physics: const ClampingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        itemCount: catgories.length,
        itemBuilder: (context, index) {
          var data = catgories[index];
          return Column(
            children: [
              Container(
                margin: const EdgeInsets.all(10),
                width: 80,
                height: 80,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(color: Colors.black12, blurRadius: 15, offset: Offset(0, 5)),
                  ],
                ),
                child: Image.network(
                  data.image.url as String,
                  height: 80,
                ),
              ),
              Row(
                children: [
                  Text(data.categoryName.toString()),
                  const Icon(
                    Icons.keyboard_arrow_right,
                    size: 14,
                  ),
                ],
              )
            ],
          );
        },
      ),
    );
  }
}

一切正常,但运行时出错

Exception has occurred.
_CastError (Null check operator used on a null value)

任何帮助都将不胜感激。
尝试向行添加null safety,但未解决

ha5z0ras

ha5z0ras1#

错误来自

image = (json['image'] != null ? Image.fromJson(json['image']) : null)!;

因为image不可为空,并在) : null)!;上强制[null-assertion]。
您可以使dataType可为空,如下所示

Image? image

然后分配

image = json['image'] != null ? Image.fromJson(json['image']) : null;

或者如果您想提供默认值

image = json['image'] != null ? Image.fromJson(json['image']) : Image.fromJson("defaultImage") ;

关于understanding-null-safety的更多信息

qhhrdooz

qhhrdooz2#

要解决此问题,您需要使Image模型类为空,如下所示,另一种解决方法是为该URL分配一个默认图像
(一)

class Category {
  late final int categoryId;
  late final String categoryName;
  late final String categoryDesc;
  late final int parent;
  Image? image;

  Category(
      {required this.categoryId,
      required this.categoryName,
      required this.categoryDesc,
      this.image});

  Category.fromJson(Map<String, dynamic> json) {
    categoryId = json['id'];
    categoryName = json['name'];
    categoryDesc = json['description'];
    parent = json['parent'];
    image = json['image'] != null ? Image.fromJson(json['image']) : null;
  }
}

1.类类别{最后一个int categoryId;最后一个字符串categoryName;最后一个字符串categoryDesc;后期最终int父代;后期图像;

Category(
    {required this.categoryId,
    required this.categoryName,
    required this.categoryDesc,
    this.image});

Category.fromJson(Map<String, dynamic> json) {
  categoryId = json['id'];
  categoryName = json['name'];
  categoryDesc = json['description'];
  parent = json['parent'];
  image = json['image'] != null ? Image.fromJson(json['image']) : Image.fromJson("YOUR_URL");
}

}

siotufzp

siotufzp3#

所以经过几次试验

image = json['image'] != null ? Image.fromJson(json['image']) : null;

image = json['image'] != null
    ? Image.fromJson(json['image'])
    : Image(url: '');

给出默认图像链接

data.image.url as String,

data.image!.url,

非常感谢你的帮助。

相关问题