Flutter 讓你的Dialog脫胎換骨吧!(Attach,Dialog,Loading,Toast)

小呆呆666發表於2022-01-08

前言

Q:你一生中聞過最臭的東西,是什麼?

A:我那早已腐爛的夢。

兄弟萌!!!我又來了!

這次,我能自信的對大家說:我終於給大家帶了一個,能真正幫助大家解決諸多坑比場景的pub包!

將之前的flutter_smart_dialog,在保持api穩定的基礎上,進行了各種抓頭重構,解決了一系列問題

現在,我終於可以說:它現在是一個簡潔,強大,侵入性極低的pub包!

關於侵入性問題

  • 之前為了解決返回關閉彈窗,使用了一個很不優雅的解決方法,導致侵入性有點高
  • 這真是讓我如坐鍼氈,如芒刺背,如鯁在喉,這個問題終於搞定了!

同時,我在pub包內部設計了一個彈窗棧,能自動移除棧頂彈窗,也可以定點移除棧內標記的彈窗。

存在的問題

使用系統彈窗存在一系列坑,來和各位探討探討

  • 必須傳BuildContext

    • 在一些場景必須多做一些傳參工作,蛋痛但不難的問題
  • loading彈窗

    • 使用系統彈窗做loading彈窗,肯定遇到過這個坑比問題

      • loading封裝在網路庫裡面:請求網路時載入loading,手賤按了返回按鈕,關閉了loading
      • 然後請求結束後發現:特麼我的頁面怎麼被關了!!!
    • 系統彈窗就是一個路由頁面,關閉系統就是用pop方法,這很容易誤關正常頁面

      • 當然肯定有解決辦法,路由監聽的地方處理,此處就不細表了
  • 某頁面彈出了多個系統Dialog,很難定點關閉某個非棧頂彈窗

    • 蛋蛋,這是路由入棧出棧機制導致的,理解的同時也一樣要吐槽
  • 系統Dialog,點選事件無法穿透暗色背景

    • 這個坑比問題,我是真沒轍
相關思考

上面列舉了一些比較常見的問題,最嚴重的問題,應該就是loading的問題

  • loading是個超高頻使用的彈窗,關閉loading彈窗的方法,同時也能關閉正常使用的頁面,本身就是一個隱患
  • 穿透dialog遮罩是個非常重要的功能,基於該功能,能夠在實際業務中,實現很多騷操作
  • 既然在系統dialog難以解決各種痛點,加上系統dialog也是基於overlay去實現的,這樣的話,我們也可以去高度定製overlay!

這次,我要一次性幫各位解決:toast訊息,loading彈窗,以及更強大的自定義dialog!

快速上手

初始化
dependencies:
  flutter_smart_dialog: ^3.2.0
  • 接入方式更加簡潔?
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage,
      // here
      navigatorObservers: [FlutterSmartDialog.observer],
      // here
      builder: FlutterSmartDialog.init(),
    );
  }
}
極簡使用
  • toast使用?
SmartDialog.showToast('test toast');

toastDefault

  • loading使用
SmartDialog.showLoading();
await Future.delayed(Duration(seconds: 2));
SmartDialog.dismiss(); 

loadingDefault

  • dialog使用?
var custom = Container(
    height: 80,
    width: 180,
    decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(20),
    ),
    alignment: Alignment.center,
    child: Text('easy custom dialog', style: TextStyle(color: Colors.white)),
);
// here
SmartDialog.show(widget: custom, isLoadingTemp: false);

dialogEasy

OK,上面展示了,只需要極少的程式碼,就可以呼叫相應的功能

當然,內部還有不少地方做了特殊優化,接下來,我會詳細的向大家描述下

你可能會有的疑問

初始化框架的時候,相比以前,居然讓大家多寫了一個引數,內心十分愧疚?

關閉頁面本質上是一個比較複雜的情況,涉及到

  • 物理返回按鍵
  • AppBar的back按鈕
  • 手動pop

為了監控這些情況,不得已增加了一個路由監控引數

實體返回鍵

對返回按鈕的監控,是非常重要的,基本能覆蓋大多數情況

initBack

pop路由

雖然對返回按鈕的監控能覆蓋大多數場景,但是一些手動pop的場景就需要新增引數監控

  • 不加FlutterSmartDialog.observer

    • 如果開啟了穿透引數(就可以和彈窗後的頁面互動),然後手動關閉頁面
    • 就會出現這種很尷尬的情況

initPopOne

  • 加了FlutterSmartDialog.observer,就能比較合理的處理了

    • 當然,這裡的過渡動畫,也提供了引數控制是否開啟 ?

initPopTwo

關於 FlutterSmartDialog.init()

本方法不會佔用你的builder引數,init內部回撥出來了builder,你可以大膽放心的繼續套

  • 例如:繼續套Bloc全域性例項?
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage,
      navigatorObservers: [FlutterSmartDialog.observer],
      builder: FlutterSmartDialog.init(builder: _builder),
    );
  }
}

Widget _builder(BuildContext context, Widget? child) {
  return MultiBlocProvider(
    providers: [
      BlocProvider.value(value: BlocSpanOneCubit()),
    ],
    child: child!,
  );
}
超實用的引數:backDismiss
  • 這個引數是預設設定為true,返回的時候會預設關閉彈窗;如果設定為false,將不會關閉頁面

    • 這樣就可以十分輕鬆的做一個緊急彈窗,禁止使用者的下一步操作
  • 我們來看一個場景:假定某開源作者決定棄坑軟體,不允許使用者再使用該軟體的彈窗
SmartDialog.show(
  // here
  backDismiss: false,
  clickBgDismissTemp: false,
  isLoadingTemp: false,
  widget: Container(
    height: 480,
    width: 500,
    padding: EdgeInsets.all(20),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(20),
      color: Colors.white,
    ),
    alignment: Alignment.topCenter,
    child: SingleChildScrollView(
      child: Wrap(
        direction: Axis.vertical,
        crossAxisAlignment: WrapCrossAlignment.center,
        spacing: 10,
        children: [
          // title
          Text(
            '特大公告',
            style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
          ),
          // content
          Text('鄙人日夜鑽研下面祕籍,終於成功釣到富婆'),
          Image.network(
            'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211102213746.jpeg',
            height: 200,
            width: 400,
          ),
          Text('鄙人思考了三秒鐘,懷著\'沉重\'的心情,決定棄坑本開源軟體'),
          Text('本人今後的生活是富婆和遠方,已無\'精力\' 再維護本開源軟體了'),
          Text('各位叼毛,有緣江湖再見!'),
          // button (only method of close the dialog)
          ElevatedButton(
            onPressed: () => SmartDialog.dismiss(),
            child: Text('再會!'),
          )
        ],
      ),
    ),
  ),
);

hardClose

從上面的效果圖可以看出來

  • 點選遮罩,無法關閉彈窗
  • 點選返回按鈕無法關閉彈窗
  • 只能點我們自己的按鈕,才能關閉彈窗,點選按鈕的邏輯可以直接寫成關閉app之類

只需要倆個簡單的引數設定,就能實現這樣一個很棒的應急彈窗

設定全域性引數

SmartDialog的全域性引數都有著一個比較合理的預設值

為了應付多變的場景,你可以修改符合你自己要求的全域性引數

  • 設定符合你的要求的資料,放在app入口就行初始化就行

    • 注:如果沒有特殊要求,可以不用初始化全域性引數(內部皆有預設值)
SmartDialog.config
  ..alignment = Alignment.center
  ..isPenetrate = false
  ..clickBgDismiss = true
  ..maskColor = Colors.black.withOpacity(0.35)
  ..maskWidget = null
  ..animationDuration = Duration(milliseconds: 260)
  ..isUseAnimation = true
  ..isLoading = true
  ..antiShake = false
  ..antiShakeTime = Duration(milliseconds: 300);
  • 程式碼的註釋寫的很完善,某個引數不明白的,點進去看看就行了

image-20211102223129866

Attach篇

這是一個很重要的功能,本來早就想加進去了,但是比較忙,一直擱置了;元旦(2022.1.1)開了頭,就花了一些時間,完成了這個功能和相關demo

定位

定位目標widget的座標,這個做起來並不難;但是必須要拿到我們傳入的自定義widget大小,這樣才能將自定義widget疊放到一個比較合適的位置(通過一些計算,獲取中心點)

  • 實際上Flutter提供一個非常合適的元件CustomSingleChildLayout,這個元件還提供偏移座標功能,按理來說非常合適
  • 但是,CustomSingleChildLayoutSizeTransition 動畫控制元件,存在佔位面積衝突,只能使用AnimatedOpacity漸隱動畫
  • 位移動畫不能用,這我沒法忍,拋棄 CustomSingleChildLayout;使用了各種騷操作,終於拿到自定義widget的大小,比較完美實現了效果

定位dialog,使用showAttach方法,引數註釋寫的相當詳細,不明白用法的看看註釋就行了

強大的定位功能
  • 必須傳目標widget的BuildContext,需要通過它計算出目標widget的座標和大小
var attach = (BuildContext context, AlignmentGeometry alignment) async {
  SmartDialog.showAttach(
    targetContext: context,
    isPenetrateTemp: true,
    alignmentTemp: alignment,
    clickBgDismissTemp: false,
    widget: Container(width: 100, height: 100, color: randomColor()),
  );
  await Future.delayed(Duration(milliseconds: 350));
};

//target widget
List<BuildContext> contextList = [];
List<Future Function()> funList = [
  () async => await attach(contextList[0], Alignment.topLeft),
  () async => await attach(contextList[1], Alignment.topCenter),
  () async => await attach(contextList[2], Alignment.topRight),
  () async => await attach(contextList[3], Alignment.centerLeft),
  () async => await attach(contextList[4], Alignment.center),
  () async => await attach(contextList[5], Alignment.centerRight),
  () async => await attach(contextList[6], Alignment.bottomLeft),
  () async => await attach(contextList[7], Alignment.bottomCenter),
  () async => await attach(contextList[8], Alignment.bottomRight),
];
var btn = ({
  required String title,
  required Function(BuildContext context) onTap,
}) {
  return Builder(builder: (context) {
    Color? color = title.contains('all') ? randomColor() : null;
    contextList.add(context);
    return Container(
      width: 130,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: ButtonStyleButton.allOrNull<Color>(color),
        ),
        onPressed: () => onTap(context),
        child: Text('$title'),
      ),
    );
  });
};

SmartDialog.show(
  isLoadingTemp: false,
  widget: Container(
    width: 700,
    padding: EdgeInsets.all(70),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(20),
      color: Colors.white,
    ),
    child: Wrap(
      spacing: 50,
      runSpacing: 50,
      alignment: WrapAlignment.spaceEvenly,
      children: [
        btn(title: 'topLeft', onTap: (context) => funList[0]()),
        btn(title: 'topCenter', onTap: (context) => funList[1]()),
        btn(title: 'topRight', onTap: (context) => funList[2]()),
        btn(title: 'centerLeft', onTap: (context) => funList[3]()),
        btn(title: 'center', onTap: (context) => funList[4]()),
        btn(title: 'centerRight', onTap: (context) => funList[5]()),
        btn(title: 'bottomLeft', onTap: (context) => funList[6]()),
        btn(title: 'bottomCenter', onTap: (context) => funList[7]()),
        btn(title: 'bottomRight', onTap: (context) => funList[8]()),
        btn(
          title: 'allOpen',
          onTap: (_) async {
            for (var item in funList) {
              await item();
            }
          },
        ),
        btn(
          title: 'allClose',
          onTap: (_) => SmartDialog.dismiss(status: SmartStatus.allAttach),
        ),
      ],
    ),
  ),
);

attachLocation

動畫效果和show方法幾乎是一致的,為了這個一致的體驗,內部做了相當多的針對性優化

自定義座標點
  • 大多數情況基本都是使用targetContext
SmartDialog.showAttach(
  targetContext: context,
  widget: Container(width: 100, height: 100, color: Colors.red),
);
  • 當然還有少數情況,需要使用自定義座標,此處也提供target引數:設定了target引數,targetContext將自動失效

    • targetContext 是十分常見到場景,所以,這邊設定為必傳引數,但是你可以給它設定為null
SmartDialog.showAttach(
  targetContext: null,
  target: Offset(100, 100);,
  widget: Container(width: 100, height: 100, color: Colors.red),
);
  • 看來下自定義座標點效果
var attach = (Offset offset) {
  var random = Random().nextInt(100) % 5;
  var alignment = Alignment.topCenter;
  if (random == 0) alignment = Alignment.topCenter;
  if (random == 1) alignment = Alignment.centerLeft;
  if (random == 2) alignment = Alignment.center;
  if (random == 3) alignment = Alignment.centerRight;
  if (random == 4) alignment = Alignment.bottomCenter;
  SmartDialog.showAttach(
    targetContext: null,
    target: offset,
    isPenetrateTemp: true,
    clickBgDismissTemp: false,
    alignmentTemp: alignment,
    keepSingle: true,
    widget: ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(width: 100, height: 100, color: randomColor()),
    ),
  );
};

SmartDialog.show(
  isLoadingTemp: false,
  widget: Container(
    width: 600,
    height: 400,
    alignment: Alignment.center,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(20),
      color: Colors.white,
    ),
    child: GestureDetector(
      onTapDown: (detail) => attach(detail.globalPosition),
      child: Container(
        width: 500,
        height: 300,
        color: Colors.grey,
        alignment: Alignment.center,
        child: Text('click me', style: TextStyle(color: Colors.white)),
      ),
    ),
  ),
);

attachPoint

模仿DropdownButton
  • 實際上模仿DropdownButton挺不容易的

    • 首先要計算DropdownButton控制元件的位置,在其位置上顯示點選後的摺疊控制元件
    • 需要處理DropdownButton之外區域的點選事件(點選區域外關閉DropdownButton)
    • 還需要監聽返回事件,手動pop路由事件;是這類事件的,需要關閉DropdownButton
  • 這玩意要自定義,挺讓人頭大的;但是,現在你可以使用SmartDialog.showAttach 輕鬆模仿一個,上述需要注意的事項都幫你處理好了
//模仿DropdownButton
var imitate = (BuildContext context) {
  var list = ['小呆呆', '小菲菲', '小豬豬'];
  SmartDialog.showAttach(
    targetContext: context,
    isPenetrateTemp: true,
    widget: Container(
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(color: Colors.black12, blurRadius: 8, spreadRadius: 0.2)
        ],
      ),
      child: Column(
        children: List.generate(list.length, (index) {
          return Material(
            color: Colors.white,
            child: InkWell(
              onTap: () => SmartDialog.dismiss(),
              child: Container(
                height: 50,
                width: 100,
                alignment: Alignment.center,
                child: Text('${list[index]}'),
              ),
            ),
          );
        }),
      ),
    ),
  );
};

//imitate widget
var dropdownButton = ({String title = 'Dropdown'}) {
  return DropdownButton<String>(
    value: '1',
    items: [
      DropdownMenuItem(value: '1', child: Text('$title:小呆呆')),
      DropdownMenuItem(value: '2', child: Text('小菲菲')),
      DropdownMenuItem(value: '3', child: Text('小豬豬'))
    ],
    onChanged: (value) {},
  );
};
var imitateDropdownButton = () {
  return Builder(builder: (context) {
    return Stack(children: [
      dropdownButton(title: 'Attach'),
      GestureDetector(
        onTap: () => imitate(context),
        child: Container(height: 50, width: 140, color: Colors.transparent),
      )
    ]);
  });
};
SmartDialog.show(
  isLoadingTemp: false,
  widget: Container(
    width: 600,
    height: 400,
    alignment: Alignment.center,
    padding: EdgeInsets.symmetric(horizontal: 100),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(20),
      color: Colors.white,
    ),
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [dropdownButton(), imitateDropdownButton()],
      ),
    ),
  ),
);

attachImitate

高亮

這次把遮罩特定區域高亮的功能加上了,這是一個非常實用的功能!

  • 你只需要設定highlight引數即可

    • 定義高亮的區域,他必須是個不通透的Widget,例如是Contaienr,必須設定一個顏色(色值無要求)

      • 使用各種奇形怪狀的圖片也行,這樣就能顯示各種複雜圖形的高亮區域
    • highlight型別是Positioned,你可以在螢幕上定位任何需要高亮的區域
SmartDialog.showAttach(
  targetContext: context,
  alignmentTemp: Alignment.bottomCenter,
  highlight: Positioned(
    right: 190,
    bottom: 190,
    child: Container(
      height: 120,
      width: 120,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
    ),
  ),
  widget: Container(width: 100, height: 100, color: Colors.red),
);
實際的業務場景
  • 這邊舉倆個常見的例子,程式碼有一點點多,就不貼了,感興趣的請檢視:flutter_use

attachBusiness

上面倆個業務場景非常常見,有時候,我們需要目標widget上面或下面或特定的區域,不被遮罩覆蓋

自己去做的話,可以做出來,但是會很麻煩;現在你可以使用showAttach中的highlight引數輕鬆實現這個需求

引導操作

引導操作在app上還是非常常見的,需要指定區域高亮,然後介紹其功能

  • 使用showAttach中的highlight引數,也可以輕鬆實現這個需求,來看下效果

    • 程式碼同樣有一點點多,感興趣的請檢視:flutter_use

attachGuide

Dialog篇

花裡胡哨

彈窗從不同位置彈出,動畫是有區別的

image-20211031221419600

  • alignmentTemp:該引數設定不同,動畫效果會有所區別
var location = ({
  double width = double.infinity,
  double height = double.infinity,
}) {
  return Container(width: width, height: height, color: randomColor());
};

//left
SmartDialog.show(
  widget: location(width: 70),
  alignmentTemp: Alignment.centerLeft,
);
await Future.delayed(Duration(milliseconds: 500));
//top
SmartDialog.show(
  widget: location(height: 70),
  alignmentTemp: Alignment.topCenter,
);
await Future.delayed(Duration(milliseconds: 500));
//right
SmartDialog.show(
  widget: location(width: 70),
  alignmentTemp: Alignment.centerRight,
);
await Future.delayed(Duration(milliseconds: 500));
//bottom
SmartDialog.show(
  widget: location(height: 70),
  alignmentTemp: Alignment.bottomCenter,
);
await Future.delayed(Duration(milliseconds: 500));
//center
SmartDialog.show(
  widget: location(height: 100, width: 100),
  alignmentTemp: Alignment.center,
  isLoadingTemp: false,
);

dialogLocation

  • isPenetrateTemp:互動事件穿透遮罩
SmartDialog.show(
    alignmentTemp: Alignment.centerRight,
    isPenetrateTemp: true,
    clickBgDismissTemp: false,
    widget: Container(
        width: 80,
        height: double.infinity,
        color: randomColor(),
    ),
);

dialogPenetrate

dialog棧

  • 這是一個強大且實用的功能!

    • 可以很輕鬆的定點關閉某個彈窗
var stack = ({
  double width = double.infinity,
  double height = double.infinity,
  String? msg,
}) {
  return Container(
    width: width,
    height: height,
    color: randomColor(),
    alignment: Alignment.center,
    child: Text('dialog $msg', style: TextStyle(color: Colors.white)),
  );
};

//left
SmartDialog.show(
  tag: 'A',
  widget: stack(msg: 'A', width: 70),
  alignmentTemp: Alignment.centerLeft,
);
await Future.delayed(Duration(milliseconds: 500));
//top
SmartDialog.show(
  tag: 'B',
  widget: stack(msg: 'B', height: 70),
  alignmentTemp: Alignment.topCenter,
);
await Future.delayed(Duration(milliseconds: 500));
//right
SmartDialog.show(
  tag: 'C',
  widget: stack(msg: 'C', width: 70),
  alignmentTemp: Alignment.centerRight,
);
await Future.delayed(Duration(milliseconds: 500));
//bottom
SmartDialog.show(
  tag: 'D',
  widget: stack(msg: 'D', height: 70),
  alignmentTemp: Alignment.bottomCenter,
);
await Future.delayed(Duration(milliseconds: 500));

//center:the stack handler
SmartDialog.show(
  alignmentTemp: Alignment.center,
  isLoadingTemp: false,
  widget: Container(
    decoration: BoxDecoration(
        color: Colors.white, borderRadius: BorderRadius.circular(15)),
    padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
    child: Wrap(spacing: 20, children: [
      ElevatedButton(
        child: Text('close dialog A'),
        onPressed: () => SmartDialog.dismiss(tag: 'A'),
      ),
      ElevatedButton(
        child: Text('close dialog B'),
        onPressed: () => SmartDialog.dismiss(tag: 'B'),
      ),
      ElevatedButton(
        child: Text('close dialog C'),
        onPressed: () => SmartDialog.dismiss(tag: 'C'),
      ),
      ElevatedButton(
        child: Text('close dialog D'),
        onPressed: () => SmartDialog.dismiss(tag: 'D'),
      ),
    ]),
  ),
);

dialogStack

Loading篇

避坑指南

  • 開啟loading後,可以使用以下方式關閉

    • SmartDialog.dismiss():可以關閉loading和dialog
    • status設定為SmartStatus.loading:僅僅關閉loading
// easy close
SmartDialog.dismiss();
// exact close
SmartDialog.dismiss(status: SmartStatus.loading);
  • 一般來說,loading彈窗是封裝在網路庫裡面的,隨著請求狀態的自動開啟和關閉

    • 基於這種場景,我建議:使用dismiss時,加上status引數,將其設定為:SmartStatus.loading
  • 坑比場景

    • 網路請求載入的時候,loading也隨之開啟,這時很容易誤觸返回按鈕,關閉loading
    • 當網路請求結束時,會自動呼叫dismiss方法
    • 因為loading已被關閉,假設此時頁面又有SmartDialog的彈窗,未設定status的dismiss就會關閉SmartDialog的彈窗
    • 當然,這種情況很容易解決,封裝進網路庫的loading,使用:SmartDialog.dismiss(status: SmartStatus.loading); 關閉就行了
  • status引數,是為了精確關閉對應型別彈窗而設計的引數,在一些特殊場景能起到巨大的作用

    • 如果大家理解這個引數的含義,那對於何時新增status引數,必能胸有成竹

引數說明

引數在註釋裡面寫的十分詳細,就不贅述了,來看看效果

image-20211031215728656

  • maskWidgetTemp:強大的遮罩自定義功能?,發揮你的腦洞吧。。。
var maskWidget = Container(
  width: double.infinity,
  height: double.infinity,
  child: Opacity(
    opacity: 0.6,
    child: Image.network(
      'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101103911.jpeg',
      fit: BoxFit.fill,
    ),
  ),
);
SmartDialog.showLoading(maskWidgetTemp: maskWidget);

loadingOne

  • maskColorTemp:支援快捷自定義遮罩顏色
SmartDialog.showLoading(maskColorTemp: randomColor().withOpacity(0.3));

/// random color
Color randomColor() => Color.fromRGBO(
    Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

loadingTwo

  • background:支援載入背景自定義
SmartDialog.showLoading(background: randomColor());

/// random color
Color randomColor() => Color.fromRGBO(
    Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

loadingThree

  • isLoadingTemp:動畫效果切換
SmartDialog.showLoading(isLoadingTemp: false);

loadingFour

  • isPenetrateTemp:互動事件可以穿透遮罩,這是個十分有用的功能,對於一些特殊的需求場景十分關鍵
SmartDialog.showLoading(isPenetrateTemp: true);

loadingFive

自定義Loading

使用showLoading可以輕鬆的自定義出強大的loading彈窗;鄙人腦洞有限,就簡單演示下

自定義一個loading佈局
class CustomLoading extends StatefulWidget {
  const CustomLoading({Key? key, this.type = 0}) : super(key: key);

  final int type;

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

class _CustomLoadingState extends State<CustomLoading>
    with TickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    _controller.forward();
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reset();
        _controller.forward();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      // smile
      Visibility(visible: widget.type == 0, child: _buildLoadingOne()),

      // icon
      Visibility(visible: widget.type == 1, child: _buildLoadingTwo()),

      // normal
      Visibility(visible: widget.type == 2, child: _buildLoadingThree()),
    ]);
  }

  Widget _buildLoadingOne() {
    return Stack(alignment: Alignment.center, children: [
      RotationTransition(
        alignment: Alignment.center,
        turns: _controller,
        child: Image.network(
          'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101174606.png',
          height: 110,
          width: 110,
        ),
      ),
      Image.network(
        'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101181404.png',
        height: 60,
        width: 60,
      ),
    ]);
  }

  Widget _buildLoadingTwo() {
    return Stack(alignment: Alignment.center, children: [
      Image.network(
        'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101162946.png',
        height: 50,
        width: 50,
      ),
      RotationTransition(
        alignment: Alignment.center,
        turns: _controller,
        child: Image.network(
          'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101173708.png',
          height: 80,
          width: 80,
        ),
      ),
    ]);
  }

  Widget _buildLoadingThree() {
    return Center(
      child: Container(
        height: 120,
        width: 180,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15),
        ),
        alignment: Alignment.center,
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          RotationTransition(
            alignment: Alignment.center,
            turns: _controller,
            child: Image.network(
              'https://cdn.jsdelivr.net/gh/xdd666t/MyData@master/pic/flutter/blog/20211101163010.png',
              height: 50,
              width: 50,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Text('loading...'),
          ),
        ]),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
來看看效果
  • 效果一
SmartDialog.showLoading(isLoadingTemp: false, widget: CustomLoading());
await Future.delayed(Duration(seconds: 2));
SmartDialog.dismiss();

loadingSmile

  • 效果二
SmartDialog.showLoading(
    isLoadingTemp: false,
    widget: CustomLoading(type: 1),
);
await Future.delayed(Duration(seconds: 2));
SmartDialog.dismiss();

loadingIcon

  • 效果三
SmartDialog.showLoading(widget: CustomLoading(type: 2));
await Future.delayed(Duration(seconds: 2));
SmartDialog.dismiss();

loadingNormal

Toast篇

toast的特殊性

嚴格來說,toast是一個非常特殊的彈窗,我覺得理應具備下述的特徵

toast訊息理應一個個展示,後續訊息不應該頂掉前面的toast
  • 這是一個坑點,如果框架內部不做處理,很容易出現後面toast會直接頂掉前面toast的情況

    • 當然,內部提供了type引數,你可以選擇你想要的顯示邏輯

toastOne

展示在頁面最上層,不應該被一些彈窗之類遮擋
  • 可以發現loading和dialog的遮罩等佈局,均未遮擋toast資訊

toastTwo

對鍵盤遮擋情況做處理
  • 鍵盤這玩意有點坑,會直接遮擋所有佈局,只能曲線救國

    • 在這裡做了一個特殊處理,當喚起鍵盤的時候,toast自己會動態的調整自己和螢幕底部的距離
    • 這樣就能起到一個,鍵盤不會遮擋toast的效果

toastSmart

自定義Toast

引數說明

toast的一些引數並未向外暴露,僅僅暴露了msg和alignment

  • 例如:toast字型大小,字型顏色,toast的背景色等等之類,都沒提供引數

    • 一是覺得提供了這些引數,會讓整體引數輸入變的非常多,亂花漸入迷人眼
    • 二是覺得就算我提供了很多引數,也不一定會滿足那些奇奇怪怪的審美和需求
  • 基於上述的考慮,我直接提供了大量的底層引數

    • 你可以隨心所欲的定製toast

      • 注意喔,不僅僅可以定製toast,例如:成功提示,失敗提示,警告提示等等
      • Toast做了很多的優化,type引數,讓你能擁有多種顯示邏輯,發揮你的想象力吧
    • 注意:使用了widget引數,msgalignment引數會失效

image-20211217142656380

調整toast顯示的位置
SmartDialog.showToast('the toast at the bottom');
SmartDialog.showToast('the toast at the center', alignment: Alignment.center);
SmartDialog.showToast('the toast at the top', alignment: Alignment.topCenter);

toastLocation

更強大的自定義toast
  • 首先,整一個自定義toast
class CustomToast extends StatelessWidget {
  const CustomToast(this.msg, {Key? key}) : super(key: key);

  final String msg;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        margin: EdgeInsets.only(bottom: 30),
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 7),
        decoration: BoxDecoration(
          color: _randomColor(),
          borderRadius: BorderRadius.circular(100),
        ),
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          //icon
          Container(
            margin: EdgeInsets.only(right: 15),
            child: Icon(Icons.add_moderator, color: _randomColor()),
          ),

          //msg
          Text('$msg', style: TextStyle(color: Colors.white)),
        ]),
      ),
    );
  }

  Color _randomColor() {
    return Color.fromRGBO(
      Random().nextInt(256),
      Random().nextInt(256),
      Random().nextInt(256),
      1,
    );
  }
}
  • 使用
SmartDialog.showToast('', widget: CustomToast('custom toast'));
  • 效果

toastCustom

騷氣的小技巧

有一種場景比較蛋筒

  • 我們使用StatefulWidget封裝了一個小元件
  • 在某個特殊的情況,我們需要在這個元件外部,去觸發這個元件內部的一個方法
  • 對於這種場景,有不少實現方法,但是弄起來可能有點麻煩

這裡提供一個簡單的小思路,可以非常輕鬆的觸發,元件內部的某個方法

  • 建立一個小元件
class OtherTrick extends StatefulWidget {
  const OtherTrick({Key? key, this.onUpdate}) : super(key: key);

  final Function(VoidCallback onInvoke)? onUpdate;

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

class _OtherTrickState extends State<OtherTrick> {
  int _count = 0;

  @override
  void initState() {
    // here
    widget.onUpdate?.call(() {
      _count++;
      setState(() {});
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 50, vertical: 20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text('Counter: $_count ', style: TextStyle(fontSize: 30.0)),
      ),
    );
  }
}
  • 展示這個元件,然後外部觸發它
VoidCallback? callback;

// display
SmartDialog.show(
  alignmentTemp: Alignment.center,
  widget: OtherTrick(
    onUpdate: (VoidCallback onInvoke) => callback = onInvoke,
  ),
);

await Future.delayed(Duration(milliseconds: 500));

// handler
SmartDialog.show(
  alignmentTemp: Alignment.centerRight,
  maskColorTemp: Colors.transparent,
  widget: Container(
    height: double.infinity,
    width: 150,
    color: Colors.white,
    alignment: Alignment.center,
    child: ElevatedButton(
      child: Text('add'),
      onPressed: () => callback?.call(),
    ),
  ),
);
  • 來看下效果

trick

最後

相關地址
哎,人總是在不斷的迷茫中前行。。。

夢

相關文章