圖片緩存 原生平台 iOS的話是Swift Kingfisher
我們一樣先再次封裝一層,construct給imageUrl圖片網址,
還有圖片正下載讀取時候的placeholderPath(佔位圖路徑),
而裡面的imagUrlPrefix則是,
一般情況會有固定的網域 + API給的是圖片的路徑 兩者組合起來.
再來裡面有placeholder(下載中),imageBuilder(下載完成顯示), errorWidget(下載錯誤).
placeholder, errorWidget這兩者 可以顯示成同一個,或依需求去替換.
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class ImageCached extends StatefulWidget {
const ImageCached(
{Key? key, required this.imageUrl, this.placeholderPath = ''})
: super(key: key);
final String imageUrl;
final String placeholderPath;
@override
_ImageCachedState createState() => _ImageCachedState();
}
class _ImageCachedState extends State<ImageCached> {
String placeholderPath = '';
static const imagUrlPrefix = 'https://www.solivatech.com';
String imageUrl = '';
@override
void initState() {
super.initState();
placeholderPath = widget.placeholderPath;
imageUrl = imagUrlPrefix + widget.imageUrl;
}
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
placeholder: (context, url) {
return (placeholderPath.isEmpty)
? Icon(Icons.photo_library)
: Image.asset(placeholderPath, fit: BoxFit.contain);
},
imageUrl: imageUrl,
imageBuilder: (context, imageProvider) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.contain,
),
),
);
},
errorWidget: (context, url, error) {
return (placeholderPath.isEmpty)
? Icon(Icons.image_not_supported_outlined)
: Image.asset(placeholderPath, fit: BoxFit.contain);
},
);
}
}
實際使用
class CachedImagePage extends GetView<CachedImagePageController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('CachedImagePage')),
body: SafeArea(
child: SizedBox.expand(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: ImageCached(
imageUrl:
'/assets/uploads/media-uploader/flutter-app-development-company1623499975.jpg'),
),
],
),
),
),
);
}
}
效果如下(第一次打開的時候會先有個Icon 佔位圖,回上一頁再次點開, 圖片直接顯示)
下一篇將為大家介紹 qr_flutter(產) & qr_code_scanner(掃)