Variable is not being decremented as the line excluded through Dismissible

Asked

Viewed 39 times

-1

I have a ListView.builder returning a ListTile, adding the time at title and value "10" in trailing every time the "ADD +10" button is triggered.

I used the widget Dismissible to delete items, but I can’t decrease the variable novoValor when a line is excluded through Dismissible, since the variable novoValor has a value and should be decreased by 10 each time a line is excluded.

I have tried several actions with the brief knowledge I have in programming, but I could not get any solution. I also did a lot of research, but I was not successful. I have spent a few days trying to understand what happens.

Just for clarification, I have tried some alternatives, one of them was to store the value of the deleted line in a variable and so use to decrease, I could not even recover the value of this excluded line. I used a List with a Map inside, so I couldn’t even get the "value" of the deleted line Map. Learning phase rs.

As the key and the value are as String, I had science that I would need to convert to int, but without success.

Man onDismissed: is no lines of code with any logic to solve the problem, but it is because I deleted what was not working.

My code:

import 'package:flutter/material.dart';

void main (){
  runApp ( MaterialApp(
      home: Home()
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {

  TimeOfDay horario;
  int valor = 10;
  int novoValor = 0;

  List lista = [];

  void addItens (){

    horario = TimeOfDay.now();

    Map <String, String> item = Map();
    item ['horario'] = '${horario.format(context)}';
    item ['valor'] = '$valor';
    lista.add (item);

    setState(() {
      novoValor += valor;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(padding: EdgeInsets.all(30),
              child: GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    width: 150,
                    height: 50,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        gradient: LinearGradient(colors: [Color(0xff388df8), Color(0xff28c9fc)])
                    ),
                    child: Text('ADD +10',
                      style: TextStyle(
                          color: Colors. white,
                          fontSize: 22,
                          fontWeight: FontWeight.bold
                      ),
                    ),
                  ),
                  onTap:addItens
              ),
            ),
            //Text colocado para testar se está incrementando e decrementando
            Text('Valor Atual: $novoValor'),
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: ListView.builder(
                  itemCount: lista.length,
                  itemBuilder: (context, indice) {
                    return Dismissible(
                      direction: DismissDirection.endToStart,
                      key: UniqueKey(),
                      onDismissed: (direction){
                        lista.removeAt(indice);
                        setState(() {
                          novoValor -= lista.removeAt(indice);
                        });
                      },
                      child: ListTile(
                        title: Text(lista[indice]['horario'],
                          style: TextStyle(
                              fontSize: 17,
                              fontWeight: FontWeight.bold
                          ),
                        ),
                        trailing: Text(lista[indice]['valor'],
                          style: TextStyle(
                              fontSize: 17
                          ),
                        ),
                      ),
                    );
                  }
              ),
            ),
          ],
        ),
      ),
    );
  }
}

1 answer

1


Your problem is related to your logic, come on...

Here you are removing the item from the list, then you remove the item again with the removeAt which in turn returns the deleted item which is a Map and not an integer... Doing so, you would be removing 2 items in a row.

onDismissed: (direction){
  lista.removeAt(indice);
  setState(() {
    novoValor -= lista.removeAt(indice);
  });
},

All you have to do is replace this block of code above with the following:

onDismissed: (direction){
  setState(() {
    novoValor -= int.parse(lista.removeAt(indice)["valor"]);
  });
},

Complete code:

import 'package:flutter/material.dart';

void main (){
  runApp ( MaterialApp(
      home: Home()
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {

  TimeOfDay horario;
  int valor = 10;
  int novoValor = 0;

  List lista = [];

  void addItens (){

    horario = TimeOfDay.now();

    Map <String, String> item = Map();
    item ['horario'] = '${horario.format(context)}';
    item ['valor'] = '$valor';
    lista.add (item);

    setState(() {
      novoValor += valor;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(padding: EdgeInsets.all(30),
              child: GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    width: 150,
                    height: 50,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        gradient: LinearGradient(colors: [Color(0xff388df8), Color(0xff28c9fc)])
                    ),
                    child: Text('ADD +10',
                      style: TextStyle(
                          color: Colors. white,
                          fontSize: 22,
                          fontWeight: FontWeight.bold
                      ),
                    ),
                  ),
                  onTap:addItens
              ),
            ),
            //Text colocado para testar se está incrementando e decrementando
            Text('Valor Atual: $novoValor'),
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: ListView.builder(
                  itemCount: lista.length,
                  itemBuilder: (context, indice) {
                    return Dismissible(
                      direction: DismissDirection.endToStart,
                      key: UniqueKey(),
                      onDismissed: (direction){
                        setState(() {
                          novoValor -= int.parse(lista.removeAt(indice)["valor"]);
                        });
                      },
                      child: ListTile(
                        title: Text(lista[indice]['horario'],
                          style: TextStyle(
                              fontSize: 17,
                              fontWeight: FontWeight.bold
                          ),
                        ),
                        trailing: Text(lista[indice]['valor'],
                          style: TextStyle(
                              fontSize: 17
                          ),
                        ),
                      ),
                    );
                  }
              ),
            ),
          ],
        ),
      ),
    );
  }
}
  • Thanks for the help. My problem was that I didn’t know how to extract the power that programming can give me. I even have the reasoning and managed to do many things myself, but sometimes I end up thinking that things should be done as a cake recipe. I used removeAt as I learned and simply did not imagine that there was this possibility that you did. Dismissible were the last attempt I had made, before were made other rs. Thanks again and I will look for some material to improve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.