Рассмотрите фрагменты кода ниже:Тряпка/Дротик
Код: Выделить всё
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Native Camera Test',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Native Camera Test'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
static const platform = MethodChannel('samples.flutter.dev/camera');
Future openCamera() async {
// Check and request camera permission
bool isCameraGranted = await _requestPermission(Permission.camera);
if (isCameraGranted) {
try {
final String imagePath = await platform.invokeMethod('openCamera');
print('Image Path: $imagePath');
} on PlatformException catch (e) {
print("Failed to open camera: '${e.message}'.");
}
} else {
print('Permission denied');
}
}
Future _requestPermission(Permission permission) async {
// Check if the permission is already granted
if (await permission.isGranted) {
return true;
}
// Request permission if not already granted
var status = await permission.request();
return status == PermissionStatus.granted;
}
Future imagePath(String imagePath) async {
print("Hit from Kotlin");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
Код: Выделить всё
package com.example.nativecameratest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.IOException
import java.util.*
import io.flutter.embedding.engine.FlutterEngine
import androidx.annotation.NonNull
class MainActivity: FlutterActivity(){
private val CHANNEL = "samples.flutter.dev/camera"
private val REQUEST_IMAGE_CAPTURE = 1
private lateinit var currentPhotoPath: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set up the method channel on the binaryMessenger
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "openCamera") {
dispatchTakePictureIntent(result)
} else {
result.notImplemented()
}
}
}
private fun dispatchTakePictureIntent(result: MethodChannel.Result) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(packageManager) != null) {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
result.error("FILE_CREATION_FAILED", "Error occurred while creating the file", null)
null
}
if (photoFile != null) {
val photoURI = FileProvider.getUriForFile(this, "com.example.nativecameratest.fileprovider", photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
private fun createImageFile(): File {
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${System.currentTimeMillis()}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
Log.d("MainActivity", "Image file created at: $currentPhotoPath")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
// Return the file path to Flutter
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).invokeMethod("imagePath", currentPhotoPath)
}
}
}
Итак, вот чего я собираюсь достичь:
- Откройте полнофункциональную камеру, как показано ниже:

[*]Возможность сделать несколько фотографий перед закрытием камеры (аналогично съемке фотографий с помощью WhatsApp). Этого можно достичь, если иметь доступ ко всей камере. Если № 1 невозможен, как я могу это сделать?
[*]Отправьте фотографии (пути к фотографиям) обратно во Flutter/Dart< /p>
Подробнее здесь: https://stackoverflow.com/questions/789 ... red-camera
Мобильная версия