rameez khan
rameez khan

Reputation: 359

Flutter setState list isnt updating Listviewbuilder

I have a simple list and I am filter the list by date range picker. All is working fine its showing result also that list is filter success but on ListView builer its showing this error.

Class 'WhereIterable<Object>' has no instance method '[]'.

My code

  Future<List> getCustomerList() async {
    print(widget.data);
    // print('check running');
    final storage = new FlutterSecureStorage();

    String uUid = await storage.read(key: "uUid");

    CollectionReference _collectionRef =
        FirebaseFirestore.instance.collection('Transaction');
    QuerySnapshot querySnapshot = await _collectionRef.get();

    // Get data from docs and convert map to List
    List allData = querySnapshot.docs
        .where((element) => element['CustomerID'] == widget.data['customerID'])
        .map((doc) => doc.data())
        .toList();
    print(allData);

    restore = allData;
    backrestore = allData;
    setState(() {
      show = true;
    });
  }




    Padding(
        padding: const EdgeInsets.all(8.0),
        child: GestureDetector(
            onTap: () async {
              final List<DateTime> picked =
                  await DateRangePicker.showDatePicker(
                      context: context,
                      initialFirstDate: new DateTime.now(),
                      initialLastDate: (new DateTime.now())
                          .add(new Duration(days: 6)),
                      firstDate: new DateTime(2015),
                      lastDate:
                          new DateTime(DateTime.now().year + 2));
              if (picked != null && picked.length == 2) {
                print(picked);
                selectedDate = picked[0];
                DateTime endDate = picked[1];
                List<DateTime> days = [];
                var filterData = backrestore;
                DateTime date = DateTime.parse(
                    filterData[0]['lastupdate'].toDate().toString());
                print(date);

                for (int i = 0;
                    i <= endDate.difference(selectedDate).inDays;
                    i++) {
                  days.add(selectedDate.add(Duration(days: i)));
                }
                print(days);

                final filteredItemsToAdd = filterData.where((item) =>
                    days.contains(DateTime.parse(
                        item['lastupdate'].toDate().toString())));
                print(filteredItemsToAdd.length);
                print(filteredItemsToAdd);
                setState(() {
                  restore = filteredItemsToAdd;
                });
              }
            },
            child: Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),

                    color: Color(0xffE5E7E9)
                ),child: Padding(
                  padding: const EdgeInsets.all(13.0),
                  child: Text('Date'),
                ))),
      ),


Container(
  height: Height * 0.5,
  child: ListView.builder(
    shrinkWrap: true,
    itemCount: restore.length,
    itemBuilder: (BuildContext context, int index) {
      DateTime date = DateTime.parse(
          restore[index]['lastupdate'].toDate().toString());

      // print(DateFormat('dd-MMM-yyy').format(date)); // prints 2019-04-16
      // print('List length ${snapshot.data.length}');
      return Padding(
        padding: const EdgeInsets.only(left: 13, right: 13),
        child: Container(
          decoration: BoxDecoration(
            border: Border(
                top: BorderSide(color: Colors.grey, width: .5)),
          ),
          child: Padding(
            padding: const EdgeInsets.all(13.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  DateFormat('dd MMM yyy').format(date).toString(),
                  style: TextStyle(fontFamily: 'PoppinsMedium'),
                ),
    

Row(
                  children: [
                    Text(
                      restore[index]['give'].toString(),
                      style: TextStyle(
                          fontFamily: 'PoppinsMedium',
                          color: Colors.green),
                    ),
                    SizedBox(
                      width: 60,
                    ),
                    Text(
                      restore[index]['take'].toString(),
                      style: TextStyle(
                          fontFamily: 'PoppinsMedium',
                          color: Colors.red),
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      );
    },
  ),
),

You can see I am fetching list then saving on object. And on DateRange picker I am changing the new value by setState but dont know why its showing this error.

Upvotes: 0

Views: 57

Answers (1)

Phuoc
Phuoc

Reputation: 1116

I believe this code causes the problem

List allData = querySnapshot.docs
        .where((element) => element['CustomerID'] == widget.data['customerID'])
        .map((doc) => doc.data())
        .toList();

element has type QueryDocumentSnapshot. Replace element['CustomerID'] by element.data()['customID'].

Upvotes: 1

Related Questions