Flutter本地图片轮播插件local_image_pager的使用
Flutter本地图片轮播插件local_image_pager的使用
插件介绍
local_image_pager
是一个用于显示设备本地图片的插件,并且支持分页功能。
特性
- 获取设备中所有图片的数量。
- 通过分页方式获取本地图片。
开始使用
在你的 pubspec.yaml
文件中添加以下依赖:
dependencies:
...
local_image_pager:
在你的库文件中添加以下导入:
import 'package:local_image_pager/local_image_pager.dart';
示例代码
下面是一个完整的示例代码,展示了如何使用 local_image_pager
插件来实现本地图片轮播效果。
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:local_image_pager/local_image_pager.dart';
/// An example app for local_image_pager plugin.
void main() {
runApp(MaterialApp(
title: 'Local images pager example',
home: LocalImagePagerDemo(),
));
}
class LocalImagePagerDemo extends StatefulWidget {
[@override](/user/override)
_LocalImagePagerDemoState createState() => _LocalImagePagerDemoState();
}
/// How many images you want to fetch per 1 page.
const per_load_count = 30;
/// GridView's crossAxisCount.
const cross_axis_count = 4;
/// GridView's mainAxisSpacing, crossAxisSpacing, and padding. (Used to calculate the thumbnail size.)
const double spacing = 5;
/// GridView v padding. (Used to calculate the thumbnail size.)
const double horizontal_padding = 10;
class _LocalImagePagerDemoState extends State<LocalImagePagerDemo> {
/// You need to ask [Permission.storage].
final _permissions = [Permission.storage];
final _completers = <Completer>[];
[@override](/user/override)
void initState() {
super.initState();
}
Future<bool> get _initPermissions async {
final statuses = await _permissions.request();
for (final status in statuses) {
if (status != PermissionStatus.granted) {
print('_initPermissions:not granted');
return false;
}
}
print('_initPermissions:granted');
return true;
}
[@override](/user/override)
Widget build(BuildContext context) {
// Calculate the thumbnail's size first to improve performance.
final itemSize = ((MediaQuery.of(context).size.width -
spacing * (cross_axis_count - 1) - horizontal_padding * 2) /
cross_axis_count);
final cacheSize = (itemSize * 1.5).round();
final pager = LocalImagePager();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Local images pager'),
),
body: Column(children: [
const SizedBox(height: 100,
child: Center(child: Text('Your own widget here.', style: TextStyle(fontSize: 20, color: Colors.blue, fontWeight: FontWeight.bold),))),
Expanded(child: FutureBuilder(
future: _initPermissions,
builder: ( context, snapshot {
if (snapshot.hasData) {
if (snapshot.data) {
return FutureBuilder(
future: LocalImagePager.totalNumber,
builder: ( context, snapshot {
if (snapshot.hasData) {
final count = snapshot.data;
if (count == 0 {
return const Center(
child: Text('No images'),
);
} else {
return GridView.builder(
padding: const EdgeInsets.symmetric(horizontal: horizontal_padding),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cross_axis_count,
mainAxisSpacing: spacing,
crossAxisSpacing: spacing,
),
itemCount: count,
itemBuilder: ( context, index =>
_itemBuilder(pager, count, index, itemSize, cacheSize));
}
} else if (snapshot.hasError {
return Center(
child: Text(
snapshot.error.toString(),
style: const TextStyle(color: Colors.red),
),
);
} else {
return const Center(
child: CircularProgressIndicator());
}
},
);
} else {
return Column(
children: [
const Text(
'Permission not granted, try again.',
style: const TextStyle(color: Colors.red),
),
FlatButton(
onPressed: () {
setState(() {});
},
child: const Text('OK'))
],
);
}
} else if ( snapshot.hasError {
return Center(
child: Text(
snapshot.error.toString(),
style: const TextStyle(color: Colors.red),
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),)
])),
);
}
Widget _itemBuilder(
LocalImagePager paginate, int totalNumber, int index, double itemSize, int cacheSize) {
_load(paginate, totalNumber, index);
return FutureBuilder(
future: _completers[index].future,
builder: ( context, snapshot {
if (snapshot.hasData {
return Image.file(
File(snapshot.data),
fit: BoxFit.cover,
height: itemSize,
cacheHeight: cacheSize,
);
} else if ( snapshot.hasError {
print('_itemBuilder:error:${snapshot.error.toString()}');
return const SizedBox(
width: 0,
height: 0,
);
} else {
return const SizedBox(
width: 0,
height: 0,
);
}
},
);
}
_load(LocalImagePager paginate, int count, int itemIndex) async {
if (itemIndex % per_load_count != 0) {
return;
}
if (itemIndex >= _completers.length {
final toLoad = min(count - itemIndex, per_load_count);
if toLoad > 0 {
_completers.addAll(List.generate(toLoad, (index) {
return Completer();
}));
try {
final images = await paginate.latestImages(itemIndex, itemIndex + toLoad - 1);
image.asMap().forEach((index, item) {
_completers[itemIndex + index].complete(item);
});
} catch (e {
print('_load:error:${e.toString()}');
_completers
.sublist(itemIndex, itemIndex + toLoad)
.forEach((completer) {
completer.completeError(e);
});
}
}
}
}
}
更多关于Flutter本地图片轮播插件local_image_pager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter本地图片轮播插件local_image_pager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用local_image_pager
插件来实现本地图片轮播的代码示例。local_image_pager
是一个用于在Flutter应用中显示本地图片轮播的插件。
首先,确保你已经将local_image_pager
添加到你的pubspec.yaml
文件中:
dependencies:
flutter:
sdk: flutter
local_image_pager: ^x.y.z # 请将x.y.z替换为实际的版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter项目中,你可以按照以下方式使用local_image_pager
:
import 'package:flutter/material.dart';
import 'package:local_image_pager/local_image_pager.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Local Image Pager Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LocalImagePagerScreen(),
);
}
}
class LocalImagePagerScreen extends StatelessWidget {
// 本地图片资源列表,确保这些图片在你的assets目录下
final List<String> imageAssets = [
'assets/images/image1.jpg',
'assets/images/image2.jpg',
'assets/images/image3.jpg',
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Local Image Pager Demo'),
),
body: Center(
child: LocalImagePager(
imageList: imageAssets,
looping: true, // 是否循环播放
autoPlay: true, // 是否自动播放
autoPlayInterval: 3000, // 自动播放间隔时间(毫秒)
onPageChanged: (index) {
// 页面改变时的回调
print('Current Page Index: $index');
},
onDoubleTap: () {
// 双击时的回调
print('Image double tapped!');
},
indicatorColor: Colors.white, // 指示器颜色
indicatorSize: 10.0, // 指示器大小
indicatorActiveColor: Colors.blue, // 指示器激活时的颜色
indicatorSpace: 5.0, // 指示器之间的间距
pageController: PageController(), // PageController用于控制页面切换
),
),
);
}
}
在这个示例中:
- 我们定义了一个包含本地图片资源路径的列表
imageAssets
。 - 在
LocalImagePagerScreen
中,我们使用LocalImagePager
组件来显示这些图片。 LocalImagePager
组件接收多个参数,包括:imageList
:图片资源路径列表。looping
:是否循环播放。autoPlay
:是否自动播放。autoPlayInterval
:自动播放间隔时间(毫秒)。onPageChanged
:页面改变时的回调。onDoubleTap
:双击时的回调。indicatorColor
:指示器颜色。indicatorSize
:指示器大小。indicatorActiveColor
:指示器激活时的颜色。indicatorSpace
:指示器之间的间距。pageController
:用于控制页面切换的PageController
。
确保你的图片资源已经放在assets/images/
目录下,并在pubspec.yaml
文件中正确声明了这些资源:
flutter:
assets:
- assets/images/image1.jpg
- assets/images/image2.jpg
- assets/images/image3.jpg
这样,你就可以在Flutter应用中实现本地图片的轮播效果了。