alert dialog button not working when created with generic dialog flutter

Viewed 21

enter image description here

i have created a generic dialog that can create buttons that return some values

import 'package:flutter/material.dart';

typedef DialogOptionBuilder<T> = Map<String, T?> Function();

Future<T?> showGenericDialog<T>({
  required BuildContext context,
  required String title,
  required String content,
  required DialogOptionBuilder optionBuilder,
}) {
  final options = optionBuilder();
  return showDialog<T>(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: options.keys.map((optionTitle) {
          final value = options[optionTitle];
          return TextButton(
            onPressed: () {
              if (value) {
                Navigator.of(context).pop(value);
              } else {
                Navigator.of(context).pop();
              }
            },
            child: Text(optionTitle),
          );
        }).toList(),
      );
    },
  );
}

and when i try to use this generic dialog to create a simple alert dialog that has a button "ok" this "ok" button is not poping out the alert dialog even though i have coded to popout the dialog when no value is returned from the dialog when a button is pressed


Future<void> showCannotShareEmptyNoteDialog(BuildContext context) async {
  return showGenericDialog<void>(
    context: context,
    title: 'Sharing',
    content: "You can't share a empty note",
    optionBuilder: () => {
      'OK': null,
    },
  );
}

in here i'm calling the alert dialog

appBar: AppBar(
        title: const Text("New Note"),
        actions: [
          IconButton(
            onPressed: () async {
              final text = _textController.text;
              if (_note == null || text.isEmpty) {
                await showCannotShareEmptyNoteDialog(context);
              } else {
                Share.share(text);
              }
            },
            icon: const Icon(Icons.share),
          ),
        ],
      ),
1 Answers

ok button is not removing the alert dialog from the screen

thats because your condition below throw exception. since your type is void no value returned.

...
 return TextButton(
    onPressed: () {
       if (value) {  // this one is caused the error. because its null. not bool
          Navigator.of(context).pop(value);
       } else {
          Navigator.of(context).pop();
       }

error:

════════ Exception caught by gesture ═════════
type 'Null' is not a subtype of type 'bool'

change to this:

return TextButton(
  onPressed: () {
    if (value == true) {
      Navigator.of(context).pop(value);
    } else {
      print(value);
      Navigator.of(context).pop();
    }
  },
Related