object appears in console but is not added to list

Asked

Viewed 18 times

0

When added in the list, the objects appear in the console. however the list is not updated and no obj sent appears.

    import 'package:flutter/material.dart';

void main() => runApp(Home());

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListaTransferencias(),
        // body: FormularioTransferencia(),
      ),
    );
  }
}

class FormularioTransferencia extends StatelessWidget {
  final TextEditingController _controllerNumeroConta = TextEditingController();
  final TextEditingController _controllerValor = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Criando uma transferência'),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Editor(
              controlador: _controllerNumeroConta,
              rotulo: 'Número da conta',
              dica: '0000',
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Editor(
              controlador: _controllerValor,
              rotulo: 'Valor',
              dica: '0.0',
              icone: Icons.monetization_on,
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(0.0, 32.0, 0.0, 0.0),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                  textStyle: const TextStyle(fontSize: 24),
                  padding: EdgeInsets.fromLTRB(
                      30.0, 20.0, 30.0, 20.0) // aumentar o tamanho do botão
                  ),
              onPressed: () => _criaTransferencia(context),
              child: Text('Salvar'),
            ),
          )
        ],
      ),
    );
  }

  void _criaTransferencia(BuildContext context) {
    final int? numeroConta = int.tryParse(_controllerNumeroConta.text);
    final double? valor = double.tryParse(_controllerValor.text);
    if (numeroConta != null && valor != null) {
      final transferenciaCriada = Transferencia(numeroConta, valor);
      Navigator.pop(context, transferenciaCriada);
    }
  }
}

class Editor extends StatelessWidget {
  final TextEditingController? controlador;
  final String? rotulo;
  final String? dica;
  final IconData? icone;

  Editor({this.controlador, this.rotulo, this.dica, this.icone});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: controlador,
        keyboardType: TextInputType.number,
        style: TextStyle(
          fontSize: 24.0,
        ),
        decoration: InputDecoration(
          prefixIcon: Icon(icone),
          hintText: dica,
          labelText: rotulo,
        ),
      ),
    );
  }
}

// tela que lista todas as transferencias
class ListaTransferencias extends StatefulWidget {
  final List<Transferencia> _list = [];

  @override
  State<StatefulWidget> createState() {
    return ListaTransferenciaState();
  }
}

class ListaTransferenciaState extends State<ListaTransferencias> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Transferências'),
      ),
      body: ListView.builder(
        itemCount: widget._list.length,
        itemBuilder: (context, index) {
          final transferencia = widget._list[index];

          return ItemTransferencia(transferencia);
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          final Future<Transferencia?> future = Navigator.push(
            context,
            MaterialPageRoute(builder: (context) {
              return FormularioTransferencia();
            }),
          );

          future.then((value) {
            if (value != null) {
              setState(() {
                () => widget._list.add(value);
              });
            }
          });
        },
      ),
    );
  }
}

class ItemTransferencia extends StatelessWidget {
  final Transferencia _transferencia;

  ItemTransferencia(this._transferencia);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        leading: Icon(Icons.attach_money),
        title: Text(_transferencia.valor.toString()),
        subtitle: Text(_transferencia.conta.toString()),
      ),
    );
  }
}

class Transferencia {
  final int conta;
  final double valor;

  Transferencia(this.conta, this.valor);

  @override
  String toString() {
    return 'Transferencia{conta: $conta, valor: $valor}';
  }
}

1 answer

0


Come on, there are 2 points that are causing your problem...

first If your list will be mutable, ie, will have its status changed, the variable _list must be declared within the state and not in the widget itself, it follows the correct form:

class ListaTransferenciaState extends State<ListaTransferencias> {
  final List<Transferencia> _list = [];

  [...]
}

Obs.: That way no more need to do widget._list, may just be _list

2nd The setState do not need to return a function, you can do only:

  future.then((value) {
    if (value != null) {
      setState(() {
        widget._list.add(value);
      });
    }
  });

Note: I only removed the Arrow-Function () => { }

Browser other questions tagged

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