I’m trying to get the result of this code. I want to show a Confirm AlertDialog with two buttons, One Accepting and Other One Cancelling and want display the result of pressing each button in the debug console. I have read the documentation related to this error but couldn’t find anything helpful.
You can see the error is in first Image.
This is my Code
import 'dart:async';
import 'package:flutter/material.dart';
class dayThirteen extends StatelessWidget {
const dayThirteen({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: AlertWidget(),
);
}
}
class AlertWidget extends StatelessWidget {
AlertWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Day Thirteen (Alert Widget)'),
),
body: Center(
child: Container(
child: ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
onPressed: () async {
final field fieldatt = await confirmalertdialogwidget(context);
print("User Selection $fieldatt");
},
child: Text('Basic AlertDialog')),
),
),
);
}
}
enum field { Confirm, Accept }
Future<field> confirmalertdialogwidget(BuildContext context) async{
showDialog<field>(
barrierDismissible: true,
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Confirm'),
content: Text('This is for notification purpose!!!!'),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
Navigator.of(context).pop(field.Confirm);
},
child: Text("Cancel")),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(field.Accept);
},
child: Text('Accept'),
style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
)
],
);
});
}
2
Answers
You are not returning the Futrue from the method, and the dialog can be dismissed (Thus, the return is optional):
You need to consider naming the Enum and the method based on Dart naming convention
I changed the code and got it working:
Instead of returning the value from the
confirmalertdialogwidget
function we now directly set thefieldatt
variable inside the function. Therefore thefieldatt
variable is now a global variable.