Flutter第十一章(AlertDialog ,SimpleDialog ,showModalBottomSheet,CupertionDialogAction ,LinearProgres...

版權聲明:本文為作者原創書籍。轉載請注明作者和出處,未經授權,嚴禁私自轉載,侵權必究?。。?/a>

情感語錄: 今日的事情,盡心、盡意、盡力去做了,無論成績如何,都應該高高興興地上床恬睡。

歡迎來到本章節,上一章節介紹了常用可滾動組件的使用,知識點回顧 戳這里 Flutter基礎第十章

本章簡要:

1、AlertDialog 對話框

2、SimpleDialog 對話框

3、showModalBottomSheet 底部彈框

4、CupertionDialogAction IOS風格對話框

5、LinearProgressIndicator 條形進度條

6、CircularProgressIndicatorr 圓形進度條

7、自定義對話框和進度條實現加載 Dialog 效果

前景提要: 為了不贅述,這里 說明下在 Flutter 中 要彈出對話框需要 在 showDialog()函數中處理,且它是一個異步的,如果要接收對話框里的返回值 可以通過 Dart 中講解的 async 和 await 來處理接收值,也可以使用 Flutter 中提供的 then() 接收一個異步的回調函數,可以在這里面處理接收值。 Dialog的關閉 使用Navigator.pop(context);或者 Navigator.pop(context,"傳值");

   Future<T> showDialog<T>({
      @required BuildContext context,
      bool barrierDismissible = true,
      @Deprecated(
      ) Widget child,
      WidgetBuilder builder,
    })

context : 必傳參數上下文。

barrierDismissible: 點擊其他區域是否能關閉對話框。

child : 指各種類型的對話框。

一、AlertDialog 對話框

像 Android 原生中 AlertDialog 一樣,它可以實現一個提示對話題 ,但它的使用比原生更加方便靈活。

構造函數:

  const AlertDialog({
    Key key,
    this.title,
    this.titlePadding,
    this.titleTextStyle,
    this.content,
    this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
    this.contentTextStyle,
    this.actions,
    this.backgroundColor,
    this.elevation,
    this.semanticLabel,
    this.shape,
  }) 
常用屬性:
    屬性                           描述

    title                         對話框標題

    titlePadding                  標題的內距

    titleTextStyle                標題文字樣式

    content                       對話框內容

    contentPadding                話框內容內距

    contentTextStyle              話框內容樣式

    actions                       一般放 確定 取消按鈕組
     
    backgroundColor               對話框背景色

    elevation                     設置陰影(視乎沒效果)

    shape                         設置Dialog 形狀,如圓角

簡單運用:

  import 'package:flutter/material.dart';
  import 'package:flutter_learn/util/ToastUtil.dart';

  class DialogPage extends StatefulWidget {
    DialogPage({Key key}) : super(key: key);

    _DialogPageState createState() => _DialogPageState();
  }

  class _DialogPageState extends State<DialogPage> {

    _alertDialog() {

      showDialog(
         //表示點擊灰色背景的時候是否消失彈出框
          barrierDismissible:false,
          context:context,
          builder: (context){
            return AlertDialog(
              //添加背景色
              backgroundColor:Colors.white,
              elevation: 1000,
              // 文字內容內距
              contentPadding:EdgeInsets.all(30) ,
              //標題
              title: Text("提示信息!",style: TextStyle(color: Colors.redAccent),),
              //內容
              content:Text("您確定要刪除嗎?"),
              //控制圓角
              shape:RoundedRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(10))),

              actions: <Widget>[
                FlatButton(
                  child: Text("取消"),
                  onPressed: (){
                    Navigator.pop(context,'Cancle');
                  },
                ),
                FlatButton(
                  child: Text("確定"),
                  onPressed: (){
                    Navigator.pop(context,"Ok");
                  },
                )
              ],
            );
          }
      ).then((value){
        ToastUtil.show("回傳值:"+value);
      });
    }

效果如下:

AlertDialog.gif

是吧! 非常簡單,這里使用了RoundedRectangleBorder 來控制 Dialog 進行了圓角樣式, 在 Flutter 中還有很多 ShapeBorder 可以選擇,更多用法請參閱內部源碼。

二、SimpleDialog 對話框

SimpleDialog 用法與 AlertDialog 非常相似,SimpleDialog 常常結合 SimpleDialogOption 組件一起使用。

構造函數:

  const SimpleDialog({
    Key key,
    this.title,
    this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
    this.children,
    this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
    this.backgroundColor,
    this.elevation,
    this.semanticLabel,
    this.shape,
  })

SimpleDialog 中的屬性和 AlertDialog 幾乎一致,需要注意的是 這里的 children 屬性 接收的是一個List<Widget> 這意味著我們可以在這里面自定義各種各樣的組件和樣式。

簡單運用:

  _simpleDialog() async{

    var result= await  showDialog(

        barrierDismissible:false,
        context:context,
        builder: (context){
          return SimpleDialog(
            title:Text("選擇內容",style: TextStyle(color: Colors.blue)),
            children: <Widget>[

              SimpleDialogOption(
                child: Text("Option A"),
                onPressed: (){
                  Navigator.pop(context,"A");
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text("Option B"),
                onPressed: (){
                  Navigator.pop(context,"B");
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text("Option C"),
                onPressed: (){
                  Navigator.pop(context,"C");
                },
              ),
              Divider(),

            ],

          );
        }
    );

    ToastUtil.show("回傳值:"+result);

  }

效果如下:

SimpleDialog.gif

從上面的兩個案例中 無論是 async 和 await 還是 then () 接收回調函數都能正確拿到從 Dialog 中返回的值。在 Flutter 開發中盡量使用 then() 方式,因為它的鏈式調用能明確代碼執行的依賴關系和實現異常捕獲。

三、showModalBottomSheet 底部彈出框

showModalBottomSheet 屬性和 AlertDialog 一致。它在開發中也是非常實用的,如:常見的底部彈出一個分享的彈出框,還有如上傳頭像是彈出的選擇 照片或者相機的彈出框。下面來仿寫一個分享彈框:

 _modelBottomSheet() {

    showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
            color: Colors.white,
            height: 220,
            child: Column(
              children: <Widget>[
                Container(
                  height: 50,
                  child: Center(
                    child: Text(
                      "分享",
                      style: TextStyle(color: Colors.black54),
                    ),
                  ),
                ),
                Divider(),
                Row(
                  mainAxisAlignment:MainAxisAlignment.center,
                  children: <Widget>[

                    Container(
                      width: 80,
                      color: Colors.white,
                      child: Column(children: <Widget>[
                        Icon(Icons.chat,color: Colors.green, size: 40,),
                        SizedBox(height: 10),
                        Text('微信', style: TextStyle(color: Colors.deepPurple)),

                      ],)
                    ),

                    Container(
                        width: 140,
                        color: Colors.white,
                        child: Column(children: <Widget>[
                          Icon(Icons.question_answer,color: Colors.green,size: 40,),
                          SizedBox(height: 10),
                          Text('QQ', style: TextStyle(color: Colors.deepPurple)),

                        ],)
                    ),

                    Container(
                        width: 80,
                        color: Colors.white,
                        child: Column(children: <Widget>[
                          Icon(Icons.web,color: Colors.green,size: 40,),
                          SizedBox(height: 10),
                          Text('微博', style: TextStyle(color: Colors.deepPurple)),

                        ],)
                    ),
                  ],
                ),

                SizedBox(height: 20),

                FlatButton(

                  textColor: Colors.white,
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.grey,
                  color: Colors.blue,
                  highlightColor: Colors.blue[700],
                  colorBrightness: Brightness.dark,
                  splashColor: Colors.grey,
                  child: Text("取消"),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0)),
                  //按鈕點擊回調
                  onPressed: () =>  Navigator.pop(context)
                ),

              ],

            ),
          );
        });
  }

效果如下:

showModalBottomSheet.gif

寫的比較簡單,圖片也是隨便用的系統的,但可以看出效果還是不錯的 O(∩_∩)O

四、CupertinoAlertDialog IOS 風格對話框

CupertinoAlertDialog 和 AlertDialog 在使用上沒有什么區別,需要注意的是 使用IOS 風格的 actions 時 也得使用 IOS 風格的 CupertinoDialogAction 組件。

   _showCupertinoAlertDialog() {

    showDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("iOS風格的對話框"),
            content: Column(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Align(
                  child: Text("你確定不關注我嗎?"),
                  alignment: Alignment(0, 0),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text("確定"),
                onPressed: () {
                },
              ),
            ],
          );
        });
  }

效果如下:

CupertinoAlertDialog.gif

考慮到在 Android 平臺下各種復制環境情況下的兼容性,開發中還是建議少使用 IOS 風格的組件。

五、LinearProgressIndicator 條形進度條

LinearProgressIndicator 本身不能設置高度,可以通過一層父容器設置高度來間接設置,它的使用也是非常常見;如:通常在做下載時,給用戶提示一個 條形進度條提示用戶正在下載操作。

構造函數:

  const LinearProgressIndicator({
    Key key,
    double value,
    Color backgroundColor,
    Animation<Color> valueColor,
    String semanticsLabel,
    String semanticsValue,
  })

常用屬性:

    屬性                           描述

    value                          0~1的浮點數,用來表示進度值;如果 value 為 null 或空,則顯示一個動畫,否則顯示一個定值

    backgroundColor                背景顏色

    valueColor                     animation類型的參數,用來設定進度值的顏色,默認為主題色

簡單運用:

  SizedBox(
    child: LinearProgressIndicator(
        //背景顏色
        backgroundColor: Colors.yellow,
        //進度顏色
        valueColor: new AlwaysStoppedAnimation<Color>(Colors.red)),
    height: 8.0,
    width: 200,

效果如下:

LinearProgressIndicator.gif

六、CircularProgressIndicator 圓形進度條

CircularProgressIndicator 同 LinearProgressIndicator 一樣 本身不能設置高度,智能通過一層父容器設置高度來間接設置,在用法上也是如出一轍。

常用屬性:

    屬性                           描述

    value                          0~1的浮點數,用來表示進度值;如果 value 為 null 或空,則顯示一個動畫,否則顯示一個定值

    backgroundColor                背景顏色

    valueColor                     animation類型的參數,用來設定進度值的顏色,默認為主題色
    
    strokeWidth                    可設置進度Bar 寬度

簡單運用:

   new SizedBox(
        //限制進度條的高度
        height: 40.0,
        //限制進度條的寬度
        width: 40,
        child: new CircularProgressIndicator(
            strokeWidth: 3,
            //背景顏色
            backgroundColor: Colors.yellow,
            //進度顏色
            valueColor: new AlwaysStoppedAnimation<Color>(Colors.red)),
      ),

效果如下:

CircularProgressIndicator.gif

七、自定義加載 Dialog 效果

為了讓我們的 Dialog 更加通用性,我們盡可能的讓 Dialog 的樣式從外部傳入,用戶盡可能多的能夠控制它的樣式。比如: 我們要實現 能夠設置 Dialog 的最大顯示時長,加載效果支持 圓形進度條或者條形進度條或者是他們的派生類,圓角,背景等。

首先讓我們的自定義 Widget 繼承 Dialog ,如下:

import 'dart:async';

import 'package:flutter/material.dart';

/*
 * creat_user: zhengzaihong
 * Email:1096877329@qq.com
 * creat_date: 2019/9/2
 * creat_time: 9:50
 * describe  自定義dialog
 **/

// ignore: must_be_immutable
class LoadingViewDialog extends Dialog {

  //內容布局
  final Widget content;

  //加載中動畫
  final Widget progress;

  //dialog 的寬
  double dialogWidth;

  //dialog 的高
  double dialogHight;

  //dialog 的圓角度數
  double radius;

  // dialog 的容器布局內距
  double contentPadding;

  //dialog 的背景顏色
  Color backGroundColor;

  //dialog 的最大顯示時長 單位秒。
  int maxShowTime ;

  LoadingViewDialog({
    Key key,
    this.dialogWidth = 120.0,
    this.dialogHight = 120.0,
    this.content,
    this.progress,
    this.radius = 8.0,
    this.contentPadding = 20,
    this.maxShowTime = 100,
    this.backGroundColor =  Colors.white
  }) :
        super(key: key);

  @override
  Widget build(BuildContext context) {

    showTimer(context);
    return new Material( //創建透明層
      type: MaterialType.transparency, //透明類型
      child: new Center( //保證控件居中效果

        child: new SizedBox(
          width: dialogWidth,
          height: dialogHight,
          child: new Container(
            padding: EdgeInsets.all(contentPadding),
            decoration: ShapeDecoration(
              color: backGroundColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(radius),
                ),
              ),
            ),
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                progress,
                Padding(
                  padding: const EdgeInsets.only(
                    top: 20,
                  ),
                  child: content
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  //添加定時
  showTimer(context) {
    Timer.periodic(Duration(milliseconds: maxShowTime*1000), (t) {
      Navigator.pop(context);
      //取消定時器
      t.cancel();
    });
  }

}

首先我們來看下條形進度條,實例代碼如下:

_LoadingDialog() {

  showDialog(
      context: context, //BuildContext對象
      barrierDismissible: false,
      builder: (BuildContext context) {
        //調用我們的自定義 對話框
        return LoadingViewDialog(
          progress: LinearProgressIndicator(
              //背景顏色
              backgroundColor: Colors.yellow,
              //進度顏色
              valueColor: AlwaysStoppedAnimation<Color>(Colors.red)
          ),

          content: Text(
            '正在加載...',
            style: TextStyle(color: Colors.blue),
          ),
          maxShowTime: 5,
        );
      });

}

無論是 Flutter 內置的對話框,還是我們繼承 Dialog 自定義的 對話框都需要調用 showDialog 函數。下面我們來看下效果圖:

自定義Dialog.gif

LoadingViewDialog 中的屬性配置在代碼中已經明確寫出了,這里就不在一 一描述,可以看到 通過設置 maxShowTime 顯示最大時長和,progress 的樣式類型都是生效了的,但這種樣式的可能并不常用,下面來看下開發中常用的加載樣式:

實例代碼:

_LoadingDialog() {

  showDialog(
      context: context, //BuildContext對象
      barrierDismissible: false,
      builder: (BuildContext context) {
        return LoadingViewDialog(
          //調用對話框

            progress: CircularProgressIndicator(
              strokeWidth: 3,
              //背景顏色
              backgroundColor: Colors.red,
              //進度顏色
            ),

          content: Text(
            '正在加載...',
            style: TextStyle(color: Colors.blue),
          ),
          maxShowTime: 5,
        );
      });
}

效果如下:

自定義Dialog2.gif

好了本章節到此結束,又到了說再見的時候了,如果你喜歡請留下你的小紅星,你們的支持才是創作的動力,如有錯誤,請熱心的你留言指正, 謝謝大家觀看,下章再會 O(∩_∩)O

實例源碼地址: https://github.com/zhengzaihong/flutter_learn

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容