Flutter之Dialog使用和踩坑

入魔的冬瓜發表於2019-01-31

簡單介紹

最近使用了Flutter的展示對話方塊的功能,踩了一點坑,順便做下總結,方便各位以後少踩坑,如果有說錯的地方,還請大家指出來。

Flutter之Dialog使用和踩坑

下面將介紹對話方塊的幾種場景和踩坑。

  • 展示普通對話方塊
  • 展示包含列表項的對話方塊
  • 對話方塊介面需要動態重新整理
  • 自定義對話方塊。

先理解一些東西

  • 對話方塊本質上是屬於一個路由的頁面route,由Navigator進行管理,所以控制對話方塊的顯示和隱藏,也是呼叫Navigator.of(context)的push和pop方法。

  • 在Flutter中,對話方塊會有兩種風格,呼叫showDialog()方法展示的是material風格的對話方塊,呼叫showCupertinoDialog()方法展示的是ios風格的對話方塊。 而這兩個方法其實都會去呼叫showGeneralDialog()方法,可以從原始碼中看到最後是利用Navigator.of(context, rootNavigator: true).push()一個頁面。

基本要傳的引數:context上下文,builder用於建立顯示的widget,barrierDismissible可以控制點選對話方塊以外的區域是否隱藏對話方塊。

  • 你會注意到,showDialog()方法返回的是一個Future物件,可以通過這個future物件來獲取對話方塊所傳遞的資料。 比如我們想知道想知道使用者是點選了對話方塊的確認按鈕還是取消按鈕,那就在退出對話方塊的時候,利用Navigator.of(context).pop("一些資料");
Future<T> showCupertinoDialog<T>({
  @required BuildContext context,
  @required WidgetBuilder builder,
});

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

Future<T> showGeneralDialog<T>({
  @required BuildContext context,
  @required RoutePageBuilder pageBuilder,
  bool barrierDismissible,
  String barrierLabel,
  Color barrierColor,
  Duration transitionDuration,
  RouteTransitionsBuilder transitionBuilder,
}) {
  assert(pageBuilder != null);
  assert(!barrierDismissible || barrierLabel != null);
  return Navigator.of(context, rootNavigator: true).push<T>(_DialogRoute<T>(
    pageBuilder: pageBuilder,
    barrierDismissible: barrierDismissible,
    barrierLabel: barrierLabel,
    barrierColor: barrierColor,
    transitionDuration: transitionDuration,
    transitionBuilder: transitionBuilder,
  ));
}
複製程式碼

簡單的顯示對話方塊

Flutter中的Dialog主要是SimpleDialog和AlertDialog。

  • SimpleDialog,一般可以利用多個SimpleDialogOption為使用者提供了幾個選項。
  • AlertDialog,警告對話方塊。警告對話方塊有一個可選標題title和一個可選列表的actions選項。

展示一個簡單的SimpleDialog,程式碼如下:

void showMySimpleDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new SimpleDialog(
            title: new Text("SimpleDialog"),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text("SimpleDialogOption One"),
                onPressed: () {
                  Navigator.of(context).pop("SimpleDialogOption One");
                },
              ),
              new SimpleDialogOption(
                child: new Text("SimpleDialogOption Two"),
                onPressed: () {
                  Navigator.of(context).pop("SimpleDialogOption Two");
                },
              ),
              new SimpleDialogOption(
                child: new Text("SimpleDialogOption Three"),
                onPressed: () {
                  Navigator.of(context).pop("SimpleDialogOption Three");
                },
              ),
            ],
          );
        });
  }
複製程式碼

展示一個簡單的Material風格的AlertDialog,程式碼如下:

void showMyMaterialDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text("title"),
            content: new Text("內容內容內容內容內容內容內容內容內容內容內容"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: new Text("確認"),
              ),
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: new Text("取消"),
              ),
            ],
          );
        });
  }
複製程式碼

展示一個簡單的IOS風格的AlertDialog,程式碼如下:

void showMyCupertinoDialog(BuildContext context) {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return new CupertinoAlertDialog(
            title: new Text("title"),
            content: new Text("內容內容內容內容內容內容內容內容內容內容內容"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop("點選了確定");
                },
                child: new Text("確認"),
              ),
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop("點選了取消");
                },
                child: new Text("取消"),
              ),
            ],
          );
        });
  }
複製程式碼

展示列表項對話方塊(踩坑了)

構造對話方塊的時候,我們都需要傳一個content物件,來構造對話方塊的主要內容。一般情況下,如果content裡面只是簡單的一些內容,那問題不大,可以正常顯示。 但是有時候,我們需要展示一個列表對話方塊。這個時候,如果列表項比較多,就會出現一些問題。

  • 使用Column+SingleChildScrollView來顯示列表對話方塊。

當Column的列表項資料比較多的時候,螢幕已經放不了,就會出現overflow錯誤了,所以這個時候需要在外部巢狀一個SingleChildScrollView控制元件,使內部child控制元件可以滾動, 不會出現overflow錯誤。(哈哈,可以使用下面的程式碼跑一跑,然後去掉SingleChildScrollView,對比執行結果)

void showMyDialogWithColumn(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text("title"),
            content: new SingleChildScrollView(
              child: new Column(
                children: <Widget>[
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                  new SizedBox(
                    height: 100,
                    child: new Text("1"),
                  ),
                ],
              ),
            ),
            actions: <Widget>[
              new FlatButton(
                onPressed: () {},
                child: new Text("確認"),
              ),
              new FlatButton(
                onPressed: () {},
                child: new Text("取消"),
              ),
            ],
          );
        });
  }
複製程式碼
  • 使用ListView+指定寬度和高度的Container來顯示對話方塊

要將ListView包裝在具有特定寬度和高度的Container中。 如果Container沒有定義這兩個屬性的話,會報錯,無法顯示ListView。(目前我也是這樣解決的,不知道有沒有人有其他更好的方法哈。) 報錯如下:

void showMyDialogWithListView(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
            content: new Container(
          /*
              暫時的解決方法:要將ListView包裝在具有特定寬度和高度的Container中
              如果Container沒有定義這兩個屬性的話,會報錯,無法顯示ListView
               */
          width: MediaQuery.of(context).size.width * 0.9,
          height: MediaQuery.of(context).size.height * 0.9,
          child: new ListView.builder(
            itemBuilder: (context, index) {
              return new SizedBox(
                height: 100,
                child: new Text("1"),
              );
            },
            itemCount: 10,
            shrinkWrap: true,
          ),
        ));
      },
    );

  //如果直接將ListView放在dialog中,會報錯,比如
  //下面這種寫法會報錯:I/flutter (10721): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
  //    I/flutter (10721): The following assertion was thrown during performLayout():
  //    I/flutter (10721): RenderShrinkWrappingViewport does not support returning intrinsic dimensions.
  //    I/flutter (10721): Calculating the intrinsic dimensions would require instantiating every child of the viewport, which
  //    I/flutter (10721): defeats the point of viewports being lazy.
  //    I/flutter (10721): If you are merely trying to shrink-wrap the viewport in the main axis direction, you should be able
  //    I/flutter (10721): to achieve that effect by just giving the viewport loose constraints, without needing to measure its
  //    I/flutter (10721): intrinsic dimensions.
  //    I/flutter (10721):
  //    I/flutter (10721): When the exception was thrown, this was the stack:
  //    I/flutter (10721): #0      RenderShrinkWrappingViewport.debugThrowIfNotCheckingIntrinsics.<anonymous closure> (package:flutter/src/rendering/viewport.dart:1544:9)
  //    I/flutter (10721): #1      RenderShrinkWrappingViewport.debugThrowIfNotCheckingIntrinsics (package:flutter/src/rendering/viewport.dart:1554:6)
  //    I/flutter (10721): #2      RenderViewportBase.computeMaxIntrinsicWidth (package:flutter/src/rendering/viewport.dart:321:12)
  //    I/flutter (10721): #3      RenderBox._computeIntrinsicDimension.<anonymous closure> (package:flutter/src/rendering/box.dart:1109:23)
  //    I/flutter (10721): #4      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:277:23)
  //    I/flutter (10721): #5      RenderBox._computeIntrinsicDimension (package:flutter/src/rendering/box.dart:1107:41)
  //    I/flutter (10721): #6      RenderBox.getMaxIntrinsicWidth (package:flutter/src/rendering/box.dart:1291:12)
  //    I/flutter (10721): #7      _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeMaxIntrinsicWidth (package:flutter/src/rendering/proxy_box.dart:81:20)

  //        showDialog(context: context, builder: (context) {
  //      return new AlertDialog(title: new Text("title"),
  //        content: new SingleChildScrollView(
  //          child: new Container(
  //            height: 200,
  //            child: new ListView.builder(
  //              itemBuilder: (context, index) {
  //                return new SizedBox(height: 100, child: new Text("1"),);
  //              }, itemCount: 10, shrinkWrap: true,),
  //          ),
  //        ),
  //        actions: <Widget>[
  //          new FlatButton(onPressed: () {}, child: new Text("確認"),),
  //          new FlatButton(onPressed: () {}, child: new Text("取消"),),
  //        ],);
  //    });


複製程式碼

需要動態更新介面的對話方塊

利用StatefulBuilder來實現一些對話方塊場景,需要對話方塊動態更新介面的。

比如在對話方塊裡面顯示一個checkbox,然後點選會修改checkbox的顯示狀態。如果是跟之前一樣的實現對話方塊方法, 是無法實現動態去重新整理對話方塊的介面的。

StatefulBuilder可以包含一個child,具有狀態,可以呼叫setState重新整理介面。

builder引數,用於建立想要顯示的widget,可以呼叫StateSetter型別的setState引數來進行重新整理介面。

Flutter之Dialog使用和踩坑
typedef StatefulWidgetBuilder = Widget Function(BuildContext context, StateSetter setState);

 const StatefulBuilder({
    Key key,
    @required this.builder
  }) : assert(builder != null),
       super(key: key);
複製程式碼

例項的程式碼如下:

 void showMyDialogWithStateBuilder(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          bool selected = false;
          return new AlertDialog(
            title: new Text("StatefulBuilder"),
            content:
                new StatefulBuilder(builder: (context, StateSetter setState) {
              return Container(
                child: new CheckboxListTile(
                    title: new Text("選項"),
                    value: selected,
                    onChanged: (bool) {
                      setState(() {
                        selected = !selected;
                      });
                    }),
              );
            }),
          );
        });
  }
複製程式碼

自定義Dialog

比如我想顯示一個菊花的loading載入框,那麼用上面的方法都是行不通的。這個時候就需要我們去自定義一個對話方塊。

首先我們可以先去看一下Dialog的原始碼實現,然後只需再照著原始碼的實現,修改一下就行了。大部分程式碼是保持一致的,所以 對話方塊的顯示效果比如動畫,主題都是一致的。

下面是Dialog原始碼中的build方法實現。簡單的修改下child屬性所傳的引數就行了。

 @override
  Widget build(BuildContext context) {
    final DialogTheme dialogTheme = DialogTheme.of(context);
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
      duration: insetAnimationDuration,
      curve: insetAnimationCurve,
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        //所以我們其實只需要修改child這個屬性了,改成我們想要展示的widget就行了。
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: 280.0),
            child: Material(
              elevation: 24.0,
              color: _getColor(context),
              type: MaterialType.card,
              child: child,
              shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
            ),
          ),
        ),
      ),
    );
  }
複製程式碼

下面是一個自定義載入框Dialog的例子,就是將AlertDialog的原始碼進行剛才所說的修改就行了。

Flutter之Dialog使用和踩坑
  void showMyCustomLoadingDialog(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return new MyCustomLoadingDialog();
        });
  }

class MyCustomLoadingDialog extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Duration insetAnimationDuration = const Duration(milliseconds: 100);
    Curve insetAnimationCurve = Curves.decelerate;

    RoundedRectangleBorder _defaultDialogShape = RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(2.0)));

    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets +
          const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
      duration: insetAnimationDuration,
      curve: insetAnimationCurve,
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: Center(
          child: SizedBox(
            width: 120,
            height: 120,
            child: Material(
              elevation: 24.0,
              color: Theme.of(context).dialogBackgroundColor,
              type: MaterialType.card,
              //在這裡修改成我們想要顯示的widget就行了,外部的屬性跟其他Dialog保持一致
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  new CircularProgressIndicator(),
                  Padding(
                    padding: const EdgeInsets.only(top: 20),
                    child: new Text("載入中"),
                  ),
                ],
              ),
              shape: _defaultDialogShape,
            ),
          ),
        ),
      ),
    );
  }
}
複製程式碼

Demo的Github地址

github.com/LXD31256949…

公眾號

最近弄了個學習Flutter的公眾號(入魔的冬瓜),一部分是搬磚一些國外文章再加些自己的理解,一部分是自己平時的總結。

希望與大家在2019一起學習,共同進步!

祝大家狗年快樂!

Flutter之Dialog使用和踩坑

相關文章