简体   繁体   中英

how to filter data in flutter with provider

how to get data from provider and filter it in my flutter application

this is my catagory widget when u press it, i want it to filter my data with catagoryId i wanna pass filtered data to item screen. how ever i keep getting errors. i have created a method that hold catagory Id and pass it to set getOnlineItem() method to only show subcagory that thier catagory i matches

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:onlineshoping1/Assets/colors.dart';
import 'package:onlineshoping1/screans/item.dart';
import 'package:provider/provider.dart';

import '../provider/provider.dart';

class CatagoriesCard extends StatefulWidget {
  final dynamic listt;
  const CatagoriesCard({this.listt});

  @override
  State<CatagoriesCard> createState() => _CatagoriesCardState();
}

class _CatagoriesCardState extends State<CatagoriesCard> {
  @override
  Widget build(BuildContext context) {
    dynamic catagory;

    initState() {
      OnlineShopingProvider provider =
          Provider.of<OnlineShopingProvider>(context, listen: false);

      setState(() {
        catagory = provider.datalist.where((element) {
          return element['catagory_id'] == widget.listt;
        }).toList();
      });
    }

    setCategory(catagoryId) {
      OnlineShopingProvider provider = Provider.of(context, listen: false);
      provider.setCategory(catagoryId);
    }

    return GestureDetector(
      onTap: () {
        print(widget.listt);
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Item(
                    list: widget.listt['catagory_id'],
                  )),
        );
      },
      child: Container(
          width: double.infinity,
          height: 110,
          margin: EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: const [
                BoxShadow(
                  color: Colors.grey,
                  blurRadius: 5,
                  offset: Offset(0, 5),
                )
              ]),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Container(
                  height: 110,
                  width: 110,
                  margin: EdgeInsets.only(right: 20),
                  decoration: BoxDecoration(
                    color: tdgrey,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Image.network('${widget.listt['catagory_img']}'),
                ),
                Text(
                  '${widget.listt['catagory_name']}',
                  style: TextStyle(fontSize: 15),
                ),
              ],
            ),
          )),
    );
  }
}

and this is my provider class

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:onlineshoping1/screans/item.dart';

class OnlineShopingProvider with ChangeNotifier {
  int _selectedCategory = 0;
  final dynamic _data = [
    {
      'catagory_id': '1',
      'catagory_name': 'shoe',
      'catagory_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
    },
    {
      'catagory_id': '2',
      'catagory_name': 'clothes',
      'catagory_img':
          'https://www.freevector.com/uploads/vector/preview/1761/FreeVector-Womens-Clothes-Silhouettes.jpg',
    },
  ];

  final dynamic _item = [
    {
      'item_name': 'addidass',
      'item_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
      'price': '4000',
      'catagory_id': '1',
      'item_description':
          " is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,"
    },
    {
      'item_name': 'nike',
      'item_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
      'price': '3000',
      'catagory_id': '1',
      'item_description':
          " is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,"
    },
    {
      'item_name': 'reebok',
      'item_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
      'price': '2000',
      'catagory_id': '1',
      'item_description':
          " is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,"
    },
    {
      'item_name': 'chanel',
      'item_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
      'price': '2000',
      'catagory_id': '2',
      'item_description':
          " is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,"
    },
    {
      'item_name': 'CUCCI',
      'item_img':
          'https://thumbs.dreamstime.com/b/gadgets-accessories-gadgets-accessories-isolated-white-background-133429004.jpg',
      'price': '2000',
      'catagory_id': '2',
      'item_description':
          " is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,"
    },
  ];

  List cart = [];
  get datalist => _data;
  get items => _item;

  getOnlineItem() {
    if (_selectedCategory == null) {
      return _item;
    } else {
      return _item.where((e) => e['category_id'] == _selectedCategory).toList();
    }
  }

  void setCategory(id) {
    _selectedCategory = id;
    notifyListeners();
  }
}

Firstly, please, fix grammar errors, because in _item map you have "catagory_id" , while in the getOnlineItem method you are using "category_id" . I would recommend you to use data classes instead of maps.

Try to not use dynamic , please, always specify data type, when you can do it.

In the getOnlineItem method you are checking equality of two different data types.

return _item.where((e) => e['category_id'] == _selectedCategory).toList();

you are comparing e['category_id'] which is a String with _selectedCategory which is an int . So you have to either change data type of _selectedCategory to String or use toString() method. So you have the following code:

  getOnlineItem() {
    if (_selectedCategory == null) {
      return _item;
    } else {
      return _item.where((e) => e['catagory_id'] == _selectedCategory.toString()).toList();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM