在Flutter中,可以使用ListView.builder
或GridView.builder
來加載大量圖片。
首先,確保你已經導入了flutter_staggered_grid_view
插件:
dependencies:
flutter_staggered_grid_view: ^0.4.0
接下來,你可以使用以下代碼來加載大量圖片:
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),
),
);
}
}
這個例子中使用StaggeredGridView.countBuilder
來創建一個GridView
,其中itemCount
表示總共的圖片數量,itemBuilder
用于構建每個圖片的Widget
,staggeredTileBuilder
用于指定每個圖片的大小。
注意:在實際開發中,建議使用cached_network_image
插件來加載網絡圖片,這樣可以提高圖片加載的性能和體驗。
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),
),
);
}
}
這樣就可以高效地加載和顯示大量的圖片了。