Home > Mobile >  Flutter: RangeError (index): Invalid value: Range is empty
Flutter: RangeError (index): Invalid value: Range is empty

Time:12-29

My app is working fine, but anyway I got this error.

I'm using a future builder to read from database and display on screen the data, not the list but 1st item, and if i do some actions the counter which is 0 by default is increasing and getting me next data Item. (I think that I'm searching items by Index in the list that is empty and thats why I get the error but Im not sure).

The problem is that Ive seen on internet only fixes to LisView.Builder but Im not using one, and I have no idea why Im getting this error.

enter image description here

Next page after I enter Barcode in textField (this is first data from list)

enter image description here

List of items

enter image description here

// declaration of counting variable
var index = 0;

// function to read from db
 Future<List?> read(String query) async {
    var result = await SqlConn.readData(query);
    query.replaceAll("\"", "");
    List _list = jsonDecode(result) as List;
    debugPrint('${_list.length} <===== size');
    return _list;
  }

// part of code that display data
child: FutureBuilder<List?>(
                    future: read(
                        // "SELECT ProductSeriesDescr FROM ScanRest WHERE ProductStation = '${widget.nrStatie}' AND BoxID = '$cutieScan' and ProductSeriesDescr != '0331120' ANd ProductSeriesDescr != '020322'"),
                        "SELECT ProductAdress, replace(ProductName, '\"', '')ProductName, NeedCount, ScanCount, ProductBarCode, ProductSeriesCount, ProductExpirationDate FROM ScanRest WHERE ProductStation = '${widget.nrStatie}' AND BoxID = '$cutieScan' Order By ProductName ASC"),
                    builder: (context, snapshot) {
                      switch (snapshot.connectionState) {
                        case ConnectionState.waiting:
                          return const Text('Loading....');
                        default:
                          if (snapshot.hasError) {
                            debugPrint(
                                "call error"); //"call error = ${snapshot.error}"
                            return Text('Error: ${snapshot.error}');
                          } else {
                            debugPrint(
                                "call success"); // "call success = ${snapshot.data}"
                            List data = snapshot.data ?? [];
                            return Column(children: [
                              Row(
                                children: [
                                  // ----------------------------------- Product Adress
                                  Expanded(
                                      child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        i  ;
                                        if (i == snapshot.data!.length) {
                                          i = 0;
                                        }
                                      });
                                    },
                                    child: SizedBox(
                                        height: 60,
                                        child: Center(
                                          child: Text( 'i='  i.toString()   " "   ((data[i] as Map)['ProductAdress'].toString()),
                                            style: const TextStyle(fontSize: 30),
                                          ),
                                        )),
                                  )),

                                  // ------------------------------------ NEED COUNT
                                  Expanded(
                                      child: GestureDetector(
                                    onTap: () {
                                      _nrProdusController.text =
                                          (data[i] as Map)['NeedCount'].toString();
                                    },
                                    child: SizedBox(
                                      height: 60,
                                      child: Center(
                                        child: Text(
                                          ((data[i] as Map)['NeedCount']
                                              .toString()),
                                          style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold, color: Colors.primaries[Random().nextInt(Colors.primaries.length)]),
                                        ),
                                      ),
                                    ),
                                  )),
                                ],
                              ),

Data displayed in Read function

Data displayed when trying to display on screen

enter image description here

CodePudding user response:

You are using an empty list if the snapshot has no data. Indexing into the list causes the error.

Better to check snapShot.hasData and show some other widget when it returns false.

CodePudding user response:

List data = snapshot.data ?? [];

// Simple fix that worked for me:

if (snapshot.data!.isEmpty) {

return Text('Waiting for BarCode');

}

  • Related