在Flutter中,可以使用ListView.builder
或GridView.builder
來(lái)加載大量圖片。
首先,確保你已經(jīng)導(dǎo)入了flutter_staggered_grid_view
插件:
dependencies:
flutter_staggered_grid_view: ^0.4.0
接下來(lái),你可以使用以下代碼來(lái)加載大量圖片:
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
class ImageList extends StatelessWidget {
final List<String> imageUrls = [
'url1',
'url2',
// 添加更多的圖片url
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image List'),
),
body: StaggeredGridView.countBuilder(
crossAxisCount: 2,
itemCount: imageUrls.length,
itemBuilder: (BuildContext context, int index) => Image.network(imageUrls[index]),
staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
),
);
}
}
這個(gè)例子中使用StaggeredGridView.countBuilder
來(lái)創(chuàng)建一個(gè)GridView
,其中itemCount
表示總共的圖片數(shù)量,itemBuilder
用于構(gòu)建每個(gè)圖片的Widget
,staggeredTileBuilder
用于指定每個(gè)圖片的大小。
注意:在實(shí)際開(kāi)發(fā)中,建議使用cached_network_image
插件來(lái)加載網(wǎng)絡(luò)圖片,這樣可以提高圖片加載的性能和體驗(yàn)。
dependencies:
cached_network_image: ^2.5.0
使用示例代碼:
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
class ImageList extends StatelessWidget {
final List<String> imageUrls = [
'url1',
'url2',
// 添加更多的圖片url
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image List'),
),
body: StaggeredGridView.countBuilder(
crossAxisCount: 2,
itemCount: imageUrls.length,
itemBuilder: (BuildContext context, int index) => CachedNetworkImage(
imageUrl: imageUrls[index],
fit: BoxFit.cover,
),
staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
),
);
}
}
這樣就可以高效地加載和顯示大量的圖片了。