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

版權(quán)聲明:本文為作者原創(chuàng)書籍。轉(zhuǎn)載請(qǐng)注明作者和出處,未經(jīng)授權(quán),嚴(yán)禁私自轉(zhuǎn)載,侵權(quán)必究!!!

情感語(yǔ)錄: 今日的事情,盡心、盡意、盡力去做了,無(wú)論成績(jī)?nèi)绾危紤?yīng)該高高興興地上床恬睡。

歡迎來(lái)到本章節(jié),上一章節(jié)介紹了常用可滾動(dòng)組件的使用,知識(shí)點(diǎn)回顧 戳這里 Flutter基礎(chǔ)第十章

本章簡(jiǎn)要:

1、AlertDialog 對(duì)話框

2、SimpleDialog 對(duì)話框

3、showModalBottomSheet 底部彈框

4、CupertionDialogAction IOS風(fēng)格對(duì)話框

5、LinearProgressIndicator 條形進(jìn)度條

6、CircularProgressIndicatorr 圓形進(jìn)度條

7、自定義對(duì)話框和進(jìn)度條實(shí)現(xiàn)加載 Dialog 效果

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

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

context : 必傳參數(shù)上下文。

barrierDismissible: 點(diǎn)擊其他區(qū)域是否能關(guān)閉對(duì)話框。

child : 指各種類型的對(duì)話框。

一、AlertDialog 對(duì)話框

像 Android 原生中 AlertDialog 一樣,它可以實(shí)現(xiàn)一個(gè)提示對(duì)話題 ,但它的使用比原生更加方便靈活。

構(gòu)造函數(shù):

  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                         對(duì)話框標(biāo)題

    titlePadding                  標(biāo)題的內(nèi)距

    titleTextStyle                標(biāo)題文字樣式

    content                       對(duì)話框內(nèi)容

    contentPadding                話框內(nèi)容內(nèi)距

    contentTextStyle              話框內(nèi)容樣式

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

    elevation                     設(shè)置陰影(視乎沒(méi)效果)

    shape                         設(shè)置Dialog 形狀,如圓角

簡(jiǎn)單運(yùn)用:

  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(
         //表示點(diǎn)擊灰色背景的時(shí)候是否消失彈出框
          barrierDismissible:false,
          context:context,
          builder: (context){
            return AlertDialog(
              //添加背景色
              backgroundColor:Colors.white,
              elevation: 1000,
              // 文字內(nèi)容內(nèi)距
              contentPadding:EdgeInsets.all(30) ,
              //標(biāo)題
              title: Text("提示信息!",style: TextStyle(color: Colors.redAccent),),
              //內(nèi)容
              content:Text("您確定要?jiǎng)h除嗎?"),
              //控制圓角
              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

是吧! 非常簡(jiǎn)單,這里使用了RoundedRectangleBorder 來(lái)控制 Dialog 進(jìn)行了圓角樣式, 在 Flutter 中還有很多 ShapeBorder 可以選擇,更多用法請(qǐng)參閱內(nèi)部源碼。

二、SimpleDialog 對(duì)話框

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

構(gòu)造函數(shù):

  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 屬性 接收的是一個(gè)List<Widget> 這意味著我們可以在這里面自定義各種各樣的組件和樣式。

簡(jiǎn)單運(yùn)用:

  _simpleDialog() async{

    var result= await  showDialog(

        barrierDismissible:false,
        context:context,
        builder: (context){
          return SimpleDialog(
            title:Text("選擇內(nèi)容",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

從上面的兩個(gè)案例中 無(wú)論是 async 和 await 還是 then () 接收回調(diào)函數(shù)都能正確拿到從 Dialog 中返回的值。在 Flutter 開(kāi)發(fā)中盡量使用 then() 方式,因?yàn)樗逆準(zhǔn)秸{(diào)用能明確代碼執(zhí)行的依賴關(guān)系和實(shí)現(xiàn)異常捕獲。

三、showModalBottomSheet 底部彈出框

showModalBottomSheet 屬性和 AlertDialog 一致。它在開(kāi)發(fā)中也是非常實(shí)用的,如:常見(jiàn)的底部彈出一個(gè)分享的彈出框,還有如上傳頭像是彈出的選擇 照片或者相機(jī)的彈出框。下面來(lái)仿寫一個(gè)分享彈框:

 _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)),
                  //按鈕點(diǎn)擊回調(diào)
                  onPressed: () =>  Navigator.pop(context)
                ),

              ],

            ),
          );
        });
  }

效果如下:

showModalBottomSheet.gif

寫的比較簡(jiǎn)單,圖片也是隨便用的系統(tǒng)的,但可以看出效果還是不錯(cuò)的 O(∩_∩)O

四、CupertinoAlertDialog IOS 風(fēng)格對(duì)話框

CupertinoAlertDialog 和 AlertDialog 在使用上沒(méi)有什么區(qū)別,需要注意的是 使用IOS 風(fēng)格的 actions 時(shí) 也得使用 IOS 風(fēng)格的 CupertinoDialogAction 組件。

   _showCupertinoAlertDialog() {

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

效果如下:

CupertinoAlertDialog.gif

考慮到在 Android 平臺(tái)下各種復(fù)制環(huán)境情況下的兼容性,開(kāi)發(fā)中還是建議少使用 IOS 風(fēng)格的組件。

五、LinearProgressIndicator 條形進(jìn)度條

LinearProgressIndicator 本身不能設(shè)置高度,可以通過(guò)一層父容器設(shè)置高度來(lái)間接設(shè)置,它的使用也是非常常見(jiàn);如:通常在做下載時(shí),給用戶提示一個(gè) 條形進(jìn)度條提示用戶正在下載操作。

構(gòu)造函數(shù):

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

常用屬性:

    屬性                           描述

    value                          0~1的浮點(diǎn)數(shù),用來(lái)表示進(jìn)度值;如果 value 為 null 或空,則顯示一個(gè)動(dòng)畫,否則顯示一個(gè)定值

    backgroundColor                背景顏色

    valueColor                     animation類型的參數(shù),用來(lái)設(shè)定進(jìn)度值的顏色,默認(rèn)為主題色

簡(jiǎn)單運(yùn)用:

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

效果如下:

LinearProgressIndicator.gif

六、CircularProgressIndicator 圓形進(jìn)度條

CircularProgressIndicator 同 LinearProgressIndicator 一樣 本身不能設(shè)置高度,智能通過(guò)一層父容器設(shè)置高度來(lái)間接設(shè)置,在用法上也是如出一轍。

常用屬性:

    屬性                           描述

    value                          0~1的浮點(diǎn)數(shù),用來(lái)表示進(jìn)度值;如果 value 為 null 或空,則顯示一個(gè)動(dòng)畫,否則顯示一個(gè)定值

    backgroundColor                背景顏色

    valueColor                     animation類型的參數(shù),用來(lái)設(shè)定進(jìn)度值的顏色,默認(rèn)為主題色
    
    strokeWidth                    可設(shè)置進(jìn)度Bar 寬度

簡(jiǎn)單運(yùn)用:

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

效果如下:

CircularProgressIndicator.gif

七、自定義加載 Dialog 效果

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

首先讓我們的自定義 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 {

  //內(nèi)容布局
  final Widget content;

  //加載中動(dòng)畫
  final Widget progress;

  //dialog 的寬
  double dialogWidth;

  //dialog 的高
  double dialogHight;

  //dialog 的圓角度數(shù)
  double radius;

  // dialog 的容器布局內(nèi)距
  double contentPadding;

  //dialog 的背景顏色
  Color backGroundColor;

  //dialog 的最大顯示時(shí)長(zhǎng) 單位秒。
  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( //創(chuàng)建透明層
      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
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

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

}

首先我們來(lái)看下條形進(jìn)度條,實(shí)例代碼如下:

_LoadingDialog() {

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

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

}

無(wú)論是 Flutter 內(nèi)置的對(duì)話框,還是我們繼承 Dialog 自定義的 對(duì)話框都需要調(diào)用 showDialog 函數(shù)。下面我們來(lái)看下效果圖:

自定義Dialog.gif

LoadingViewDialog 中的屬性配置在代碼中已經(jīng)明確寫出了,這里就不在一 一描述,可以看到 通過(guò)設(shè)置 maxShowTime 顯示最大時(shí)長(zhǎng)和,progress 的樣式類型都是生效了的,但這種樣式的可能并不常用,下面來(lái)看下開(kāi)發(fā)中常用的加載樣式:

實(shí)例代碼:

_LoadingDialog() {

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

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

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

效果如下:

自定義Dialog2.gif

好了本章節(jié)到此結(jié)束,又到了說(shuō)再見(jiàn)的時(shí)候了,如果你喜歡請(qǐng)留下你的小紅星,你們的支持才是創(chuàng)作的動(dòng)力,如有錯(cuò)誤,請(qǐng)熱心的你留言指正, 謝謝大家觀看,下章再會(huì) O(∩_∩)O

實(shí)例源碼地址: https://github.com/zhengzaihong/flutter_learn

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容