skip to Main Content

Here is my code, I already managed to add items (authors) to my list, so now how do I delete them? I didn’t find anything here on stackoverflow to help

APP.DART

import 'package:autores/view/list.dart';
import 'package:flutter/material.dart';
class App extends StatelessWidget {

    const App({super.key});
    

    @override 
    Widget build(BuildContext context) {
     return MaterialApp(
     theme: ThemeData(
     useMaterial3: true,
     colorScheme: ColorScheme.fromSeed(seedColor: Colors.lightBlue.shade400),
),
  home: ListAutor(),
);
}


}

List.dart
import 'package:autores/model/autor.dart';
import 'package:autores/view/form.dart';
import 'package:flutter/material.dart

class ListAutor extends StatefulWidget {
 final list<Autor> _autores = [];
ListAutor({super.key});
@override
State<ListAutor>createState() => _ListAutorState();
}
class _ListAutorState extends State<ListAutor> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Lista de Autores'),
),
boby: ListView.builder(
itemCount: widget._autores.length,
itemBuilder: (context,index) {
final autor = widget._autores[index];
return ItemAutor(autor);
},
},
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const FormAutor ();
})).then ((autor) => {
if (autor!= null) {
setState(() {
widget._autores.add(autor);
})
}
});
},),
);
}
}
class ItemAutor extends StatelessWidget {
  final Autor _autor;
  const ItemAutor(this._autor, {super.key});

  @override
  Widget build (BuildContext context) {
  return Card(
  child:ListTile(
  title: Text(_autor.nome),
  subtitle: Text(_autor.anoNascimento.toString()),
),
);
}

}

Autor.dart


Class Autor {
  final String nome;
  final int anoNascimento;
  
  Autor(this.nome, this.anoNascimento);

}




Form.dart


import 'package:autores/model/autor.dart';
import 'package:flutter/material.dart';

class FormAutor extends StatefulWidget {
 const FormAutor({super.key});

 @override
 State<FormAutor> createState() => _FormAutorState();
}
class _FormAutorState extends State<FormAutor> {
  final TextEditingController _ctrlNome = TextEditingController();
  final TextEditingController _ctrlAno  = TextEditingController();

 @override
 Widget build(BuildContext context) {
  return Scaffold(
appBar: AppBar(
 title: const Text ('Formulario Autor'),
),
 body: SingleChildScrollView(
  child: Column(
  children: [
  Padding(
   padding: const EdgeInsets.all(16.0),
 child: TextField(
  controller: _ctrlNome,
  decoration: const InputDecoration(
  labelText: 'Nome do autor'
  hintText: 'Joaquim da Silva'
),
keyboardType: TextInputType.text,
),
),
 Padding(
  padding: const EdgeInsets.all(16.0),
  child: TextField(
  controller: _ctrlAno,
  decoration: const InputDecoration(
  labelText: 'Ano de nascimento do autor',
  hintText: '1990'
),
 keyboardType: TextInputType.number,
),
),
 FloatingActionButton(
   child: const Icon(Icons.save),
   onPressed: (){
   final int? anoNascimento = int.tryParse(_ctrlAno.text);
   final string nome = _ctrlNome.text;
  if(anoNascimento != null) {
   final autor = Autor (nome, anoNascimento);
   Navigator.pop(context, autor);
}
})
],
),
),
);
}
}

this is it please help I need it for a homework next friday and if I didn’t make it I will fail this subject, please helpppppppppppppppppppppppppppppppppppppppppppppppppp.

2

Answers


  1. It is really straightforward to delete from an item. All you need to do is add dismissible widget that lets you delete the listtile on left swipe.
    Replace your current code in ListAutor widget with this.

     final autor = widget._autores[index];
              return Dismissible(
                  key: ValueKey<int>(index),
                  onDismissed: (_) {
                    setState(() {
                      widget._autores.removeAt(index);
                    });
                    print(widget._autores.toString());
                  },
                  child: ItemAutor(autor));
    

    Now if you swipe an item left it should be deleted from the list and the UI.

    Login or Signup to reply.
  2. Define a method in the ItemAutor class for deleting a specific item, and then pass the delete method from the ListView.builder. Also, add an IconButton in the ItemAutor ListTile.

    The updated code is as follows:

    class ListAutor extends StatefulWidget {
      final List<Autor> _autores = [];
      ListAutor({super.key});
      @override
      State<ListAutor> createState() => _ListAutorState();
    }
    
    class _ListAutorState extends State<ListAutor> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Lista de Autores'),
          ),
          body: ListView.builder(
            itemCount: widget._autores.length,
            itemBuilder: (context, index) {
              final autor = widget._autores[index];
              return ItemAutor(
                autor,
                () {   // <--------- Pass the method from here
                  setState(() {
                    widget._autores.removeAt(index);
                  });
                },
              );
            },
          ),
          floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(
                builder: (context) {
                  return const FormAutor();
                },
              )).then((autor) => {
                    if (autor != null)
                      {
                        setState(() {
                          widget._autores.add(autor);
                        })
                      }
                  });
            },
          ),
        );
      }
    }
    
    class ItemAutor extends StatelessWidget {
      final Autor _autor;
      final VoidCallback onDelete; // <----- Define a new member
      const ItemAutor(this._autor, this.onDelete, {super.key}); // <--- Also accept it in the constructor
    
      @override
      Widget build(BuildContext context) {
        return Card(
          child: ListTile(
            title: Text(_autor.nome),
            subtitle: Text(_autor.anoNascimento.toString()),
            trailing: IconButton(  // <----- Add a button for deleting the item
              onPressed: onDelete, // <---- Assign the delete method to here
              icon: Icon(Icons.delete),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search