用Flutter實現毛玻璃效果的代碼如下:
import 'dart:ui'; import 'package:flutter/material.dart'; class FrostedGlassDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: [ ConstrainedBox( constraints: BoxConstraints.expand(), child: Image.network('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhuafans.dbankcloud.com%2Fpic%2F2017%2F01%2F25%2F195116eebdd5aa2fdaebff832280a391_IMG_20170125_153017.jpg%3Fmode%3Ddownload&refer=http%3A%2F%2Fhuafans.dbankcloud.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620875132&t=ea50802522897aad43419379eea3267a'), ), Center( child: ClipRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 3.0,sigmaY: 3.0), child: Opacity( opacity: 0.5, child: Container( width: 500.0, height: 800.0, decoration: BoxDecoration( color: Colors.grey.shade200 ), child: Center( child:Text( 'Cat', style: Theme.of(context).textTheme.display3 ) ), ), ), ), ), ) ], ), ); } }
其中,要點為:
1.用Stack組件包含圖片和毛玻璃兩個組件。
2.圖片組件外層加了約束盒子組件,從而增加約束,實現全屏擴展圖片。
3.使用剪切矩形組件包含毛玻璃組件,並居中。
4.使用背景過濾器和透明組件實現毛玻璃的具體效果。
5.在容器組件中設置毛玻璃的寬高,並使用盒子裝飾器組件修飾容器,設置顏色,也可以不使用盒子裝飾器直接設置顏色。
如:
child: Container( width: 500.0, height: 800.0, color: Colors.grey.shade200, child: Center( child:Text( 'Cat', style: Theme.of(context).textTheme.display3 ) ), ),
6.文字組件應居中,否則會在頁面的左上角。
7.使用
Theme.of(context).textTheme.display3
設置字體的樣式,也可以使用TextStyle組件進行設置。
毛玻璃效果如下: