0

My app launches successfully without warnings, but as soon as I try to save items via the add to cart controller I get the error with warnings as shown below. I'm not sure what to make of this error at this moment.

I understand that the use of (!) bang is referenced but still, I expect that not to be the problem since I have successfully fetched the instances I need to for executing functions in my controllers. I would appreciate any guidance and understanding if this issue has to do with my code or it's a flutter problem on my machine.

cart_controller with the error showing in line 17

import 'package:get/get.dart';
import 'package:izinto_on_demand/models/popular_specialty_model.dart';
import '../helpers/data/repository/cart_repo.dart';
import '../models/cart_model.dart';
import '../utils/colors.dart';

class CartController extends GetxController {
  final CartRepo cartRepo;
  CartController({required this.cartRepo});
  Map<int, CartModel> _items = {};

  Map<int, CartModel> get items => _items;

  void addItem(SpecialtyModel specialty, int quantity) {
    var totalQuantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.update(specialty.id!, (value) {
        // totalQuantity = value.quantity! + quantity;

        return CartModel(
            id: value.id,
            name: value.name,
            price: value.price,
            time: DateTime.now().toString(),
            img: value.img,
            material: value.material,
            quantity: value.quantity! + quantity,
            isExist: true,
            provider: value.provider);
      });

      if (totalQuantity <= 0) {
        _items.remove(specialty.id);
      }
    } else {
      if (quantity > 0) {
        _items.putIfAbsent(specialty.id!, () {
          return CartModel(
              id: specialty.id,
              name: specialty.name,
              price: specialty.price,
              time: DateTime.now().toString(),
              img: specialty.img,
              material: specialty.material,
              quantity: quantity,
              isExist: true,
              provider: specialty.provider);
        });
      } else {
        Get.snackbar('Item count', 'Please select items to add to cart',
            backgroundColor: AppColors.mainColor, colorText: Colors.white);
      }
    }
  }

  bool existInCart(SpecialtyModel, specialty) {
    if (_items.containsKey(specialty.id)) {
      return true;
    }
    return false;
  }

  int getQuantity(SpecialtyModel specialty) {
    var quantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.forEach((key, value) {
        if (key == specialty.id) {
          quantity = value.quantity!;
        }
      });
    }
    return quantity;
  }

  int get totalItems {
    var totalQuantity = 0;
    _items.forEach((key, value) {
      totalQuantity += value.quantity!;
    });
    return totalQuantity;
  }
}

recommended_specialty_controller with the error referenced again in line 81

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:izinto_on_demand/controllers/cart_controller.dart';
import 'package:izinto_on_demand/helpers/data/repository/recommended_specialty_repo.dart';
import 'package:izinto_on_demand/models/popular_specialty_model.dart';
import 'package:izinto_on_demand/utils/colors.dart';

class RecommendedSpecialtyController extends GetxController {
  final RecommendedSpecialtyRepo recommendedSpecialtyRepo;
  RecommendedSpecialtyController({required this.recommendedSpecialtyRepo});
  List<dynamic> _recommendedSpecialtyList = [];
  List<dynamic> get recommendedSpecialtyList => _recommendedSpecialtyList;
  late CartController _cart;

  bool _isLoaded = false;
  bool get isLoaded => _isLoaded;

  int _quantity = 0;
  int get quantity => _quantity;
  int _inCartItems = 0;
  int get inCartItems => _inCartItems + _quantity;

  Future<void> getRecommendedSpecialtyList() async {
    Response response =
        await recommendedSpecialtyRepo.getRecommendedSpecialtyList();
    if (response.statusCode == 200) {
      print('got specialties');

      _recommendedSpecialtyList = [];
      _recommendedSpecialtyList
          .addAll(Specialty.fromJson(response.body).specialties);
      print(_recommendedSpecialtyList);
      _isLoaded = true;
      update();
    } else {
      print('this is not working ${response.statusCode}');
    }
  }

  void setQuantity(bool isIncrement) {
    if (isIncrement) {
      _quantity = checkQuantity(_quantity + 1);
    } else {
      _quantity = checkQuantity(_quantity - 1);
      print('decrement ' + _quantity.toString());
    }
    update();
  }

  int checkQuantity(int quantity) {
    if ((_inCartItems + quantity) < 0) {
      Get.snackbar('Item count', 'You don\'t have items',
          backgroundColor: AppColors.mainColor, colorText: Colors.white);
      return 0;
    } else if ((_inCartItems + quantity) > 20) {
      Get.snackbar('Item count', 'Maximum number of items selected',
          backgroundColor: AppColors.mainColor, colorText: Colors.white);
      return 20;
    } else {
      return quantity;
    }
  }

  void initSpecialty(SpecialtyModel specialty, CartController cart) {
    _quantity = 0;
    _inCartItems = 0;
    _cart = cart;
    var exist = false;
    exist = _cart.existInCart(SpecialtyModel, specialty);
    //if exist
    //get from storage _inCartItems=3
    print('exist or not' + exist.toString());
    if (exist) {
      _inCartItems = _cart.getQuantity(specialty);
    }
    print('The quantity in the cart is' + _inCartItems.toString());
  }

  void addItem(SpecialtyModel specialty) {
    if (_quantity > 0) {
      _cart.addItem(specialty, _quantity);
      _quantity = 0;
      _cart.items.forEach((key, value) {
        print('The id is' +
            value.id.toString() +
            ' The quantity is ' +
            value.quantity.toString());
      });
    } else {
      Get.snackbar('Item count', 'You should at least add an item in the cart');
    }

    update();
  }

  int get totalItems {
    return _cart.totalItems;
  }
}

recommended_specialty_detail with the error referenced again in line 212

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:izinto_on_demand/controllers/cart_controller.dart';
import 'package:izinto_on_demand/controllers/popular_specialty_controller.dart';
import 'package:izinto_on_demand/controllers/recommended_specialty_controller.dart';
import 'package:izinto_on_demand/pages/home/main_specialty_page.dart';
import 'package:izinto_on_demand/utils/dimensions.dart';
import 'package:izinto_on_demand/widgets/App_column.dart';
import 'package:izinto_on_demand/widgets/app_icon.dart';
import 'package:izinto_on_demand/widgets/expandable_text.dart';
import '../../models/popular_specialty_model.dart';
import '../../utils/colors.dart';
import '../../widgets/big_text.dart';
import '../../widgets/icon_and_text_widgets.dart';
import '../../widgets/small_text.dart';

class RecommendedSpecialtyDetail extends StatelessWidget {
  int pageId;
  RecommendedSpecialtyDetail({Key? key, required this.pageId})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var specialty = Get.find<RecommendedSpecialtyController>()
        .recommendedSpecialtyList[pageId];
    Get.find<RecommendedSpecialtyController>()
        .initSpecialty(specialty, Get.find<CartController>());
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          //background image
          Positioned(
            left: 0,
            right: 0,
            child: Container(
              width: double.maxFinite,
              height: Dimensions.popularSpecialtyImgSize,
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: AssetImage(specialty.img),
                ),
              ),
            ),
          ),
          //icon widgets
          Positioned(
            top: Dimensions.height45,
            left: Dimensions.width20,
            right: Dimensions.width20,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                    onTap: () {
                      Get.to(() => MainSpecialtyPage());
                    },
                    child: AppIcon(icon: Icons.arrow_back_ios)),
                GetBuilder<RecommendedSpecialtyController>(
                  builder: (controller) {
                    return Stack(
                      children: [
                        AppIcon(icon: Icons.shopping_cart_outlined),
                        Get.find<RecommendedSpecialtyController>().totalItems >=
                                1
                            ? Positioned(
                                right: 0,
                                top: 0,
                                child: AppIcon(
                                  icon: Icons.circle,
                                  size: 20,
                                  iconColor: Colors.transparent,
                                  backgroundColor: AppColors.mainColor,
                                ),
                              )
                            : Container(),
                        Get.find<RecommendedSpecialtyController>().totalItems >=
                                1
                            ? Positioned(
                                right: 3,
                                top: 3,
                                child: BigText(
                                  text:
                                      Get.find<RecommendedSpecialtyController>()
                                          .totalItems
                                          .toString(),
                                  size: 12,
                                  color: Colors.white,
                                ),
                              )
                            : Container()
                      ],
                    );
                  },
                ),
              ],
            ),
          ),
          //introduction of specialty services
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            top: Dimensions.popularSpecialtyImgSize - 20,
            child: Container(
              padding: EdgeInsets.only(
                  left: Dimensions.width20,
                  right: Dimensions.width20,
                  top: Dimensions.height20),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(Dimensions.radius20),
                  topLeft: Radius.circular(Dimensions.radius20),
                ),
                color: Colors.white,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AppColumn(
                    text: specialty.name,
                  ),
                  SizedBox(
                    height: Dimensions.height20,
                  ),
                  BigText(text: 'Introduce'),
                  SizedBox(
                    height: Dimensions.height20,
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      child: ExpandableText(text: specialty.introduction),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: GetBuilder<RecommendedSpecialtyController>(
        builder: (recommendedSpecialty) {
          return Container(
            height: Dimensions.bottomHeightBar,
            padding: EdgeInsets.only(
                top: Dimensions.height20,
                bottom: Dimensions.height20,
                left: Dimensions.width20,
                right: Dimensions.width20),
            decoration: BoxDecoration(
              color: AppColors.buttonBackgroundColor,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(Dimensions.radius20 * 2),
                topRight: Radius.circular(Dimensions.radius20 * 2),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  padding: EdgeInsets.only(
                      top: Dimensions.height20,
                      bottom: Dimensions.height20,
                      left: Dimensions.width20,
                      right: Dimensions.width20),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimensions.radius20),
                    color: Colors.white,
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          recommendedSpecialty.setQuantity(false);
                        },
                        child: Icon(
                          Icons.remove_outlined,
                          color: AppColors.signColor,
                        ),
                      ),
                      SizedBox(
                        width: Dimensions.width15,
                      ),
                      BigText(
                        text: recommendedSpecialty.inCartItems.toString(),
                      ),
                      SizedBox(
                        width: Dimensions.width15,
                      ),
                      GestureDetector(
                        onTap: () {
                          recommendedSpecialty.setQuantity(true);
                        },
                        child: Icon(
                          Icons.add_outlined,
                          color: AppColors.signColor,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(
                      top: Dimensions.height20,
                      bottom: Dimensions.height20,
                      left: Dimensions.width20,
                      right: Dimensions.width20),
                  child: GestureDetector(
                    onTap: () {
                      recommendedSpecialty.addItem(specialty);
                    },
                    child: BigText(
                      text: 'R${specialty.price}  ' + '|  Add to cart',
                      color: Colors.white,
                    ),
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimensions.radius20),
                    color: AppColors.mainColor,
                  ),
                )
              ],
            ),
          );
        },
      ),
    );
  }
}

What's in the stack trace

The following _CastError was thrown while handling a gesture: Null check operator used on a null value

When the exception was thrown, this was the stack: #0 CartController.addItem (package:izinto_on_demand/controllers/cart_controller.dart:17:40) #1 RecommendedSpecialtyController.addItem (package:izinto_on_demand/controllers/recommended_specialty_controller.dart:81:13) #2 RecommendedSpecialtyDetail.build.. (package:izinto_on_demand/pages/specialty/recommended_specialty_Detail.dart:212:44) #3 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24) #4 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11) #5 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)

json map { "Specialties" : [ { "id": 3, "price": "150.00", "createAt": "2022-02-28T13:31:28.497Z", "img": "assets/image/dry42.jpg", "quantity" : [] } ] }

*flutter version C:\Users\CLIENT\Desktop\izinto_on_demand>flutter upgrade Flutter is already up to date on channel stable Flutter 2.10.3 • channel stable • https://github.com/flutter/flutter.git Framework • revision 7e9793dee1 (3 weeks ago) • 2022-03-02 11:23:12 -0600 Engine • revision bd539267b4 Tools • Dart 2.16.1 • DevTools 2.9.2

dependency injection in main.dart

  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    Get.find<RecommendedSpecialtyController>().getRecommendedSpecialtyList();
    Get.find<PopularSpecialtyController>().getPopularSpecialtyList();

    Get.lazyPut(() => CartController(cartRepo: Get.find()));
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,

specialty model

  late List<SpecialtyModel> _specialties;
  List<SpecialtyModel> get specialties => _specialties;

  Specialty({required specialties}) {
    this._specialties = specialties;
  }

  Specialty.fromJson(Map<String, dynamic> json) {
    if (json['Specialties'] != null) {
      _specialties = <SpecialtyModel>[];
      json['Specialties'].forEach((v) {
        _specialties.add(SpecialtyModel.fromJson(v));
      });
    }
  }
}

class SpecialtyModel {
  int? id;
  String? name;
  String? introduction;
  String? price;
  String? createAt;
  String? img;
  List<double>? location;
  String? provider;
  String? material;

  SpecialtyModel(
      {this.id,
      this.name,
      this.introduction,
      this.price,
      this.createAt,
      this.img,
      this.location,
      this.material,
      this.provider});

  SpecialtyModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    introduction = json['introduction'];
    price = json['price'];
    createAt = json['createAt'];
    img = json['img'];
    material = json['material'];
    location = json['location'].cast<double>();
    provider = json['provider'];
  }
}
  • Does this answer your question? [Null check operator used on a null value](https://stackoverflow.com/questions/64278595/null-check-operator-used-on-a-null-value) – Ivo Mar 21 '22 at 12:25
  • pretty sure it's not "a flutter problem on your machine". it simply means that that you use `!` on a null value. By the looks of it `speciality.id`. If you are absolutely sure the response from the server is correct then I assume that parsing the response goes wrong, which would be in the `Specialty.fromJson(response.body)` part. You haven't shared your `Speciality` class so can't tell what goes wrong there – Ivo Mar 21 '22 at 12:38
  • This is an awesome response because that Speciality class is what's missing but do check it out below and we'll hear if there's an omission on my side or error. – Tiisetso Dinoko Mar 21 '22 at 12:44
  • hmm. looking into that that part looks okay. Except for when `location` is empty then the cast will throw an error. So a safer `location = json['location']?.cast();` could solve that but that doesn't seem to be the error here. Maybe to double check the response you could do a `print(json.toString());` inside `SpecialtyModel.fromJson`? – Ivo Mar 21 '22 at 13:01
  • When I do that, it fetches the json objects from API as expected, so I guess the Specialty class is not the problem? – Tiisetso Dinoko Mar 21 '22 at 14:03
  • I suppose not, unless you see that one of them has no `id`. Maybe you could do this to have a fallback `id` just in case: `id = json['id'] ?? 0;` and see if it still gives the error – Ivo Mar 21 '22 at 14:10
  • 1
    Okay, Ivo thanks you had in fact detected correctly here, the original Specialties model had `id` as `id = json[id]` instead of `id = json['id']` that's where I made a problem even though in this question it was written correctly in the IDE it was wrongly referenced. Thanks you've been an on-demand hero – Tiisetso Dinoko Mar 21 '22 at 14:16

0 Answers0