Home > Enterprise >  I tried to make reusable widget but "The method '[]' was called on null. Receiver: nu
I tried to make reusable widget but "The method '[]' was called on null. Receiver: nu

Time:12-10

H3ll0, everyone. I'm new to this. I use Flutter on Android Studio. I wanna ask a question about reusable widget and its correlation to the API

I tried to make this and I tried to called it under a Container with width of MediaQuery size width

class VarianPenjualan extends StatefulWidget {
  final productDetail;

  const VarianPenjualan({Key? key, this.productDetail}) : super(key: key);

  @override
  _VarianPenjualanState createState() => _VarianPenjualanState();
}

class _VarianPenjualanState extends State<VarianPenjualan> {
  List arrList = [];
  var listData = [];
  bool isChecked = false;
  int _counter = 0;

  void initState() {
    super.initState();
    getProductDetailData(widget.productDetail['id']);
    getProduct();
  }

  getProductDetailData(id) async {
    var respon = await ApiService().getProductDetail({"id": id});

    if (respon['status'] == 200) {
      if (!this.mounted) return;
      setState(() {
        listData.addAll([respon['data']]);
      });
    }
  }

  getProduct() async {
    var respon = await ApiService().getProduct({"limit": 6, "page": 1});

    if (respon['status'] == 200) {
      if (!this.mounted) return;
      setState(() {
        arrList.addAll(respon['data']['productAsgrosList']);
      });
    }
  }

  _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  _decrementCounter() {
    setState(() {
      if (_counter > 0) {
        _counter--;
      }
    });
  }

  @override
  Widget build (BuildContext context) {
    return Row(
      mainAxisAlignment:
      MainAxisAlignment.center,
      crossAxisAlignment:
      CrossAxisAlignment.center,
      children: [
        Expanded(
          flex: 1,
          child: Checkbox(
            value: isChecked,
            onChanged: (bool? value) {
              setState(() {
                isChecked = value!;
              });
            },
          ),
        ), // CheckBox
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment:
            MainAxisAlignment.center,
            crossAxisAlignment:
            CrossAxisAlignment.stretch,
            children: [
              Text(
                "Kemasan",
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w400,
                    color: Color(0xff000000)),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    top: 5.0),
                child:
                Text("${(listData[0]['packaging'][0]['kemasan'])}"),
              )
            ],
          ),
        ), // Kemasan
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment:
            MainAxisAlignment.center,
            crossAxisAlignment:
            CrossAxisAlignment.stretch,
            children: [
              Text(
                "Harga",
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w400,
                    color: Color(0xff000000)),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    top: 5.0),
                child: Text("${GlobalFunctions().rupiah(listData[0]['packaging'][0]['price'])}"),
              )
            ],
          ),
        ), // Harga
        Expanded(
          flex: 1,
          child: Column(
            mainAxisAlignment:
            MainAxisAlignment.center,
            crossAxisAlignment:
            CrossAxisAlignment.stretch,
            children: [
              Text(
                "Stok",
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w400,
                    color: Color(0xff000000)),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    top: 5.0),
                child: Text("${(listData[0]['packaging'][0]['stock'])}"),
              )
            ],
          ),
        ), // Stok
        Expanded(
          flex: 3,
          child: Column(
            children: [
              Container(
                width: 120,
                height: 30,
                decoration: BoxDecoration(
                  color: Color(0xFF31708F),
                  borderRadius:
                  BorderRadius.circular(3),
                ),
                child: Row(
                  mainAxisAlignment:
                  MainAxisAlignment.center,
                  crossAxisAlignment:
                  CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      flex: 1,
                      child: InkWell(
                        onTap: () {
                          _decrementCounter();
                        },
                        child: Container(
                          alignment:
                          Alignment.center,
                          // padding: EdgeInsets.only(
                          //     right: 10),
                          child: Icon(
                            Icons.remove,
                            color: Color(
                                0xffFFFFFF),
                          ),
                        ),
                      ),
                    ), // Minus
                    Expanded(
                      flex: 1,
                      child: Text(
                        '$_counter',
                        textAlign:
                        TextAlign.center,
                        style: TextStyle(
                            color:
                            Colors.white),
                      ),
                    ),
                    // Quantity Number
                    Expanded(
                      flex: 1,
                      child: InkWell(
                        onTap: () {
                          _incrementCounter();
                        },
                        child: Container(
                          alignment:
                          Alignment.center,
                          // padding: EdgeInsets.only(
                          //     right: 10),
                          child: Icon(
                            Icons.add,
                            color: Color(
                                0xffFFFFFF),
                          ),
                        ),
                      ),
                    ), // Add
                  ],
                ),
              ), // Counter
              Container(
                margin: EdgeInsets.only(top: 7),
                padding: EdgeInsets.fromLTRB(
                    7, 4, 7, 4),
                width: 120,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    border: Border.all(
                        width: 0.5,
                        color:
                        Color(0xff31708F)),
                    borderRadius:
                    BorderRadius.all(
                        Radius.circular(
                            2))),
                child: Text("${GlobalFunctions().rupiah(listData[0]['packaging'][0]['price'] * _counter)}"),
              ), // Total Harga
            ],
          ),
        ), // Quantity Counter
        SizedBox(
          width: 10,
        ),
      ],
    ); // varian 1
  }
}

but " The method '[]' was called on null. Receiver: null. Tried calling: " appeared

I tried to understand the answers from the similiar question, but i can't understand it. Can you guys help me?

CodePudding user response:

You need to add loading widget since the listData fetch all response and then build the widget:

    class _VarianPenjualanState extends State<VarianPenjualan> {
      List arrList = [];
      var listData = [];
      bool isChecked = false;
      int _counter = 0;

      bool isLoaded = false;

      void initState() {
        super.initState();
        getProductDetailData(widget.productDetail['id']);
        getProduct();
      }

      getProductDetailData(id) async {
        var respon = await ApiService().getProductDetail({"id": id});

        if (respon['status'] == 200) {
          if (!this.mounted) return;
          setState(() {
            listData.addAll([respon['data']]);
            isLoaded = true;
          });
        }
      }

      getProduct() async {
        var respon = await ApiService().getProduct({"limit": 6, "page": 1});

        if (respon['status'] == 200) {
          if (!this.mounted) return;
          setState(() {
            arrList.addAll(respon['data']['productAsgrosList']);
          });
        }
      }

      _incrementCounter() {
        setState(() {
          _counter  ;
        });
      }

      _decrementCounter() {
        setState(() {
          if (_counter > 0) {
            _counter--;
          }
        });
      }

      @override
      Widget build(BuildContext context) {
        return isLoaded
            ? listData.length != 0
                ? Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: Checkbox(
                          value: isChecked,
                          onChanged: (bool? value) {
                            setState(() {
                              isChecked = value!;
                            });
                          },
                        ),
                      ), // CheckBox
                      Expanded(
                        flex: 2,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Text(
                              "Kemasan",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w400,
                                  color: Color(0xff000000)),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 5.0),
                              child: Text(
                                  "${(listData[0]['packaging'][0]['kemasan'])}"),
                            )
                          ],
                        ),
                      ), // Kemasan
                      Expanded(
                        flex: 2,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Text(
                              "Harga",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w400,
                                  color: Color(0xff000000)),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 5.0),
                              child: Text(
                                  "${GlobalFunctions().rupiah(listData[0]['packaging'][0]['price'])}"),
                            )
                          ],
                        ),
                      ), // Harga
                      Expanded(
                        flex: 1,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Text(
                              "Stok",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w400,
                                  color: Color(0xff000000)),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 5.0),
                              child:
                                  Text("${(listData[0]['packaging'][0]['stock'])}"),
                            )
                          ],
                        ),
                      ), // Stok
                      Expanded(
                        flex: 3,
                        child: Column(
                          children: [
                            Container(
                              width: 120,
                              height: 30,
                              decoration: BoxDecoration(
                                color: Color(0xFF31708F),
                                borderRadius: BorderRadius.circular(3),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: InkWell(
                                      onTap: () {
                                        _decrementCounter();
                                      },
                                      child: Container(
                                        alignment: Alignment.center,
                                        // padding: EdgeInsets.only(
                                        //     right: 10),
                                        child: Icon(
                                          Icons.remove,
                                          color: Color(0xffFFFFFF),
                                        ),
                                      ),
                                    ),
                                  ), // Minus
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                      '$_counter',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                  // Quantity Number
                                  Expanded(
                                    flex: 1,
                                    child: InkWell(
                                      onTap: () {
                                        _incrementCounter();
                                      },
                                      child: Container(
                                        alignment: Alignment.center,
                                        // padding: EdgeInsets.only(
                                        //     right: 10),
                                        child: Icon(
                                          Icons.add,
                                          color: Color(0xffFFFFFF),
                                        ),
                                      ),
                                    ),
                                  ), // Add
                                ],
                              ),
                            ), // Counter
                            Container(
                              margin: EdgeInsets.only(top: 7),
                              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
                              width: 120,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      width: 0.5, color: Color(0xff31708F)),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(2))),
                              child: Text(
                                  "${GlobalFunctions().rupiah(listData[0]['packaging'][0]['price'] * _counter)}"),
                            ), // Total Harga
                          ],
                        ),
                      ), // Quantity Counter
                      SizedBox(
                        width: 10,
                      ),
                    ],
                  )
                : Center(
                    child: Text('No Data'),
                  )
            : CircularProgressIndicator(); // varian 1
      }
    }
  • Related