首页 > 解决方案 > 照片无法立即在图库中显示

问题描述

照片不会立即在图库中显示。我拍张照片。在文件夹 Pictures 中创建的文件。

Future<void> _funMakePhoto() async {

  //if controller is initialized
  //если контроллер инициализирован
  if (!_cameraController.value.isInitialized) {
   return null;
  }

  //if photo does not making now
  //если фотография в данный момент не делается
  if (_cameraController.value.isTakingPicture) {
   return null;
  }

  //path and name of the file
  //путь + название файла
  var now = DateTime.now();
  String directory = await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_PICTURES);
  String file = '${now.year}-${now.month}-${now.day}-${now.hour}${now.minute}${now.second}.jpg';
  //соединение пути
  String pathAll = join(directory, file);

  //make photo on this path
  //делаем снимок по этому пути
  XFile xFile = await _cameraController.takePicture();

  setState(() {
   _str = xFile.path;
  });

  //read a file how an array of the bytes
  //считываем файл, как массив байтов
  var bytes = await File(xFile.path).readAsBytes();

  //create a file on this path
  //создаем файл по указанному пути
  File f = File(pathAll);

  //write in this file the array of the bytes
  //записываем в этот файл массив байтов
  await f.writeAsBytes(bytes);

  //delete a file from a folder
  //удаляем файл из папки /data/data/com.example.f1/cache/CAP-515873726.jpg
  File(xFile.path).delete();

 }

但在图库中,该文件不会立即显示。这个怎么解决?

进一步的所有代码。

主要.dart

import 'dart:io';

import 'package:camera/camera.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';

List<CameraDescription> cameras = [];
String _str = '';

Future<void> main() async {
 WidgetsFlutterBinding.ensureInitialized();
 cameras = await availableCameras();
 runApp(MyApp());
}

class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   debugShowCheckedModeBanner: false,
   title: 'Name App',
   theme: ThemeData(
    primarySwatch: Colors.blue,
   ),
   home: Scaffold(
    appBar: AppBar(
     title: Text('Name Page'),
    ),
    body: MyHomePage(),
   ),
  );
 }
}

class MyHomePage extends StatefulWidget {
 @override
 _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

 CameraController _cameraController;
 int _idCameras = 0;

 @override
 void initState() {
  super.initState();
  _funSetCameraController(cameras[0]);

 }

 @override
 void dispose() {
  super.dispose();
  _cameraController.dispose();

 }

 void _f1() {
  setState(() {

  });
 }

 Future<void> _funSetCameraController(CameraDescription cameraDescription) async {

  if (_cameraController != null) {
   await _cameraController.dispose();
  }

  _cameraController = CameraController(
   cameraDescription,
   ResolutionPreset.max
  );

  // If the controller is updated then update the UI.
  _cameraController.addListener(() {
   if (mounted) setState(() {});
  });

  try {
   await _cameraController.initialize();
  } on CameraException catch (e) {
   print(e);
  }

  if (mounted) {
   setState(() {});
  }

 }

 //method switch cameras
 //метод переключает камеры
 void _funChoiceCameras(int id) {
  setState(() {
   switch(id) {
    case 0:
     _funSetCameraController(cameras[0]);
     _idCameras = 0;
     break;
    case 1:
     _funSetCameraController(cameras[1]);
     _idCameras = 1;
     break;
   }
  });
 }

 Future<void> _funMakePhoto() async {

  //if controller is initialized
  //если контроллер инициализирован
  if (!_cameraController.value.isInitialized) {
   return null;
  }

  //if photo does not making now
  //если фотография в данный момент не делается
  if (_cameraController.value.isTakingPicture) {
   return null;
  }

  //path and name of the file
  //путь + название файла
  var now = DateTime.now();
  String directory = await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_PICTURES);
  String file = '${now.year}-${now.month}-${now.day}-${now.hour}${now.minute}${now.second}.jpg';
  //соединение пути
  String pathAll = join(directory, file);

  //make photo on this path
  //делаем снимок по этому пути
  XFile xFile = await _cameraController.takePicture();

  setState(() {
   _str = xFile.path;
  });

  //read a file how an array of the bytes
  //считываем файл, как массив байтов
  var bytes = await File(xFile.path).readAsBytes();

  //create a file on this path
  //создаем файл по указанному пути
  File f = File(pathAll);

  //write in this file the array of the bytes
  //записываем в этот файл массив байтов
  await f.writeAsBytes(bytes);

  //delete a file from a folder
  //удаляем файл из папки /data/data/com.example.f1/cache/CAP-515873726.jpg
  File(xFile.path).delete();

 }

 @override
 Widget build(BuildContext context) {

  if(!_cameraController.value.isInitialized) {
   return Container();
  }

  return Column(
   children: [

    Align(
     alignment: Alignment.center,
     child: Text(
      _str,
      style: TextStyle(
       fontSize: 26.0,
       color: Colors.pink
      ),
     ),
    ),

    Expanded(
     flex: 1,
     child: Container(
      width: MediaQuery.of(context).size.width,
      child: CameraPreview(_cameraController),
     ),
    ),
    Row(
     mainAxisAlignment: MainAxisAlignment.spaceAround,
     children: [
      TextButton(
       onPressed: () { _funChoiceCameras(0); },
       child: Container(
        width: 75.0,
        height: 50.0,
        decoration: BoxDecoration(
         border: Border.all(
          width: 2.0,
          color: (_idCameras == 0) ? Colors.pink : Colors.grey,
         ),
         borderRadius: BorderRadius.all(
          Radius.circular(10.0)
         ),
        ),
        alignment: Alignment.center,
        child: Icon(
         Icons.camera_rear_rounded,
         size: 38.0,
         color: (_idCameras == 0) ? Colors.pink : Colors.grey,
        ),
       ),
      ),

      TextButton(
       onPressed: () { _funChoiceCameras(1); },
       child: Container(
        width: 75.0,
        height: 50.0,
        decoration: BoxDecoration(
         border: Border.all(
          width: 2.0,
          color: (_idCameras == 1) ? Colors.pink : Colors.grey,
         ),
         borderRadius: BorderRadius.all(
          Radius.circular(10.0)
         ),
        ),
        alignment: Alignment.center,
        child: Icon(
         Icons.camera_front_rounded,
         size: 38.0,
         color: (_idCameras == 1) ? Colors.pink : Colors.grey,
        ),
       ),
      ),

      TextButton(
       onPressed: () { _funMakePhoto(); },
       child: Container(
        width: 75.0,
        height: 50.0,
        decoration: BoxDecoration(
         border: Border.all(
          width: 2.0,
          color: Colors.deepPurple,
         ),
         borderRadius: BorderRadius.all(
          Radius.circular(10.0)
         ),
        ),
        alignment: Alignment.center,
        child: Icon(
         Icons.photo_camera_rounded,
         size: 38.0,
         color: Colors.deepPurple,
        ),
       ),
      ),
     ],
    ),
   ],
  );
 }

}

标签: flutterdart

解决方案


推荐阅读