skip to Main Content

I have a flutter project that should have the user enter a string input thin put it into a card but for better ux i want to add a delete feature so i put an icon button but i cant think of a way to find the index of the card the user pressed on to delete it .

i have 2 files of code :

main.dart :

import 'package:flutter/material.dart';
import 'home_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: MainSt(),
    );
  }
}

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

  @override
  State<MainSt> createState() => _MainStState();
}

final addController = TextEditingController();
List cardsList = [];

class _MainStState extends State<MainSt> {
  Future<void> _dialogBuilder(BuildContext context) {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Add a word or phrase'),
          content: TextField(
            controller: addController,
            decoration: const InputDecoration(
              border: UnderlineInputBorder(),
              labelText: 'Enter word or phrase',
            ),
          ),
          actions: <Widget>[
            TextButton(
              style: TextButton.styleFrom(
                textStyle: Theme.of(context).textTheme.labelLarge,
              ),
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
                addController.clear();
              },
            ),
            TextButton(
              style: TextButton.styleFrom(
                textStyle: Theme.of(context).textTheme.labelLarge,
              ),
              child: const Text('Done'),
              onPressed: () {
                print(addController.text);
                setState(
                  () {
                    if (!(addController.text.trim().isEmpty)) {
                      cardsList.add(
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Card(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                ListTile(
                                  trailing: IconButton(
                                    icon: Icon(Icons.delete),
                                    onPressed: () {
                                      setState(() {
                                        //add card delete logic
                                      });
                                    },
                                  ),
                                  title: Row(
                                    children: [
                                      SizedBox(
                                        width: 8,
                                      ),
                                      Text(addController.text),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                      addController.clear();
                      Navigator.of(context).pop();
                    } else {
                      addController.clear();
                    }
                  },
                );
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('Wordly'),
            IconButton(
              icon: Icon(Icons.settings),
              onPressed: () {
                // Add your action here
              },
            ),
          ],
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              _dialogBuilder(context);
            },
          ),
          SizedBox(
            height: 10,
          ),
          FloatingActionButton(
            child: Icon(Icons.speaker),
            onPressed: () {},
          ),
        ],
      ),
      body: HomePage(),
    );
  }
}

and home_page.dart :

import 'package:flutter/material.dart';
import 'package:wordly/main.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: cardsList.length,
      itemBuilder: (context, index) {
        return cardsList[index];
      },
    );
  }
}

i tried saving the index before adding the card but The problem is that I am using the variable cardCurruntIndex to store the index of the card when it is added, but when you remove the card, the index might have changed due to the removal of other cards.i asked also chatGPT and bard but they didnot do anything rather than more errors .

2

Answers


  1. hi I made some changes in your code and it is working as you want

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData(
            useMaterial3: true,
          ),
          debugShowCheckedModeBanner: false,
          home: MainSt(),
        );
      }
    }
    
    class MainSt extends StatefulWidget {
      const MainSt({Key? key}) : super(key: key);
    
      @override
      State<MainSt> createState() => _MainStState();
    }
    
    final addController = TextEditingController();
    List cardsList = [];
    
    class _MainStState extends State<MainSt> {
      Future<void> _dialogBuilder(BuildContext context) {
        return showDialog<void>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Add a word or phrase'),
              content: TextField(
                controller: addController,
                decoration: const InputDecoration(
                  border: UnderlineInputBorder(),
                  labelText: 'Enter word or phrase',
                ),
              ),
              actions: <Widget>[
                TextButton(
                  style: TextButton.styleFrom(
                    textStyle: Theme.of(context).textTheme.labelLarge,
                  ),
                  child: const Text('Cancel'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    addController.clear();
                  },
                ),
                TextButton(
                  style: TextButton.styleFrom(
                    textStyle: Theme.of(context).textTheme.labelLarge,
                  ),
                  child: const Text('Done'),
                  onPressed: () {
                    print(addController.text);
                    setState(
                      () {
                        if (!(addController.text.trim().isEmpty)) {
                          cardsList.add(addController.text);
                          addController.clear();
                          Navigator.of(context).pop();
                        } else {
                          addController.clear();
                        }
                      },
                    );
                  },
                ),
              ],
            );
          },
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('Wordly'),
                IconButton(
                  icon: Icon(Icons.settings),
                  onPressed: () {
                    // Add your action here
                  },
                ),
              ],
            ),
          ),
          floatingActionButton: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () {
                  _dialogBuilder(context);
                },
              ),
              SizedBox(
                height: 10,
              ),
              FloatingActionButton(
                child: Icon(Icons.speaker),
                onPressed: () {},
              ),
            ],
          ),
          body: HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemCount: cardsList.length,
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Card(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ListTile(
                      trailing: IconButton(
                        icon: Icon(Icons.delete),
                        onPressed: () {
                          setState(() {
                            //add card delete logic
                            cardsList.removeAt(index);
                          });
                        },
                      ),
                      title: Row(
                        children: [
                          SizedBox(
                            width: 8,
                          ),
                          Text(cardsList[index]),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      }
    }
    
    Login or Signup to reply.
  2. Instead of passing a List of Widgets to listView, you should make a single widget and pass it to the list view, and in that widget you should pass List of String, which will contain all your added names, So it will give you an opportunity to also pass a callback to that single widget,in that callback you can remove item from your List of String on that particular widget and then setstate.

    This will be the variable

    List<String> cardsTextList = [];
    

    This will be your list View Widget

    class HomePage extends StatefulWidget {
    const HomePage({super.key});
    
    @override
    State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
    @override
    Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: cardsTextList.length,
      itemBuilder: (context, index) {
        return CardWidget(
          text: cardsTextList[index],
          onDelete: () {
            cardsTextList.removeAt(index);
            setState(() {});
          },
        );
      },
    );
    }
    }
    
    class CardWidget extends StatelessWidget {
    const CardWidget({
    super.key,
    required this.text,
    required this.onDelete,
    });
    
    final String text;
    final void Function() onDelete;
    
    @override
    Widget build(BuildContext context) {
     return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Card(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              trailing: IconButton(
                icon: const Icon(Icons.delete),
                onPressed: () {
                  onDelete();
                },
              ),
              title: Row(
                children: [
                  const SizedBox(
                    width: 8,
                  ),
                  Text(text),
                ],
              ),
            ),
          ],
        ),
       ),
      );
     }
     }
    

    And That’s how you can change the value of your list

     onPressed: () {
                print(addController.text);
                setState(
                  () {
                    if (!(addController.text.trim().isEmpty)) {
                      cardsTextList.add(addController.text);
                      addController.clear();
                      Navigator.of(context).pop();
                    } else {
                      addController.clear();
                    }
                  },
                );
              },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search