【Flutter】【弹窗】弹窗的快速上手使用和自定义Dialog


在这里插入图片描述

前言


一、弹窗的作用

给用户提示,让用户做出选择,或者是实现部分内容

二、开始学习

dialog 都需要 showDialog 才能显示出来,可以使用button点击触发
showDialog :

barrierDismissible: 点击弹框外部区域是否返回默认是true
barrierColor: 屏障的颜色
barrierLabel: 'barrierLabel',//给屏障定义一个string name
anchorPoint: OffSet(1,2)  //锚点 可以使整个弹出框位置发生偏移

1.AlertDialog 提示框

代码如下(示例):

            ElevatedButton(
                onPressed: () async {
                  // 等用户选择返回结果,点击空白区域返回null
                  var result = await showDialog(
                      barrierDismissible: true, //点击空白是否退出
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          // titlePadding: EdgeInsets.all(10),
                          elevation: 10,
                          backgroundColor: Colors.pink, //背景颜色

                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)), //设置形状

                          title: const Text('我是标题'),
                          // icon: Icon(Icons.work_rounded),
                          content: const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text('我可以是文本内容我可以是文本内容我可以是文本内容我可以是文本内容'),
                          ),
                          contentTextStyle: const TextStyle(
                              color: Colors.black), //文本内容的text样式
                          actions: [
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(true);
                                  },
                                  child: const Text('确定')),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: const Text('取消')),
                            ),
                          ],
                        );
                      });

                  print('result$result');
                },
                child: Text('AlertDialog')),

在这里插入图片描述

2.showCupertinoDialog 和 CupertinoAlertDialog

IOS 风格的退出框,其他的工同上
代码如下(示例):

            ElevatedButton(
              onPressed: () async {
                var resutl = await showCupertinoDialog(
                    context: context,
                    builder: (context) {
                      return CupertinoAlertDialog(
                        title: Text('标题'),
                        content: Text("文本内容文本内容文本内容文本内容"),
                        actions: [
                          CupertinoDialogAction(
                              onPressed: () {
                                Navigator.of(context).pop(true);
                              },
                              child: Text('确定')),
                          CupertinoDialogAction(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: Text('取消')),
                        ],
                      );
                    });
                print('result$resutl');
              },
              child: Text('CupertinoAlertDialog ios'),
            ),

在这里插入图片描述

3.SimpleDialog一个简单的弹窗

            ElevatedButton(
              onPressed: () async {
                var resutl = await showDialog(
                    context: context,
                    builder: (context) {
                      return SimpleDialog(
                        title: const Text('标题'),
                        children: [
                          //这边自己定义widget内容
                          Center(
                            child: Text(
                              '要删除这个数据吗?',
                              style: Theme.of(context).textTheme.bodyMedium,
                            ),
                          ),
                          TextButton(
                              onPressed: () {
                                Navigator.of(context).pop(true);
                              },
                              child: const Text(
                                '确定',
                                style: TextStyle(color: Colors.red),
                              )),
                          TextButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: const Text(
                                '取消',
                              )),
                        ],
                      );
                    });
                print('result$resutl');
              },
              child: Text('SimpleDialog 自己定义'),
            ),

在这里插入图片描述

3.自己定义一个Dialog,可以加入gif 图片

Dialog 可以完全的自己定义一个弹出框,然后可以自己定义整个弹出框的内容,比如加入图片等等

// 使用dialog 来自己真正的定义一个对话框
  Widget myDialog() {
    return Dialog(
      // insetPadding: EdgeInsets.all(10), //距离
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))), //形状
      backgroundColor: Colors.pinkAccent,
      clipBehavior: Clip.antiAlias, //强制裁剪
      elevation: 10,
      child: SizedBox(
        //需要在内部限制下高度和宽度才能更好的显示
        height: 250,
        width: 300,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // const Text('中奖拉'),
            Image.asset('assets/getit.gif'),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('取消')),
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {},
                    child: const Text('领奖')),
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {
                      Navigator.of(context).pop(true);
                    },
                    child: const Text('确定')),
              ],
            )
          ],
        ),
      ),
    );
  }

            ElevatedButton(
              onPressed: () async {
                var resutl = await showDialog(
                    context: context,
                    builder: (context) {
                      return myDialog();
                    });
              },
              child: Text('Dialog 自定义'),
            )

在这里插入图片描述


总结

全文代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
// 使用dialog 来自己真正的定义一个对话框
  Widget myDialog() {
    return Dialog(
      // insetPadding: EdgeInsets.all(10), //距离
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))), //形状
      backgroundColor: Colors.pinkAccent,
      clipBehavior: Clip.antiAlias, //强制裁剪
      elevation: 10,
      child: SizedBox(
        //需要在内部限制下高度和宽度才能更好的显示
        height: 250,
        width: 300,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // const Text('中奖拉'),
            Image.asset('assets/getit.gif'),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('取消')),
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {},
                    child: const Text('领奖')),
                ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.green)),
                    onPressed: () {
                      Navigator.of(context).pop(true);
                    },
                    child: const Text('确定')),
              ],
            )
          ],
        ),
      ),
    );
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            ElevatedButton(
                onPressed: () async {
                  // 等用户选择返回结果,点击空白区域返回null
                  var result = await showDialog(
                      barrierLabel: 'barrierLabel', //给屏障定义一个string name
                      barrierDismissible: true, //点击空白是否退出
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          // titlePadding: EdgeInsets.all(10),
                          elevation: 10,
                          backgroundColor: Colors.pink, //背景颜色

                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)), //设置形状

                          title: const Text('我是标题'),
                          // icon: Icon(Icons.work_rounded),
                          content: const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text('我可以是文本内容我可以是文本内容我可以是文本内容我可以是文本内容'),
                          ),
                          contentTextStyle: const TextStyle(
                              color: Colors.black), //文本内容的text样式
                          actions: [
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(true);
                                  },
                                  child: const Text('确定')),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: ElevatedButton(
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: const Text('取消')),
                            ),
                          ],
                        );
                      });

                  print('result$result');
                },
                child: Text('AlertDialog')),
            ElevatedButton(
              onPressed: () async {
                var resutl = await showCupertinoDialog(
                    context: context,
                    builder: (context) {
                      return CupertinoAlertDialog(
                        title: Text('标题'),
                        content: Text("文本内容文本内容文本内容文本内容"),
                        actions: [
                          CupertinoDialogAction(
                              onPressed: () {
                                Navigator.of(context).pop(true);
                              },
                              child: Text('确定')),
                          CupertinoDialogAction(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: Text('取消')),
                        ],
                      );
                    });
                print('result$resutl');
              },
              child: Text('CupertinoAlertDialog ios'),
            ),
            ElevatedButton(
              onPressed: () async {
                var resutl = await showDialog(
                    context: context,
                    builder: (context) {
                      return SimpleDialog(
                        title: const Text('标题'),
                        children: [
                          //这边自己定义widget内容
                          Center(
                            child: Text(
                              '要删除这个数据吗?',
                              style: Theme.of(context).textTheme.bodyMedium,
                            ),
                          ),
                          TextButton(
                              onPressed: () {
                                Navigator.of(context).pop(true);
                              },
                              child: const Text(
                                '确定',
                                style: TextStyle(color: Colors.red),
                              )),
                          TextButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: const Text(
                                '取消',
                              )),
                        ],
                      );
                    });
                print('result$resutl');
              },
              child: Text('SimpleDialog 自己定义'),
            ),
            ElevatedButton(
              onPressed: () async {
                var resutl = await showDialog(
                    context: context,
                    builder: (context) {
                      return myDialog();
                    });
              },
              child: Text('Dialog 自定义'),
            )
          ],
        ),
      ),
    );
  }
}

一般内置的dialog 已经够用了,如果需要自己定义更多的情况,可以自己定义下dialog,下一篇我们来说一下bottomsheet。

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter 弹窗是一种用于在应用程序中显示提示、确认或自定义内容的界面元素。常见的 Flutter 弹窗包括 AlertDialog、CupertinoAlertDialog、SimpleDialog 等。 其中,AlertDialog 提示框是最常用的一种,可以通过 showDialog 方法来显示。可以根据需要设置参数,如 barrierDismissible、barrierColor、barrierLabel 和 anchorPoint 等,来控制弹窗的行为和样式。 除了内置的弹窗类型,我们还可以自定义一个 Dialog,并根据需要添加动画效果,如 GIF 图片等。这样可以实现更加个性化的弹窗效果。 总结来说,Flutter 弹窗是应用程序中常用的界面元素,可以通过内置的弹窗类型或自定义的方式来实现,可以根据需要设置参数来控制弹窗的行为和样式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Flutter自定义Dialog实现版本更新弹窗功能的实现](https://download.csdn.net/download/weixin_38746926/12722459)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【Flutter】【弹窗弹窗快速上手使用自定义Dialog](https://blog.csdn.net/weixin_43444734/article/details/127481395)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值