Flutter图片选择插件image_picker_plus的使用

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

Flutter图片选择插件 image_picker_plus 的使用

image_picker_plus 是一个功能强大的Flutter插件,解决了传统图片选择器(如 image_picker)的许多问题,包括多主题、多语言支持以及自定义UI等。本文将详细介绍如何安装和使用该插件,并提供完整的示例代码。

插件特性

  • 支持多主题和多语言。
  • 可以自定义图片库的显示界面。
  • 支持裁剪选定的图片。
  • 支持同时选择图片和视频。
  • 提供了更现代的用户界面设计。

安装步骤

1. 添加依赖

首先,在项目的 pubspec.yaml 文件中添加 image_picker_plus 依赖:

dependencies:
  image_picker_plus: ^latest_version

请确保将 ^latest_version 替换为最新版本号。

2. 安装依赖

在终端运行以下命令来安装依赖:

flutter pub get

3. 权限配置

iOS 配置

ios/Runner/Info.plist 文件中添加以下权限声明:

<key>NSPhotoLibraryUsageDescription</key>
<string>your usage description here</string>
<key>NSCameraUsageDescription</key>
<string>your usage description here</string>
<key>NSMicrophoneUsageDescription</key>
<string>your usage description here</string>

Android 配置

android/app/build.gradle 文件中设置最低SDK版本:

compileSdkVersion 33
minSdkVersion 21

AndroidManifest.xml 文件中添加以下权限:

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

使用示例

下面是一个完整的示例代码,展示了如何使用 image_picker_plus 插件来选择图片和视频。

示例代码

import 'dart:io';
import 'package:image_picker_plus/image_picker_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom gallery display',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            normal1(context),
            normal2(context),
            normal3(context),
            preview1(context),
            preview2(context),
            preview3(context),
            camera1(context),
            camera2(context),
          ],
        ),
      ),
    );
  }

  ElevatedButton normal1(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickImage(source: ImageSource.gallery);
        if (details != null) await displayDetails(details);
      },
      child: const Text("Normal 1"),
    );
  }

  ElevatedButton normal2(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickVideo(
          source: ImageSource.both,
          multiVideos: true,
          galleryDisplaySettings: GalleryDisplaySettings(gridDelegate: _sliverGrid2Delegate()),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Normal 2"),
    );
  }

  ElevatedButton normal3(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickBoth(
          source: ImageSource.both,
          multiSelection: true,
          galleryDisplaySettings: GalleryDisplaySettings(
            appTheme: AppTheme(focusColor: Colors.white, primaryColor: Colors.black),
            gridDelegate: _sliverGrid3Delegate(),
          ),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Normal 3"),
    );
  }

  ElevatedButton preview1(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickBoth(
          source: ImageSource.gallery,
          multiSelection: true,
          galleryDisplaySettings: GalleryDisplaySettings(
            tabsTexts: _tabsTexts(),
            appTheme: AppTheme(focusColor: Colors.white, primaryColor: Colors.black),
            cropImage: true,
            showImagePreview: true,
          ),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Preview 1"),
    );
  }

  ElevatedButton preview2(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickVideo(
          source: ImageSource.both,
          multiVideos: true,
          galleryDisplaySettings: GalleryDisplaySettings(cropImage: true, showImagePreview: true),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Preview 2"),
    );
  }

  SliverGridDelegateWithFixedCrossAxisCount _sliverGrid3Delegate() {
    return const SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 3,
      crossAxisSpacing: 1.7,
      mainAxisSpacing: 1.5,
      childAspectRatio: .5,
    );
  }

  SliverGridDelegateWithFixedCrossAxisCount _sliverGrid2Delegate() {
    return const SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 2,
      crossAxisSpacing: 17,
      mainAxisSpacing: 17,
      childAspectRatio: 1,
    );
  }

  TabsTexts _tabsTexts() {
    return TabsTexts(
      videoText: "فيديو",
      galleryText: "المعرض",
      deletingText: "حذف",
      clearImagesText: "الغاء الصور المحدده",
      limitingText: "اقصي حد للصور هو 10",
    );
  }

  ElevatedButton preview3(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickBoth(
          source: ImageSource.both,
          multiSelection: true,
          galleryDisplaySettings: GalleryDisplaySettings(cropImage: true, showImagePreview: true),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Preview 3"),
    );
  }

  ElevatedButton camera1(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickBoth(
          source: ImageSource.camera,
          multiSelection: true,
          galleryDisplaySettings: GalleryDisplaySettings(cropImage: true),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("Camera 1"),
    );
  }

  ElevatedButton camera2(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        SelectedImagesDetails? details = await picker.pickVideo(
          source: ImageSource.camera,
          multiVideos: true,
          galleryDisplaySettings: GalleryDisplaySettings(appTheme: AppTheme(focusColor: Colors.white, primaryColor: Colors.black)),
        );
        if (details != null) await displayDetails(details);
      },
      child: const Text("camera 2"),
    );
  }

  Future<void> displayDetails(SelectedImagesDetails details) async {
    await Navigator.of(context).push(
      CupertinoPageRoute(
        builder: (context) {
          return DisplayImages(
            selectedBytes: details.selectedFiles,
            details: details,
            aspectRatio: details.aspectRatio,
          );
        },
      ),
    );
  }
}

class DisplayImages extends StatefulWidget {
  final List<SelectedByte> selectedBytes;
  final double aspectRatio;
  final SelectedImagesDetails details;

  const DisplayImages({
    Key? key,
    required this.details,
    required this.selectedBytes,
    required this.aspectRatio,
  }) : super(key: key);

  [@override](/user/override)
  State<DisplayImages> createState() => _DisplayImagesState();
}

class _DisplayImagesState extends State<DisplayImages> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Selected images/videos')),
      body: ListView.builder(
        itemBuilder: (context, index) {
          SelectedByte selectedByte = widget.selectedBytes[index];
          if (!selectedByte.isThatImage) {
            return _DisplayVideo(selectedByte: selectedByte);
          } else {
            return SizedBox(
              width: double.infinity,
              child: Image.file(selectedByte.selectedFile),
            );
          }
        },
        itemCount: widget.selectedBytes.length,
      ),
    );
  }
}

class _DisplayVideo extends StatefulWidget {
  final SelectedByte selectedByte;

  const _DisplayVideo({Key? key, required this.selectedByte}) : super(key: key);

  [@override](/user/override)
  State<_DisplayVideo> createState() => _DisplayVideoState();
}

class _DisplayVideoState extends State<_DisplayVideo> {
  late VideoPlayerController controller;
  late Future<void> initializeVideoPlayerFuture;

  [@override](/user/override)
  void initState() {
    super.initState();
    File file = widget.selectedByte.selectedFile;
    controller = VideoPlayerController.file(file);
    initializeVideoPlayerFuture = controller.initialize();
    controller.setLooping(true);
  }

  [@override](/user/override)
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: initializeVideoPlayerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Stack(
            alignment: Alignment.center,
            children: [
              AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: VideoPlayer(controller),
              ),
              Align(
                alignment: Alignment.center,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      if (controller.value.isPlaying) {
                        controller.pause();
                      } else {
                        controller.play();
                      }
                    });
                  },
                  child: Icon(
                    controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                    size: 45,
                  ),
                ),
              )
            ],
          );
        } else {
          return const Center(
            child: CircularProgressIndicator(strokeWidth: 1),
          );
        }
      },
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用image_picker_plus插件来选择图片的详细代码示例。image_picker_plus是一个流行的Flutter插件,用于从设备相册或相机中选择图片。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  image_picker_plus: ^4.0.0  # 确保使用最新版本,版本号根据实际情况调整

然后运行flutter pub get来安装依赖。

2. 配置权限

对于Android,你需要在android/app/src/main/AndroidManifest.xml中添加必要的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

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

    <application
        ... >
        ...
    </application>
</manifest>

对于iOS,你需要在ios/Runner/Info.plist中添加以下权限请求:

<key>NSCameraUsageDescription</key>
<string>Need camera access to capture images</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Need photo library access to select images</string>
<key>NSMicrophoneUsageDescription</key>
<string>Need microphone access to capture videos</string>

3. 实现图片选择功能

接下来,在你的Flutter项目中实现图片选择功能。以下是一个简单的示例:

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

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

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

class ImagePickerScreen extends StatefulWidget {
  @override
  _ImagePickerScreenState createState() => _ImagePickerScreenState();
}

class _ImagePickerScreenState extends State<ImagePickerScreen> {
  late final ImagePickerPlus imagePicker = ImagePickerPlus();
  late File? pickedImage;

  Future<void> pickImage(ImageSource source) async {
    final XFile? image = await imagePicker.pickImage(source: source);

    if (image != null) {
      setState(() {
        pickedImage = File(image.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Plus Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            pickedImage == null
                ? Text('No image selected.')
                : Image.file(pickedImage!),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => pickImage(ImageSource.camera),
              child: Text('Pick from camera'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => pickImage(ImageSource.gallery),
              child: Text('Pick from gallery'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 运行项目

确保你的开发环境配置正确,然后运行flutter run来启动你的Flutter应用。现在你应该能够看到一个简单的界面,点击按钮可以从相机或相册中选择图片。

这个示例展示了如何使用image_picker_plus插件来选择图片,并将其显示在屏幕上。你可以根据需要进一步扩展这个示例,比如添加错误处理、裁剪图片等功能。

回到顶部