How to show a alertbox before disming a Listtile in Flutter

60 Views Asked by At

I was trying to do a Listview.I want to delete a each row and on sliding (dismissible widget). Before dismising i want o conform using a alertbox. Also there is another problem that is i want alternate list to have Squared and circular image. But it not working in the right way.


import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sample/signin.dart';

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

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

class _HomePageState extends State<HomePage> {
  List<int> items = List<int>.generate(20, (int index) => index);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          "Home Page",
          style: GoogleFonts.ubuntuCondensed(fontWeight: FontWeight.bold),
        ),
        actions: [
          IconButton(
            onPressed: () {
              showAlertDialog(context);
            },
            icon: const Icon(Icons.logout),
          ),
        ],
      ),
      body: SafeArea(
        child: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Dismissible(
              direction: DismissDirection.vertical,
              background: Container(
                color: Colors.red,
                child: Icon(Icons.delete),
              ),
              key: ValueKey<int>(items[index]),
              onDismissed: (direction) {
                setState(() {
                  items.removeAt(index);
                });
              },
              child: ListViewWidget(
                index: index,
              ),
            );
          },
        ),
      ),
    );
  }
}

class ListViewWidget extends StatefulWidget {
  final index;
  const ListViewWidget({
    super.key,
    this.index,
  });

  @override
  State<ListViewWidget> createState() => _ListViewWidgetState();
}

class _ListViewWidgetState extends State<ListViewWidget> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: ListTile(
        leading: (widget.index % 2 == 0)
            ? Image.network(
                'https://upload.wikimedia.org/wikipedia/commons/9/9e/Placeholder_Person.jpg',
                height: 50,
                width: 50,
              )
            : CircleAvatar(
                radius: 25,
                backgroundImage: NetworkImage(
                  'https://cdn3.iconfinder.com/data/icons/business-vol-26/100/Artboard_2-512.png',
                ),
              ),
        title: Text(
          " Person ${widget.index + 1}",
          style: GoogleFonts.ubuntu(fontWeight: FontWeight.bold),
        ),
        trailing: IconButton(
          icon: Icon(Icons.delete),
          onPressed: () {},
        ),
      ),
    );
  }
}

showAlertDialog(BuildContext ctx) {
  // set up the buttons
  Widget logoutButton = TextButton(
    style: TextButton.styleFrom(backgroundColor: Colors.red),
    child: const Text(
      "Log Out",
      style: TextStyle(color: Colors.white),
    ),
    onPressed: () {
      Navigator.of(ctx).push(MaterialPageRoute(
        builder: (ctx) => const SignInPage(),
      ));
    },
  );
  Widget continueButton = TextButton(
    child: const Text(
      "Cancel",
      style: TextStyle(color: Colors.deepPurple),
    ),
    onPressed: () {
      Navigator.pop(ctx);
    },
  );

  //  the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text(
      "Warning",
      style:
          GoogleFonts.openSans(color: Colors.red, fontWeight: FontWeight.bold),
    ),
    content: Text(
      "Would you like to continue or Logout",
      style:
          GoogleFonts.archivo(color: Colors.black, fontStyle: FontStyle.italic),
    ),
    actions: [
      continueButton,
      logoutButton,
    ],
  );

  // show the dialog
  showDialog(
    context: ctx,
    builder: (BuildContext ctx) {
      return alert;
    },
  );
}

/* Delete Alert box */
// showDeleteAlertBox(BuildContext ctx) {
//   // set up the buttons
//   Widget deleteButton = TextButton(
//     style: TextButton.styleFrom(backgroundColor: Colors.red),
//     child: const Text(
//       "Delete",
//       style: TextStyle(color: Colors.white),
//     ),
//     onPressed: () {},
//   );
//   Widget continueButton = TextButton(
//     child: const Text(
//       "Cancel",
//       style: TextStyle(color: Colors.deepPurple),
//     ),
//     onPressed: () {
//       Navigator.pop(ctx);
//     },
//   );

//   //  the AlertDialog
//   AlertDialog alert = AlertDialog(
//     title: Text(
//       "Warning",
//       style:
//           GoogleFonts.openSans(color: Colors.red, fontWeight: FontWeight.bold),
//     ),
//     content: Text(
//       "Do you want to delete the item",
//       style:
//           GoogleFonts.archivo(color: Colors.black, fontStyle: FontStyle.italic),
//     ),
//     actions: [
//       continueButton,
//       deleteButton ,
//     ],
//   );

//   // show the dialog
//   showDialog(
//     context: ctx,
//     builder: (BuildContext ctx) {
//       return alert;
//     },
//   );
// }

Please reply anything and suggest any updates if i have any problems.

2

There are 2 best solutions below

1
On BEST ANSWER

Show an alert show it on onDismissed(_){} for circular avatar try to wrap a widget with cliprrect and give borederradius.

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

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

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

class _HomePageState extends State<HomePage> {
  List<int> items = List<int>.generate(20, (int index) => index);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          "Home Page",
          style: GoogleFonts.ubuntuCondensed(fontWeight: FontWeight.bold),
        ),
        actions: [
          IconButton(
            onPressed: () {
              showAlertDialog(context);
            },
            icon: const Icon(Icons.logout),
          ),
        ],
      ),
      body: SafeArea(
        child: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Dismissible(
              direction: DismissDirection.vertical,
              background: Container(
                color: Colors.red,
                child: Icon(Icons.delete),
              ),
              key: ValueKey<int>(items[index]),
              onDismissed: (direction) {
                showDialog<void>(
                  context: context,
                  barrierDismissible: false, // user must tap button!
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: const Text('Are you Sure'),
                      content: const SingleChildScrollView(
                        child: ListBody(
                          children: <Widget>[
                            Text('once Deleted you cannot restore'),
                          ],
                        ),
                      ),
                      actions: <Widget>[
                        TextButton(
                          child: const Text('calcel'),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                        TextButton(
                          child: const Text('Delete'),
                          onPressed: () {
                            items.removeAt(index);
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    );
                  },
                ).then((value) {
                  setState(() {});
                });
              },
              child: ListViewWidget(
                index: index,
              ),
            );
          },
        ),
      ),
    );
  }
}

class ListViewWidget extends StatefulWidget {
  final index;
  const ListViewWidget({
    super.key,
    this.index,
  });

  @override
  State<ListViewWidget> createState() => _ListViewWidgetState();
}

class _ListViewWidgetState extends State<ListViewWidget> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: ListTile(
        leading: (widget.index % 2 == 0)
            ? ClipRRect(
                borderRadius: BorderRadius.circular(25),
                child: Image.network(
                  'https://upload.wikimedia.org/wikipedia/commons/9/9e/Placeholder_Person.jpg',
                  height: 50,
                  width: 50,
                  fit: BoxFit.cover,
                ),
              )
            : ClipRRect(
                borderRadius: BorderRadius.circular(25),
                child: CircleAvatar(
                  radius: 25,
                  backgroundImage: NetworkImage(
                    'https://cdn3.iconfinder.com/data/icons/business-vol-26/100/Artboard_2-512.png',
                  ),
                ),
              ),
        title: Text(
          " Person ${widget.index + 1}",
          style: GoogleFonts.ubuntu(fontWeight: FontWeight.bold),
        ),
        trailing: IconButton(
          icon: Icon(Icons.delete),
          onPressed: () {},
        ),
      ),
    );
  }
}

showAlertDialog(BuildContext ctx) {
  // set up the buttons
  Widget logoutButton = TextButton(
    style: TextButton.styleFrom(backgroundColor: Colors.red),
    child: const Text(
      "Log Out",
      style: TextStyle(color: Colors.white),
    ),
    onPressed: () {},
  );
  Widget continueButton = TextButton(
    child: const Text(
      "Cancel",
      style: TextStyle(color: Colors.deepPurple),
    ),
    onPressed: () {
      Navigator.pop(ctx);
    },
  );

  //  the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text(
      "Warning",
      style:
          GoogleFonts.openSans(color: Colors.red, fontWeight: FontWeight.bold),
    ),
    content: Text(
      "Would you like to continue or Logout",
      style:
          GoogleFonts.archivo(color: Colors.black, fontStyle: FontStyle.italic),
    ),
    actions: [
      continueButton,
      logoutButton,
    ],
  );

  // show the dialog
  showDialog(
    context: ctx,
    builder: (BuildContext ctx) {
      return alert;
    },
  );
}
0
On

call this method on onDismissed and pass the context and index:

Future<bool> deleteItem(BuildContext context, int index) async {
    return (await showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Delete Item'),
            content: Text('Are you sure you want delete this item?'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  setState(() {
                    items.removeAt(index);
                  });
                },
                child: Text('YES'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('NO'),
              ),
            ],
          ),
        )) ??
        false;
  }