Flutter相机功能插件sparrow_camera的使用

Guide for Instalation

Android

app/build.gradle文件中添加以下内容:

minSdkVersion 21
IOS

info.plist文件中添加以下内容:

	<key>NSCameraUsageDescription</key>
    <string>Can I use the camera please?</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>Can I use the mic please?</string>
Flutter

pubspec.yaml文件中添加以下依赖:

sparrow_camera: current_version

How to use

sparrow_camera是一个Widget,可以在任何地方使用。以下是示例代码。

Example 01
return Scaffold(
      body: SparrowCamera(
        onFile: (file) => print(file); // 文件回调
        maxCount: 6, // 最大照片数量
        maxRecordingTime: 20, // 录制视频的最大时长(秒)
        onFile: (file) {
            print("filePath=${file.path}"); // 文件路径回调
          },
        onMessage: (message) {
            print("message=$message"); // 消息回调
          },
        onPreview: (file) {
            print("file=${file?.path}"); // 预览回调
          },
      )
);
Example 02
return Scaffold(
      body: SparrowCamera(
        onFile: (file) => print(file); // 文件回调
        maxCount: 6, // 最大照片数量
        maxRecordingTime: 20, // 录制视频的最大时长(秒)
        onFile: (file) {
            print("filePath=${file.path}"); // 文件路径回调
          },
        onMessage: (message) {
            print("message=$message"); // 消息回调
          },
        onPreview: (file) {
            print("file=${file?.path}"); // 预览回调
          },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
           Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => SparrowCamera(
                  onFile: (file) {
                    photos.add(file);
                    // 当拍摄照片时应该关闭相机
                    Navigator.pop(context);
                    setState(() {});
                  },
                )))
        },
        child: Icon(Icons.camera_alt), // 相机图标
      ),
);

Roadmap 1.0

Feature Progress
Zoom
Flash
CameraSide select
nullsafety support
Add Exposure control
Add Easy Mode Video
Add Gallery

Contributing

欢迎提交Pull Request。对于重大更改,请先打开一个问题讨论你想要进行的更改。
请确保更新适当的测试。

License

MIT


示例代码

以下是完整的示例代码,展示如何使用sparrow_camera插件:

example/lib/main.dart

import 'dart:io';

import 'package:flutter/material.dart';

import 'package:sparrow_camera/sparrow_camera.dart';

void main() {
  // cameraMain();
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        // 使用SparrowCamera作为主体
        body: SparrowCamera(
          enableAudio: true, // 是否启用音频
          enableZoom: false, // 是否启用缩放
          maxCount: 6, // 最大照片数量
          maxRecordingTime: 20, // 录制视频的最大时长(秒)
          onFile: (file) {
            print("filePath=${file.path}"); // 文件路径回调
          },
          onMessage: (message) {
            print("message=$message"); // 消息回调
          },
          onPreview: (file) {
            print("file=${file?.path}"); // 预览回调
          },
        ),
      ),
    );
  }
}

更多关于Flutter相机功能插件sparrow_camera的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter相机功能插件sparrow_camera的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


sparrow_camera 是一个 Flutter 插件,用于在 Flutter 应用中集成相机功能。它提供了简单的 API,使得开发者可以轻松地在应用中实现拍照、录像等功能。以下是 sparrow_camera 的基本使用步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 sparrow_camera 依赖:

dependencies:
  flutter:
    sdk: flutter
  sparrow_camera: ^1.0.0  # 请使用最新版本

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

2. 导入包

在需要使用相机功能的 Dart 文件中导入 sparrow_camera 包:

import 'package:sparrow_camera/sparrow_camera.dart';

3. 初始化相机

在应用的适当位置初始化相机。通常可以在 initState 方法中进行初始化:

SparrowCameraController? _cameraController;

[@override](/user/override)
void initState() {
  super.initState();
  _cameraController = SparrowCameraController();
}

4. 显示相机预览

使用 SparrowCameraPreview 组件来显示相机预览:

[@override](/user/override)
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Sparrow Camera Example'),
    ),
    body: Center(
      child: SparrowCameraPreview(
        controller: _cameraController!,
      ),
    ),
  );
}

5. 拍照

你可以使用 takePicture 方法来拍照:

void _takePicture() async {
  final image = await _cameraController!.takePicture();
  if (image != null) {
    // 处理拍摄的照片
    print('Picture taken: ${image.path}');
  }
}

6. 录像

你可以使用 startRecordingstopRecording 方法来录像:

void _startRecording() async {
  await _cameraController!.startRecording();
}

void _stopRecording() async {
  final video = await _cameraController!.stopRecording();
  if (video != null) {
    // 处理录制的视频
    print('Video recorded: ${video.path}');
  }
}

7. 释放资源

在页面销毁时,记得释放相机资源:

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

8. 处理权限

在使用相机功能之前,确保你已经处理了相机和存储权限。你可以使用 permission_handler 插件来请求权限:

import 'package:permission_handler/permission_handler.dart';

void _checkPermissions() async {
  var cameraStatus = await Permission.camera.status;
  var storageStatus = await Permission.storage.status;

  if (!cameraStatus.isGranted) {
    await Permission.camera.request();
  }
  if (!storageStatus.isGranted) {
    await Permission.storage.request();
  }
}

9. 完整示例

以下是一个完整的示例,展示了如何使用 sparrow_camera 插件实现拍照和录像功能:

import 'package:flutter/material.dart';
import 'package:sparrow_camera/sparrow_camera.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CameraExample(),
    );
  }
}

class CameraExample extends StatefulWidget {
  [@override](/user/override)
  _CameraExampleState createState() => _CameraExampleState();
}

class _CameraExampleState extends State<CameraExample> {
  SparrowCameraController? _cameraController;

  [@override](/user/override)
  void initState() {
    super.initState();
    _cameraController = SparrowCameraController();
    _checkPermissions();
  }

  void _checkPermissions() async {
    var cameraStatus = await Permission.camera.status;
    var storageStatus = await Permission.storage.status;

    if (!cameraStatus.isGranted) {
      await Permission.camera.request();
    }
    if (!storageStatus.isGranted) {
      await Permission.storage.request();
    }
  }

  void _takePicture() async {
    final image = await _cameraController!.takePicture();
    if (image != null) {
      print('Picture taken: ${image.path}');
    }
  }

  void _startRecording() async {
    await _cameraController!.startRecording();
  }

  void _stopRecording() async {
    final video = await _cameraController!.stopRecording();
    if (video != null) {
      print('Video recorded: ${video.path}');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sparrow Camera Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: SparrowCameraPreview(
                controller: _cameraController!,
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _takePicture,
                  child: Text('Take Picture'),
                ),
                ElevatedButton(
                  onPressed: _startRecording,
                  child: Text('Start Recording'),
                ),
                ElevatedButton(
                  onPressed: _stopRecording,
                  child: Text('Stop Recording'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    _cameraController?.dispose();
    super.dispose();
  }
}
回到顶部