0

Flutter i am adding data by forEach loop in an array

Code.

class _BrowserCategoryPage2State extends State<BrowserCategoryPage2> {
  var items = {'Items': []};

  @override
  Widget build(BuildContext context) {
    print('browse subcategory');
    print(widget.subCategory);

        widget.subCategory.forEach((subcategory) {
          items['Items'].addAll(subcategory['Items']);
        });
      print(items);
      print('sada');


    return Scaffold(
      appBar: buildAppBar(),
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              buildCategoryHeading(context),
              GridView.builder(
                itemCount: widget.subCategory.length,
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                physics: ScrollPhysics(),
                padding: EdgeInsets.symmetric(horizontal: 18.0),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 15.0,
                  mainAxisSpacing: 15.0,
                  childAspectRatio: 4.0 / 7.0,
                ),
                itemBuilder: (context, index) {
                  var category = categoryList[index];
                  double duration = index / 2;
                  return FadeInAnimation(
                    duration.toInt(),
                    child: GestureDetector(
                        onTap: (){
                          print(widget.subCategory[index]['Items']);
                          setState(() {
                            var items = {'Items': []};
                            print(items);
                          });


                        },
                        child: Container(
                          width: 80.0,
                          child: Column(
                            children: <Widget>[
                              Container(
                                width: 60.0,
                                height: 60.0,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      color: Theme.of(context)
                                          .accentColor
                                          .withOpacity(.2)),
                                  image: DecorationImage(
                                    image: AssetImage(
                                        'assets/icons/shirt.png'),
                                  ),
                                ),
                              ),
                              SizedBox(height: 12.0),
                              Text(
                                widget.subCategory[index]['Name'],
                                textAlign: TextAlign.center,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2,
                              ).tr(),
                            ],
                          ),
                        )
                    ),
                  );
                },
              ),
              
            ],
          ),
        ),
      ),
    );
  }
}

Now you can see I am showing products that are coming in the Items array. Now what I need to do is onTap I need to clear all items. So after then ill insert another item so need to remove all arrays from Items.

Hope my question is understandable its simple mean I need to clear all arrays from Items when I click on GestureDetectore

1
  • is items.clear() is not what you want? Commented Jan 25, 2021 at 10:47

3 Answers 3

2

Although you clear list by tapping button, list will be added again when 'build' is called.

  @override
  Widget build(BuildContext context) {
    print('browse subcategory');
    print(widget.subCategory);

        widget.subCategory.forEach((subcategory) {
          items['Items'].addAll(subcategory['Items']);
        });

So you need to move initializing list code.

class _BrowserCategoryPage2State extends State<BrowserCategoryPage2> {
  var items = {'Items': []};

  @override
  void initState() {
    super.initState();

    print(widget.subCategory);

    widget.subCategory.forEach((subcategory) {
       items['Items'].addAll(subcategory['Items']);
    });     
    print(items);
    print('sada');
  }

  @override
  Widget build(BuildContext context) {
    print('browse subcategory');
    return Scaffold(
      appBar: buildAppBar(),
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              buildCategoryHeading(context),
              GridView.builder(
                itemCount: widget.subCategory.length,
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                physics: ScrollPhysics(),
                padding: EdgeInsets.symmetric(horizontal: 18.0),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 15.0,
                  mainAxisSpacing: 15.0,
                  childAspectRatio: 4.0 / 7.0,
                ),
                itemBuilder: (context, index) {
                  var category = categoryList[index];
                  double duration = index / 2;
                  return FadeInAnimation(
                    duration.toInt(),
                    child: GestureDetector(
                        onTap: (){
                          print(widget.subCategory[index]['Items']);
                          setState(() {
                            items = {'Items': []};
                            // Or 
                            // items['Items'].clear();
                            print(items);
                          });


                        },
                        child: Container(
                          width: 80.0,
                          child: Column(
                            children: <Widget>[
                              Container(
                                width: 60.0,
                                height: 60.0,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      color: Theme.of(context)
                                          .accentColor
                                          .withOpacity(.2)),
                                  image: DecorationImage(
                                    image: AssetImage(
                                        'assets/icons/shirt.png'),
                                  ),
                                ),
                              ),
                              SizedBox(height: 12.0),
                              Text(
                                widget.subCategory[index]['Name'],
                                textAlign: TextAlign.center,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: Theme.of(context)
                                    .textTheme
                                    .subtitle2,
                              ).tr(),
                            ],
                          ),
                        )
                    ),
                  );
                },
              ),
              
            ],
          ),
        ),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can just assign a new value, that is empty:

items['Items'] = [];

You can also call the clear method:

items['Items'].clear();

And if you want make the smallest possible change to your code that would work, remove the var, you don't want a new variable, you want to change the existing one:

setState(() {
   items = {'Items': []};
   print(items);
});

1 Comment

@rameezkhan Okay, so did you try it? Did it work?
-2

I have never used flutter but Id say just declare the array again.

var items = {'Items': []};

widget.subCategory.forEach((subcategory) {
  items['Items'].addAll(subcategory['Items']);
});

//declare array again to empty array

var items = {'Items': []};

7 Comments

Please don't take guesses. It looks mostly correct, but we aim to be more than the site where you get a mostly correct guess.
@nvoigt I am experienced enough to be able to provide the above answer without having to use flutter, it's a very basic programming concept.
Well, you made the same mistake the OP did, so I guess it's not that easy. The mistake is not specific to flutter btw.
What are you referring to ?
You cannot "declare" it again. You can remove the declaration part and it would work though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.