flutterdartdialog

Display a Flutter Alert Dialog when meeting a condition or on error from method


In the following code, the message "Not A Double" is displayed whenever the value in the TextField is not a double value. This is done from the methods in this Flutter app. Instead of the message shown as in here, I'd like them to be displayed in Alert Dialogues. How can I achieve that? Thank you.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late TextEditingController myController;
  String text = "INIT";

  bool is_double_input(String str) {
    double a = 0.0;
    int exception_caught = 0;
    try {
      a = double.parse(str);
    } catch (e) {
      exception_caught++;
    } finally {
      if (exception_caught == 0) {
        return true;
      } else {
        return false;
      }
    }
  }

  void setMessage(String myStr) {
    // text = myStr;
    if (is_double_input(myStr)) {
      text = myStr;
    } else {
      text = "Not A Double";
    }
  }

  @override
  void initState() {
    super.initState();
    myController = TextEditingController();
  }

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          Expanded(
            child: TextField(
              controller: myController,
              keyboardType: TextInputType.number,
              onChanged: (value) {
                setState(() {
                  setMessage(value);
                });
              },
            ),
          ),
          Expanded(
            child: Text("MESSAGE: ${text}"),
          ),
        ],
      ),
    );
  }
}

UPDATE 01: Though the question is now answered, I've also added additional code in showDialog to to pop the Alert Dialog but this is not working. I'm having to touch outside of the Alert dialog to dismiss the dialog. Can someone help? Here is the code:

showDialog(
  context: context,
  builder: (context) => AlertDialog(
    title: const Text('Error'),
    content: const Text('Not a Double'),
    actions: [
      TextButton(
        onPressed: () {
          Navigator.of(context).pop;
        },
        child: const Text("Ok"),
      ),
    ],
  ),
);

Solution

  • You can send the BuildContext to the setMessage method and, in the else, you can show the dialog you need:

    ...
    void setMessage(String myStr, BuildContext context) {
        // text = myStr;
        if (is_double_input(myStr)) {
          text = myStr;
        } else {
        
          showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: Text('Error'),
                      content: Text('Not a Double'),
                    ),
                  );
        }
      }