Flutter多图选择插件multi_image_picker_plus的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter多图选择插件multi_image_picker_plus的使用

multi_image_picker_plus 是一个允许在iOS和Android上显示多图选择器的Flutter插件。它基于 FishBunBSImagePicker,并提供了一系列强大的功能。

关键特性

  • 选择多张图片
  • 原生性能
  • 按相册排序的照片
  • 网格视图中的拍照选项
  • 限制用户可以选择的最大图片数量
  • 可自定义的UI和本地化
  • 缩略图支持
  • 指定原始图片或缩略图的质量
  • 读取图片元数据

安装配置

iOS

<project root>/ios/Runner/Info.plist 文件中添加以下键值:

<key>NSPhotoLibraryUsageDescription</key>
<string>我们需要访问您的照片库以选择图片。</string>

Android

<project root>/android/app/src/main/AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

<!-- For Android 13 and above -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE"
    android:maxSdkVersion="32" />

使用示例

以下是完整的示例代码,展示如何使用 multi_image_picker_plus 插件来选择多张图片:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:multi_image_picker_plus/multi_image_picker_plus.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MaterialApp(
      home: const MyApp(),
      theme: ThemeData(
        colorSchemeSeed: Colors.deepOrange,
        brightness: Brightness.dark,
      ),
    ));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Asset> images = <Asset>[];
  String _error = 'No Error Detected';
  bool _permissionReady = false;

  static const List<Permission> _permissions = [
    Permission.storage,
    Permission.camera
  ];

  Future<void> _requestPermissions() async {
    final Map<Permission, PermissionStatus> statues =
        await _permissions.request();
    if (statues.values.every((status) => status.isGranted)) {
      _permissionReady = true;
    }
  }

  Future<void> _loadAssets() async {
    if (!_permissionReady) {
      openAppSettings();
      return;
    }

    final ColorScheme colorScheme = Theme.of(context).colorScheme;

    List<Asset> resultList = <Asset>[];
    String error = 'No Error Detected';

    try {
      resultList = await MultiImagePicker.pickImages(
        selectedAssets: images,
        iosOptions: IOSOptions(
          doneButton: UIBarButtonItem(title: 'Confirm', tintColor: colorScheme.primary),
          cancelButton: UIBarButtonItem(title: 'Cancel', tintColor: colorScheme.primary),
          albumButtonColor: colorScheme.primary,
        ),
        androidOptions: AndroidOptions(
          actionBarColor: colorScheme.surface,
          actionBarTitleColor: colorScheme.onSurface,
          statusBarColor: colorScheme.surface,
          actionBarTitle: "Select Photo",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: colorScheme.primary,
          hasCameraInPickerPage: true,
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    if (!mounted) return;

    setState(() {
      images = resultList;
      _error = error;
    });
  }

  @override
  void initState() {
    _requestPermissions();
    super.initState();
  }

  Widget _buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Column(
        children: <Widget>[
          Center(child: Text('Error: $_error')),
          ElevatedButton(
            onPressed: _loadAssets,
            child: const Text("Pick images"),
          ),
          Expanded(
            child: _buildGridView(),
          )
        ],
      ),
    );
  }
}

注意事项

  • 在使用插件之前,请确保已正确配置权限。
  • 对于iOS设备,如果不需要获取完整元数据,可以不请求 NSPhotoLibraryUsageDescription 权限。
  • 在Android 13及以上版本中,请注意媒体权限的变化。

通过上述步骤,您可以轻松集成 multi_image_picker_plus 插件到您的Flutter项目中,并实现多图选择功能。希望这个指南对您有所帮助!


更多关于Flutter多图选择插件multi_image_picker_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter多图选择插件multi_image_picker_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用multi_image_picker_plus插件来选择多张图片的示例代码。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加multi_image_picker_plus依赖:

dependencies:
  flutter:
    sdk: flutter
  multi_image_picker_plus: ^4.0.13  # 请检查最新版本号

2. 导入插件

在你的Dart文件中导入插件:

import 'package:multi_image_picker_plus/multi_image_picker_plus.dart';

3. 请求权限

在Android和iOS上,选择图片通常需要访问存储的权限。确保在AndroidManifest.xmlInfo.plist中声明这些权限。

Android:

AndroidManifest.xml中添加:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

iOS:

Info.plist中添加:

<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library</string>
<key>NSCameraUsageDescription</key>
<string>We need access to use your camera</string>

4. 使用插件选择图片

在你的Flutter页面中,你可以使用以下代码来选择多张图片:

import 'package:flutter/material.dart';
import 'package:multi_image_picker_plus/multi_image_picker_plus.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Asset> images = [];

  Future<void> pickImages() async {
    try {
      final List<Asset> resultList = await MultiImagePickerPlus.pickImages(
        maxImages: 9,  // 最大选择图片的数量
        enableCamera: true,  // 是否启用相机
        selectionAssets: images,  // 已经选择的图片
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),  // iOS的选项
        materialOptions: MaterialOptions(
          actionBarColor: "#ffffff",
          actionBarTitle: "选择图片",
          allViewTitle: "全部图片",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );

      // 更新状态
      setState(() {
        images = resultList;
      });
    } catch (e) {
      e.printStackTrace();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Multi Image Picker Plus 示例"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: pickImages,
            child: Text("选择图片"),
          ),
          SizedBox(height: 20),
          GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 4,
              mainAxisSpacing: 4,
            ),
            itemCount: images.length,
            itemBuilder: (BuildContext context, int index) {
              Asset asset = images[index];

              // 获取图片路径
              ImageProvider image = MultiImagePickerPlus.getImageProvider(
                asset: asset,
                width: 100,
                height: 100,
              );

              return Card(
                child: Image(imageProvider: image),
              );
            },
          ),
        ],
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml中添加multi_image_picker_plus
  2. 权限请求:在AndroidManifest.xmlInfo.plist中添加必要的权限。
  3. 选择图片:使用MultiImagePickerPlus.pickImages方法来选择图片,并更新状态。
  4. 显示图片:使用GridView.builder来显示选择的图片。

这段代码展示了如何在Flutter中使用multi_image_picker_plus插件来选择并显示多张图片。希望这对你有所帮助!

回到顶部