skip to Main Content

Have been following a tutorial made with earlier version of flutter, now with null safety, errors are bugging me though it has helped me with learning more about null safety, I am stuck. I need help.

here is the code from class model

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'];
  }
}

and the my category code

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,
                  ),
                ],
              )
            ],
          );
        },
      ),
    );
  }
}

everything is without error. But having runtime error

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

any help will be appreciated.

tried adding null safety to lines but unresolved

2

Answers


  1. Chosen as BEST ANSWER

    so after several trials changed

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

    to

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

    giving a default image link and

    data.image.url as String,
    

    to

    data.image!.url,
    

    Very much appreciated for the assistance.


  2. The error is coming from

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

    because image isnot nullable, and forcing [null-assertion] on ) : null)!;.

    You can make dataType nullable like

    Image? image
    

    And assign like

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

    Or if you like to provide default value

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

    More about understanding-null-safety

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search