Skip to content

Instantly share code, notes, and snippets.

@alana-mullen
Last active December 20, 2023 02:16
Show Gist options
  • Save alana-mullen/247c8efa117552812bdf8b580435d2ad to your computer and use it in GitHub Desktop.
Save alana-mullen/247c8efa117552812bdf8b580435d2ad to your computer and use it in GitHub Desktop.
Flutter Adaptive AlertDialog

Flutter Adaptive AlertDialog

Open and run in dartpad.dev.

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Adaptive AlertDialog Demo',
debugShowCheckedModeBanner: false,
home: MyHomePage(title: 'Flutter Adaptive AlertDialog Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({super.key, required this.title});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Flutter Adaptive AlertDialog Demo')),
body: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue, // background
foregroundColor: Colors.white, // foreground
),
onPressed: () => showPlatformAlertDialog(
context: context,
title: 'Some title',
message: 'Some message',
dismissText: 'Close me',
),
child: const Text('Open AlertDialog')));
}
}
class PlatformAlertDialog extends StatelessWidget {
const PlatformAlertDialog({
super.key,
this.title,
this.message,
this.dismissText,
});
final String? title;
final String? message;
final String? dismissText;
@override
Widget build(BuildContext context) => Semantics(
label: message ?? '',
enabled: true,
container: true,
child: AlertDialog.adaptive(
title: Text(title ?? ''),
content: Text(message ?? ''),
actions: [
TextButton(
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop('dialog'),
child: Text(dismissText ?? 'Dismiss'),
),
],
),
);
}
showPlatformAlertDialog({
required BuildContext context,
String title = '',
String message = '',
String dismissText = '',
}) =>
showDialog(
context: context,
builder: (_) => PlatformAlertDialog(
title: title, message: message, dismissText: dismissText),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment