阅读量:8
在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), ), ); } }
这样就可以高效地加载和显示大量的图片了。