Home > Net >  How to remove any widget from a list and set its state in flutter
How to remove any widget from a list and set its state in flutter

Time:03-03

Here i am creating an app which contain a section through which a user can create a poll. So when i am pressing a add button options container get added but when i am trying to remove the option container by pressing the minus button it's not working. Can someone help me to fix this. This is my college project.

application preview

import 'package:flutter/material.dart';
import 'package:note_app_demo/scaffold.dart';

List<Container> options = [
  Container(
    padding: EdgeInsets.all(15),
    child: TextField(
      decoration: InputDecoration(
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
        hintText: 'Option 1',
      ),
    ),
  ),
];

class POLL extends StatefulWidget {
  const POLL({Key? key}) : super(key: key);

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

class _POLLState extends State<POLL> {
  int option_var = 1;
  @override
  Widget build(BuildContext context) {
    return SCAFFOLD(
      BODY: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(15),
              child: TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10)),
                  hintText: 'Write your question here',
                ),
              ),
            ),
            Column(
              children: options,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Container(
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        options.removeAt(option_var);
                      });
                      option_var--;
                    },
                    child: Icon(
                      Icons.remove_circle,
                      size: 60,
                    ),
                  ),
                ),
                Container(
                  child: GestureDetector(
                    onTap: () {
                      option_var  ;
                      if (option_var < 9) {
                        setState(() {
                          options.add(
                            Container(
                              padding: EdgeInsets.all(15),
                              child: TextField(
                                decoration: InputDecoration(
                                  border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(10)),
                                  hintText: 'Option $option_var',
                                ),
                              ),
                            ),
                          );
                        });
                      }
                    },
                    child: Icon(
                      Icons.add_circle,
                      size: 60,
                    ),
                  ),
                ),
              ],
            ),
            Container(
              child: GestureDetector(
                onTap: () {},
                child: Icon(
                  Icons.check_circle,
                  size: 60,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

Every time you trigger the widget rebuild upon calling setState the option_var gets reset to 1. At the top of the build method, when setting the value of the option_var, use instead:

int option_var = options.length;

which will reflect the accurate number of items in the collection, thus keeping your count in sync.

Then, in your removal code, just do:

onPressed: () {
  setState(() {
     option_var--;
     options.removeAt(option_var);
  });         
},

Where you keep the option_var updated, and you always remove from the end of the array.

It should look like this after the updates:

enter image description here

Good luck in your project!

CodePudding user response:

Yes, I checked the code, the addition works. When deleting an error occurs that the number is 1 more than necessary.

Changed instead of option_var made option_var-1 Therefore o

   onTap: () {
                       setState(() {
                         options.removeAt(option_var-1);
                       });
                       option_var--;
                     },

made it work.

CodePudding user response:

Ok, so there are many reasons why this might be happening, or rather there are many unconventional things going on with your code, so I am not sure if changing just one of them will fix the bug.

The first obvious thing you have to change is this:

onTap: () {
  setState(() {
    options.removeAt(option_var);
  });
  option_var--;
},

Imagine you have a single item on your list, options_var should be equal to 1. So you are saying:

remove the item in position number 1.

But remember, lists count from 0, so the item in position number one would be the second item on your list. You should use position 0.

A simple way to fix this is to move the -- operator to before your set state.

onTap: () {
  option_var--;
  setState(() {
    options.removeAt(option_var);
  });
},

I will also let you know that lists, like options, have a length variable that gets updated automatically and works exactly the same as your option_var does, so you could use it instead:

onTap: () {
  setState(() {
    options.removeAt(options.length-1);
  });
},

The other two things that you could change are as follows:

  1. I like to use setState with explicit assignments:
onTap: () {
  var _options = options.removeAt(options.length-1);
  setState(() {
    options = _options;
  });
},
  1. I would make options be a _POLLState variable, like option_var
  • Related