Home > database >  Flutter AlertDialog in seperate file does not show
Flutter AlertDialog in seperate file does not show

Time:01-09

I want to show a AlertDialog in Flutter when I click on the FloatingActionButton. Therefore I have put the AlertDialog Widget in a separate Class. But when I click the Floating button, nothing happens. I import the file with the AlertDialog so this one should work. But what else do I miss? As far as I understand, as soon as I create an instance of this class, the AlertButton shows up on the display.

The FloatingButton looks like this:

...
        floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            DisplayDesc(desc: 'Test description', grade: 'A  ');
          },
          elevation: 10.0,
          label: const Text('Show Description'),
          icon: const Icon(Icons.description),
          backgroundColor: Colors.blue[900],
          foregroundColor: Colors.white,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
...

and the class with the AlertDialog looks like this:

import 'package:flutter/material.dart';

    class DisplayDesc extends StatelessWidget {
      //const DisplayDesc({Key? key}) : super(key: key);
    
      final String desc;
      final String grade;
    
      DisplayDesc ({ required this.desc, required this.grade });
    
      @override
      Widget build(BuildContext context) {
        return AlertDialog(
          title: Text(desc),
          content: Text(grade),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.pop(context, 'Cancel'),
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context, 'OK'),
              child: const Text('OK'),
            ),
          ],
        );
      }
    }

What do I miss?

Thanks Chris

CodePudding user response:

Change your FloatingActionButton's onPressed like so

onPressed: () => showDialog(
  context: context,
  builder: (context) => DisplayDesc(desc: 'Test description', grade: 'A  ')
),
  •  Tags:  
  • Related