Flutter 学习 - Widget 之 对话框

前言

本篇我们介绍Flutter中常用的对话框,先看下效果图

对话框 - android.gif
对话框 - ios.gif

正文

Flutter 中对话框也是Widget,有两种显示对话框的方法,对于对画框对使用还有特殊要求,我们后面介绍,先来看下这两种方法
1.showAboutDialog()
2.showDialog()
我们来逐一看下这两个方法

  • 关于对话框 – showAboutDialog()

使用方法

    showAboutDialog(
        context: context,
        applicationName: "Flutter Widget-对话框",
        applicationVersion: '1.0.0');

运行效果见上图动画第一个按钮点击事件

源码分析
showAboutDialog的参数除了context是必选参数,其他的都是可选参数

    void showAboutDialog({
  @required BuildContext context,//应用上下文 类型BuildContext
  String applicationName,//String 类型,应用的名字	
  String applicationVersion,//String 类型,应用的版本
  Widget applicationIcon,//应用的 Icon,类型Widget(可以是Image和Icon)
  String applicationLegalese,//String 类型,应用的法律信息	
  List<Widget> children,//添加在后面的Widget,类型List< Widget>
}) {
  assert(context != null);
  ...
}
  • showDialog()
    showDialog()可以弹出不同类型的Dialog,在Flutter中主要是以下三种:
  1. SimpleDialog
  2. AlertDialog
  3. CupertinoAlertDialog

源码分析
先来看下showDialog的源码

Future<T> showDialog<T>({
  @required BuildContext context,//必选,应用上下文
  bool barrierDismissible = true,//点击背景是否可以关闭 dialog默认为true,点击背景可以关闭 dialog
  Widget child,//要显示的 Widget,这个已经废弃了,请使用 builder
  WidgetBuilder builder,//创建要显示的 Widget
}) {
    ...
}

来看下实际使用方式

  • 使用SimpleDialog
showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text("SimpleDialog"),
            children: <Widget>[
              SimpleDialogOption(
                child: Text("OK"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              SimpleDialogOption(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });

SimpleDialog源码解析
注:参数均为可选

 const SimpleDialog({
    Key key,//Widget 的标识
    this.title,//对话框的标题,通常是 Text
    this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),//标题的边距,类型是EdgeInsetsGeometry
    this.children,//对话框的按钮,显示在对话框标题的下面通常是一组 SimpleDialogOption,类型是List< Widget>
    this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),//内容的边距,类型是EdgeInsetsGeometry	
    this.backgroundColor,//对话框的背景,类型是Color
    this.elevation,//double类型,Button 相对于其父级放置的z坐标,这可以控制Button 下的阴影大小,该值必须>=0
    this.semanticLabel,//String 类型,给文本加上一个语义标签,用于盲人辅助模式下
    this.shape,//Widget 的形状 类型是ShapeBorder
  }) : assert(titlePadding != null),
       assert(contentPadding != null),
       super(key: key);

这里在使用的时候还用到了SimpleDialogOption,SimpleDialogOption是SimpleDialog的选项按钮,源码如下:

 const SimpleDialogOption({
    Key key,//Widget 的标识
    this.onPressed,//点击事件,当手指松开时才触发
    this.child,//显示的内容一般是 Text
  }) : super(key: key);
  • 使用AlertDialog
showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(
              "AlertDialog",
              textAlign: TextAlign.center,
            ),
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text("here is a alert dialog"),
                  Text("this is description")
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("OK"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });

** AlertDialog 源码分析**
注:参数均为可选

const AlertDialog({
    Key key,//	Widget 的标识
    this.title,//对话框的标题通常是 Text
    this.titlePadding,//标题的边距,类型是EdgeInsetsGeometry	
    this.titleTextStyle,//标题的文本格式,类型是TextStyle
    this.content,//对话框的内容	类型是Widget
    this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),//内容的边距,类型是EdgeInsetsGeometry	
    this.contentTextStyle,//内容的文本格式,类型是TextStyle
    this.actions,//对话框的选型按钮,通常是一组 FlatButton,类型是List< Widget>
    this.backgroundColor,//对话框的背景,类型是Color
    this.elevation,//double 类型,Button 相对于其父级放置的z坐标,这可以控制Button 下的阴影大小,该值必须>=0
    this.semanticLabel,//String类型,给文本加上一个语义标签,用于盲人辅助模式下
    this.shape,//Widget 的形状,类型ShapeBorder
  }) : assert(contentPadding != null),
       super(key: key);
  • 使用CupertinoAlertDialog
showDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text("CupertinoAlertDialog"),
            content: Text("this is a CupertinoAlertDialog"),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("OK"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              CupertinoDialogAction(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });

CupertinoAlertDialog源码分析
注:参数均为可选

  const CupertinoAlertDialog({
    Key key,//Widget 的标识
    this.title,//对话框的标题,通常是 Text
    this.content,//对话框的内容,通常是 Text
    this.actions = const <Widget>[],//对话框的选型按钮,通常是一组 CupertinoDialogAction,	类型List< Widget>
    this.scrollController,//可用于控制对话框中内容的滚动控制器,类型ScrollController
    this.actionScrollController,//可用于控制对话框中 actions 的滚动控制器,类型ScrollController
  }) : assert(actions != null),
       super(key: key);

这里在使用CupertinoAlertDialog的时候还用到了CupertinoDialogAction,看下这个源码

 const CupertinoDialogAction({
    this.onPressed,//点击事件,当手指松开时才触发
    this.isDefaultAction = false,//bool 类型,是否默认操作
    this.isDestructiveAction = false,//bool 类型是否是该操作造成摧坏
    this.textStyle,//按钮文本的样式  类型是TextStyle
    @required this.child,
  }) : assert(child != null),
       assert(isDefaultAction != null),
       assert(isDestructiveAction != null);

下面来看下isDestructiveAction 被设置成true的效果 设置为true之后按钮会变成红色,以达到醒目的提示
20190815152748.jpg
下面来看下isDefaultAction 被设置成true的效果,设置为true之后按钮会被加粗
20190815152622.jpg

注意:
1.在使用CupertinoAlertDialog的时候要import ‘package:flutter/cupertino.dart’;
2.使用 Navigator.of(context).pop() 来关闭 SimpleDialog,AlertDialog,CupertinoAlertDialog

下面贴上完整的demo源码,供大家参考:
首先是main.dart文件

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'home_page.dart';

void main() {
  runApp(MyApp());
  if (Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后,是为了在渲染后进行set赋值,覆盖状态栏,写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter 学习 - Widget 之 对话框'),
    );
  }
}

下面就是我们实现dialog的文件,也就是上面代码中的MyHomePage.dart文件

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();

  _showAboutDialog(BuildContext context) {
    showAboutDialog(
        context: context,
        applicationName: "Flutter Widget-对话框",
        applicationVersion: '1.0.0');
  }

  _ShowSimpleDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text("SimpleDialog"),
            children: <Widget>[
              SimpleDialogOption(
                child: Text("OK"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              SimpleDialogOption(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  _ShowAlertDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(
              "AlertDialog",
              textAlign: TextAlign.center,
            ),
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text("here is a alert dialog"),
                  Text("this is description")
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("OK"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  _ShowCupertinoAlertDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text("CupertinoAlertDialog"),
            content: Text("this is a CupertinoAlertDialog"),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("OK"),
                isDestructiveAction: true,
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "OK", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              ),
              CupertinoDialogAction(
                child: Text("CANCEL"),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "CANCEL", toastLength: Toast.LENGTH_SHORT);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            textWidthBasis: TextWidthBasis.parent,
          ),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            RaisedButton(
                  onPressed: () {
                    _showAboutDialog(context);
                  },
                  child: Text("showAboutDialog"),
                ),
            RaisedButton(
                  onPressed: () {
                    _ShowSimpleDialog(context);
                  },
                  child: Text("ShowSimpleDialog"),
                ),
            RaisedButton(
              onPressed: () {
                _ShowAlertDialog(context);
              },
              child: Text("AlertDialog"),
            ),
            RaisedButton(
              onPressed: () {
                _ShowCupertinoAlertDialog(context);
              },
              child: Text("CupertinoAlertDialog"),
            )
          ],
        ));
  }
}

关于Flutter中Dialog的使用方法就介绍完了。
以下是我的Flutter系列的链接,后续会持续更新,欢迎大家指正。

Flutter 系列文章

更多关于技术相关的内容请关注博主公众号–迷途程序猿
迷途程序猿

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值