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

增加了不少實(shí)用的功能,最新更新介紹,請(qǐng)查看:https://juejin.cn/post/7026150456673959943

前言

Q:你一生中聞過(guò)最臭的東西,是什么?

A:我那早已腐爛的夢(mèng)。

兄弟萌!??!我又來(lái)了!

這次,我能自信的對(duì)大家說(shuō):我終于給大家?guī)Я艘粋€(gè),能真正幫助大家解決諸多坑比場(chǎng)景的pub包!

將之前的flutter_smart_dialog,在保持api穩(wěn)定的基礎(chǔ)上,進(jìn)行了各種抓頭重構(gòu),解決了一系列問(wèn)題

現(xiàn)在,我終于可以說(shuō):它現(xiàn)在是一個(gè)簡(jiǎn)潔,強(qiáng)大,侵入性極低的pub包!

關(guān)于侵入性問(wèn)題

  • 之前為了解決返回關(guān)閉彈窗,使用了一個(gè)很不優(yōu)雅的解決方法,導(dǎo)致侵入性有點(diǎn)高
  • 這真是讓我如坐針氈,如芒刺背,如鯁在喉,這個(gè)問(wèn)題終于搞定了!

同時(shí),我在pub包內(nèi)部設(shè)計(jì)了一個(gè)彈窗棧,能自動(dòng)移除棧頂彈窗,也可以定點(diǎn)移除棧內(nèi)標(biāo)記的彈窗。

存在的問(wèn)題

使用系統(tǒng)彈窗存在一系列坑,來(lái)和各位探討探討

  • 必須傳BuildContext

    • 在一些場(chǎng)景必須多做一些傳參工作,蛋痛但不難的問(wèn)題
  • loading彈窗

    • 使用系統(tǒng)彈窗做loading彈窗,肯定遇到過(guò)這個(gè)坑比問(wèn)題
      • loading封裝在網(wǎng)絡(luò)庫(kù)里面:請(qǐng)求網(wǎng)絡(luò)時(shí)加載loading,手賤按了返回按鈕,關(guān)閉了loading
      • 然后請(qǐng)求結(jié)束后發(fā)現(xiàn):特么我的頁(yè)面怎么被關(guān)了?。?!
    • 系統(tǒng)彈窗就是一個(gè)路由頁(yè)面,關(guān)閉系統(tǒng)就是用pop方法,這很容易誤關(guān)正常頁(yè)面
      • 當(dāng)然肯定有解決辦法,路由監(jiān)聽(tīng)的地方處理,此處就不細(xì)表了
  • 某頁(yè)面彈出了多個(gè)系統(tǒng)Dialog,很難定點(diǎn)關(guān)閉某個(gè)非棧頂彈窗

    • 蛋蛋,這是路由入棧出棧機(jī)制導(dǎo)致的,理解的同時(shí)也一樣要吐槽
  • 系統(tǒng)Dialog,點(diǎn)擊事件無(wú)法穿透暗色背景

    • 這個(gè)坑比問(wèn)題,我是真沒(méi)轍

相關(guān)思考

上面列舉了一些比較常見(jiàn)的問(wèn)題,最嚴(yán)重的問(wèn)題,應(yīng)該就是loading的問(wèn)題

  • loading是個(gè)超高頻使用的彈窗,關(guān)閉loading彈窗的方法,同時(shí)也能關(guān)閉正常使用的頁(yè)面,本身就是一個(gè)隱患

  • 穿透dialog遮罩是個(gè)非常重要的功能,基于該功能,能夠在實(shí)際業(yè)務(wù)中,實(shí)現(xiàn)很多騷操作

  • 既然在系統(tǒng)dialog難以解決各種痛點(diǎn),加上系統(tǒng)dialog也是基于overlay去實(shí)現(xiàn)的,這樣的話(huà),我們也可以去高度定制overlay!

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

快速上手

初始化

dependencies:
  flutter_smart_dialog: ^3.2.0
  • 接入方式更加簡(jiǎn)潔??
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(),
    );
  }
}

極簡(jiǎn)使用

  • toast使用??
SmartDialog.showToast('test toast');

[圖片上傳失敗...(image-f31b20-1641222341623)]

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

[圖片上傳失敗...(image-66991d-1641222341623)]

  • 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);

[圖片上傳失敗...(image-34c4d7-1641222341623)]

OK,上面展示了,只需要極少的代碼,就可以調(diào)用相應(yīng)的功能

當(dāng)然,內(nèi)部還有不少地方做了特殊優(yōu)化,接下來(lái),我會(huì)詳細(xì)的向大家描述下

你可能會(huì)有的疑問(wèn)

初始化框架的時(shí)候,相比以前,居然讓大家多寫(xiě)了一個(gè)參數(shù),內(nèi)心十分愧疚??

關(guān)閉頁(yè)面本質(zhì)上是一個(gè)比較復(fù)雜的情況,涉及到

  • 物理返回按鍵
  • AppBar的back按鈕
  • 手動(dòng)pop

為了監(jiān)控這些情況,不得已增加了一個(gè)路由監(jiān)控參數(shù)

實(shí)體返回鍵

對(duì)返回按鈕的監(jiān)控,是非常重要的,基本能覆蓋大多數(shù)情況

initBack

pop路由

雖然對(duì)返回按鈕的監(jiān)控能覆蓋大多數(shù)場(chǎng)景,但是一些手動(dòng)pop的場(chǎng)景就需要新增參數(shù)監(jiān)控

  • 不加FlutterSmartDialog.observer
    • 如果打開(kāi)了穿透參數(shù)(就可以和彈窗后的頁(yè)面交互),然后手動(dòng)關(guān)閉頁(yè)面
    • 就會(huì)出現(xiàn)這種很尷尬的情況
initPopOne
  • 加了FlutterSmartDialog.observer,就能比較合理的處理了
    • 當(dāng)然,這里的過(guò)渡動(dòng)畫(huà),也提供了參數(shù)控制是否開(kāi)啟 ??

[圖片上傳失敗...(image-1b78e7-1641222341623)]

關(guān)于 FlutterSmartDialog.init()

本方法不會(huì)占用你的builder參數(shù),init內(nèi)部回調(diào)出來(lái)了builder,你可以大膽放心的繼續(xù)套

  • 例如:繼續(xù)套Bloc全局實(shí)例??
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!,
  );
}

超實(shí)用的參數(shù):backDismiss

  • 這個(gè)參數(shù)是默認(rèn)設(shè)置為true,返回的時(shí)候會(huì)默認(rèn)關(guān)閉彈窗;如果設(shè)置為false,將不會(huì)關(guān)閉頁(yè)面
    • 這樣就可以十分輕松的做一個(gè)緊急彈窗,禁止用戶(hù)的下一步操作
  • 我們來(lái)看一個(gè)場(chǎng)景:假定某開(kāi)源作者決定棄坑軟件,不允許用戶(hù)再使用該軟件的彈窗
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('鄙人思考了三秒鐘,懷著\'沉重\'的心情,決定棄坑本開(kāi)源軟件'),
          Text('本人今后的生活是富婆和遠(yuǎn)方,已無(wú)\'精力\' 再維護(hù)本開(kāi)源軟件了'),
          Text('各位叼毛,有緣江湖再見(jiàn)!'),
          // button (only method of close the dialog)
          ElevatedButton(
            onPressed: () => SmartDialog.dismiss(),
            child: Text('再會(huì)!'),
          )
        ],
      ),
    ),
  ),
);
hardClose

從上面的效果圖可以看出來(lái)

  • 點(diǎn)擊遮罩,無(wú)法關(guān)閉彈窗
  • 點(diǎn)擊返回按鈕無(wú)法關(guān)閉彈窗
  • 只能點(diǎn)我們自己的按鈕,才能關(guān)閉彈窗,點(diǎn)擊按鈕的邏輯可以直接寫(xiě)成關(guān)閉app之類(lèi)

只需要倆個(gè)簡(jiǎn)單的參數(shù)設(shè)置,就能實(shí)現(xiàn)這樣一個(gè)很棒的應(yīng)急彈窗

設(shè)置全局參數(shù)

SmartDialog的全局參數(shù)都有著一個(gè)比較合理的默認(rèn)值

為了應(yīng)付多變的場(chǎng)景,你可以修改符合你自己要求的全局參數(shù)

  • 設(shè)置符合你的要求的數(shù)據(jù),放在app入口就行初始化就行
    • 注:如果沒(méi)有特殊要求,可以不用初始化全局參數(shù)(內(nèi)部皆有默認(rèn)值)
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
  ..debounce = false
  ..debounceTime = Duration(milliseconds: 300);
  • 代碼的注釋寫(xiě)的很完善,某個(gè)參數(shù)不明白的,點(diǎn)進(jìn)去看看就行了
image-20211102223129866

Attach篇

這是一個(gè)很重要的功能,本來(lái)早就想加進(jìn)去了,但是比較忙,一直擱置了;元旦(2022.1.1)開(kāi)了頭,就花了一些時(shí)間,完成了這個(gè)功能和相關(guān)demo

定位

定位目標(biāo)widget的坐標(biāo),這個(gè)做起來(lái)并不難;但是必須要拿到我們傳入的自定義widget大小,這樣才能將自定義widget疊放到一個(gè)比較合適的位置(通過(guò)一些計(jì)算,獲取中心點(diǎn))

  • 實(shí)際上Flutter提供一個(gè)非常合適的組件CustomSingleChildLayout,這個(gè)組件還提供偏移坐標(biāo)功能,按理來(lái)說(shuō)非常合適
  • 但是,CustomSingleChildLayoutSizeTransition 動(dòng)畫(huà)控件,存在占位面積沖突,只能使用AnimatedOpacity漸隱動(dòng)畫(huà)
  • 位移動(dòng)畫(huà)不能用,這我沒(méi)法忍,拋棄 CustomSingleChildLayout;使用了各種騷操作,終于拿到自定義widget的大小,比較完美實(shí)現(xiàn)了效果

定位dialog,使用showAttach方法,參數(shù)注釋寫(xiě)的相當(dāng)詳細(xì),不明白用法的看看注釋就行了

強(qiáng)大的定位功能

  • 必須傳目標(biāo)widget的BuildContext,需要通過(guò)它計(jì)算出目標(biāo)widget的坐標(biāo)和大小
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),
        ),
      ],
    ),
  ),
);

[圖片上傳失敗...(image-730d52-1641222341623)]

動(dòng)畫(huà)效果和show方法幾乎是一致的,為了這個(gè)一致的體驗(yàn),內(nèi)部做了相當(dāng)多的針對(duì)性?xún)?yōu)化

自定義坐標(biāo)點(diǎn)

  • 大多數(shù)情況基本都是使用targetContext
SmartDialog.showAttach(
  targetContext: context,
  widget: Container(width: 100, height: 100, color: Colors.red),
);
  • 當(dāng)然還有少數(shù)情況,需要使用自定義坐標(biāo),此處也提供target參數(shù):設(shè)置了target參數(shù),targetContext將自動(dòng)失效
    • targetContext 是十分常見(jiàn)到場(chǎng)景,所以,這邊設(shè)置為必傳參數(shù),但是你可以給它設(shè)置為null
SmartDialog.showAttach(
  targetContext: null,
  target: Offset(100, 100);,
  widget: Container(width: 100, height: 100, color: Colors.red),
);
  • 看來(lái)下自定義坐標(biāo)點(diǎn)效果
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

  • 實(shí)際上模仿DropdownButton挺不容易的
    • 首先要計(jì)算DropdownButton控件的位置,在其位置上顯示點(diǎn)擊后的折疊控件
    • 需要處理DropdownButton之外區(qū)域的點(diǎn)擊事件(點(diǎn)擊區(qū)域外關(guān)閉DropdownButton)
    • 還需要監(jiān)聽(tīng)返回事件,手動(dòng)pop路由事件;是這類(lèi)事件的,需要關(guān)閉DropdownButton
  • 這玩意要自定義,挺讓人頭大的;但是,現(xiàn)在你可以使用SmartDialog.showAttach 輕松模仿一個(gè),上述需要注意的事項(xiàng)都幫你處理好了
//模仿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

高亮

這次把遮罩特定區(qū)域高亮的功能加上了,這是一個(gè)非常實(shí)用的功能!

  • 你只需要設(shè)置highlight參數(shù)即可
    • 定義高亮的區(qū)域,他必須是個(gè)不通透的Widget,例如是Contaienr,必須設(shè)置一個(gè)顏色(色值無(wú)要求)
      • 使用各種奇形怪狀的圖片也行,這樣就能顯示各種復(fù)雜圖形的高亮區(qū)域
    • highlight類(lèi)型是Positioned,你可以在屏幕上定位任何需要高亮的區(qū)域
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),
);

實(shí)際的業(yè)務(wù)場(chǎng)景

  • 這邊舉倆個(gè)常見(jiàn)的例子,代碼有一點(diǎn)點(diǎn)多,就不貼了,感興趣的請(qǐng)查看:flutter_use
attachBusiness

上面?zhèn)z個(gè)業(yè)務(wù)場(chǎng)景非常常見(jiàn),有時(shí)候,我們需要目標(biāo)widget上面或下面或特定的區(qū)域,不被遮罩覆蓋

自己去做的話(huà),可以做出來(lái),但是會(huì)很麻煩;現(xiàn)在你可以使用showAttach中的highlight參數(shù)輕松實(shí)現(xiàn)這個(gè)需求

引導(dǎo)操作

引導(dǎo)操作在app上還是非常常見(jiàn)的,需要指定區(qū)域高亮,然后介紹其功能

  • 使用showAttach中的highlight參數(shù),也可以輕松實(shí)現(xiàn)這個(gè)需求,來(lái)看下效果
    • 代碼同樣有一點(diǎn)點(diǎn)多,感興趣的請(qǐng)查看:flutter_use

[圖片上傳失敗...(image-df0879-1641222341623)]

Dialog篇

花里胡哨

彈窗從不同位置彈出,動(dòng)畫(huà)是有區(qū)別的

image-20211031221419600
  • alignmentTemp:該參數(shù)設(shè)置不同,動(dòng)畫(huà)效果會(huì)有所區(qū)別
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,
);

[圖片上傳失敗...(image-aa397e-1641222341623)]

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

dialog棧

  • 這是一個(gè)強(qiáng)大且實(shí)用的功能!
    • 可以很輕松的定點(diǎn)關(guān)閉某個(gè)彈窗
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'),
      ),
    ]),
  ),
);

[圖片上傳失敗...(image-a91961-1641222341623)]

Loading篇

避坑指南

  • 開(kāi)啟loading后,可以使用以下方式關(guān)閉
    • SmartDialog.dismiss():可以關(guān)閉loading和dialog
    • status設(shè)置為SmartStatus.loading:僅僅關(guān)閉loading
// easy close
SmartDialog.dismiss();
// exact close
SmartDialog.dismiss(status: SmartStatus.loading);
  • 一般來(lái)說(shuō),loading彈窗是封裝在網(wǎng)絡(luò)庫(kù)里面的,隨著請(qǐng)求狀態(tài)的自動(dòng)開(kāi)啟和關(guān)閉
    • 基于這種場(chǎng)景,我建議:使用dismiss時(shí),加上status參數(shù),將其設(shè)置為:SmartStatus.loading
  • 坑比場(chǎng)景
    • 網(wǎng)絡(luò)請(qǐng)求加載的時(shí)候,loading也隨之打開(kāi),這時(shí)很容易誤觸返回按鈕,關(guān)閉loading
    • 當(dāng)網(wǎng)絡(luò)請(qǐng)求結(jié)束時(shí),會(huì)自動(dòng)調(diào)用dismiss方法
    • 因?yàn)閘oading已被關(guān)閉,假設(shè)此時(shí)頁(yè)面又有SmartDialog的彈窗,未設(shè)置status的dismiss就會(huì)關(guān)閉SmartDialog的彈窗
    • 當(dāng)然,這種情況很容易解決,封裝進(jìn)網(wǎng)絡(luò)庫(kù)的loading,使用:SmartDialog.dismiss(status: SmartStatus.loading); 關(guān)閉就行了
  • status參數(shù),是為了精確關(guān)閉對(duì)應(yīng)類(lèi)型彈窗而設(shè)計(jì)的參數(shù),在一些特殊場(chǎng)景能起到巨大的作用
    • 如果大家理解這個(gè)參數(shù)的含義,那對(duì)于何時(shí)添加status參數(shù),必能胸有成竹

參數(shù)說(shuō)明

參數(shù)在注釋里面寫(xiě)的十分詳細(xì),就不贅述了,來(lái)看看效果

image-20211031215728656
  • maskWidgetTemp:強(qiáng)大的遮罩自定義功能??,發(fā)揮你的腦洞吧。。。
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);

[圖片上傳失敗...(image-d72af8-1641222341623)]

  • 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:動(dòng)畫(huà)效果切換
SmartDialog.showLoading(isLoadingTemp: false);
loadingFour
  • isPenetrateTemp:交互事件可以穿透遮罩,這是個(gè)十分有用的功能,對(duì)于一些特殊的需求場(chǎng)景十分關(guān)鍵
SmartDialog.showLoading(isPenetrateTemp: true);
loadingFive

自定義Loading

使用showLoading可以輕松的自定義出強(qiáng)大的loading彈窗;鄙人腦洞有限,就簡(jiǎn)單演示下

自定義一個(gè)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();
  }
}

來(lái)看看效果

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

[圖片上傳失敗...(image-6b6bb7-1641222341623)]

  • 效果二
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的特殊性

嚴(yán)格來(lái)說(shuō),toast是一個(gè)非常特殊的彈窗,我覺(jué)得理應(yīng)具備下述的特征

toast消息理應(yīng)一個(gè)個(gè)展示,后續(xù)消息不應(yīng)該頂?shù)羟懊娴膖oast

  • 這是一個(gè)坑點(diǎn),如果框架內(nèi)部不做處理,很容易出現(xiàn)后面toast會(huì)直接頂?shù)羟懊鎡oast的情況
    • 當(dāng)然,內(nèi)部提供了type參數(shù),你可以選擇你想要的顯示邏輯
toastOne

展示在頁(yè)面最上層,不應(yīng)該被一些彈窗之類(lèi)遮擋

  • 可以發(fā)現(xiàn)loading和dialog的遮罩等布局,均未遮擋toast信息

[圖片上傳失敗...(image-4cb1b-1641222341623)]

對(duì)鍵盤(pán)遮擋情況做處理

  • 鍵盤(pán)這玩意有點(diǎn)坑,會(huì)直接遮擋所有布局,只能曲線(xiàn)救國(guó)
    • 在這里做了一個(gè)特殊處理,當(dāng)喚起鍵盤(pán)的時(shí)候,toast自己會(huì)動(dòng)態(tài)的調(diào)整自己和屏幕底部的距離
    • 這樣就能起到一個(gè),鍵盤(pán)不會(huì)遮擋toast的效果
toastSmart

自定義Toast

參數(shù)說(shuō)明

toast的一些參數(shù)并未向外暴露,僅僅暴露了msg和alignment

  • 例如:toast字體大小,字體顏色,toast的背景色等等之類(lèi),都沒(méi)提供參數(shù)
    • 一是覺(jué)得提供了這些參數(shù),會(huì)讓整體參數(shù)輸入變的非常多,亂花漸入迷人眼
    • 二是覺(jué)得就算我提供了很多參數(shù),也不一定會(huì)滿(mǎn)足那些奇奇怪怪的審美和需求
  • 基于上述的考慮,我直接提供了大量的底層參數(shù)
    • 你可以隨心所欲的定制toast
      • 注意喔,不僅僅可以定制toast,例如:成功提示,失敗提示,警告提示等等
      • Toast做了很多的優(yōu)化,type參數(shù),讓你能擁有多種顯示邏輯,發(fā)揮你的想象力吧
    • 注意:使用了widget參數(shù),msgalignment參數(shù)會(huì)失效
image-20211217142656380

調(diào)整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

更強(qiáng)大的自定義toast

  • 首先,整一個(gè)自定義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

騷氣的小技巧

有一種場(chǎng)景比較蛋筒

  • 我們使用StatefulWidget封裝了一個(gè)小組件
  • 在某個(gè)特殊的情況,我們需要在這個(gè)組件外部,去觸發(fā)這個(gè)組件內(nèi)部的一個(gè)方法
  • 對(duì)于這種場(chǎng)景,有不少實(shí)現(xiàn)方法,但是弄起來(lái)可能有點(diǎn)麻煩

這里提供一個(gè)簡(jiǎn)單的小思路,可以非常輕松的觸發(fā),組件內(nèi)部的某個(gè)方法

  • 建立一個(gè)小組件
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)),
      ),
    );
  }
}
  • 展示這個(gè)組件,然后外部觸發(fā)它
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(),
    ),
  ),
);
  • 來(lái)看下效果

[圖片上傳失敗...(image-7e006e-1641222341623)]

最后

相關(guān)地址

哎,人總是在不斷的迷茫中前行。。。

夢(mèng)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容