使用Flutter从Cloud firestore加载图像的速度非常慢



我正试图从cloud firestore中检索图像数据,但当我这样做时,图像加载需要非常长的时间,有时根本不会出现。

以下是我检索图像的方法:

final firestore = FirebaseFirestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;
Future<String> getProfilePic() async {
final CollectionReference users = firestore.collection('UserNames');
final String uid = auth.currentUser.uid;
final result = await users.doc(uid).get();
return result.data()['profilepic'];
}

并显示:

FutureBuilder(
future: getProfilePic(),
builder: (_, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Palette.lightGreen,
));
}
return ClipOval(
child: Image.network(snapshot.data,
height: 100, width: 100, fit: BoxFit.fill),
);
},
),

您需要缓存图像。

得到这个包裹:

cached_network_image 2.3.3

并更改此代码:

ClipOval(
child: Image.network(snapshot.data,
height: 100, width: 100, fit: BoxFit.fill),
);
},
),

到此代码

ClipOval(
child: CachedNetworkImage(
height: 100,
width: 100,
fit: BoxFit.fill,
imageUrl:
snapshot.data,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),

pubspec.yaml中添加以下包。

cached_network_image: ^2.3.3

在显示图像的地方尝试此代码:

Material(
child: snapshot.data != null
? CachedNetworkImage(
placeholder: (context, url) => Container(
child: CircularProgressIndicator(
strokeWidth: 1.0,
valueColor:
AlwaysStoppedAnimation<Color>(themeColor),
),
width: 50.0,
height: 50.0,
padding: EdgeInsets.all(15.0),
),
imageUrl: snapshot.data,
width: 50.0,
height: 50.0,
fit: BoxFit.cover,
)
: Icon(
Icons.account_circle,
size: 50.0,
color: greyColor,
),
borderRadius: BorderRadius.all(Radius.circular(25.0)),
clipBehavior: Clip.hardEdge,
)

最新更新