flutter 图像裁剪器在GetxController中不工作

up9lanfz  于 2023-01-09  发布在  Flutter
关注(0)|答案(2)|浏览(127)

以下是我尝试在中实现的代码。我猜未来的方法pickImage会出现问题。我正在使用GetxController扩展该类。该方法预期使用图像裁剪器来拾取和裁剪所选图像,然后如果裁剪成功,则将裁剪后的图像设置为imageFile变量。

import 'dart:io';

import 'package:pamoja/app/data/const.dart';
import 'package:pamoja/app/data/firebase/firebase_functions.dart';
import 'package:pamoja/app/data/global_widgets/indicator.dart';
import 'package:pamoja/app/models/advert_model.dart';
import 'package:pamoja/app/modules/my_adverts/controllers/my_adverts_controller.dart';
import 'package:pamoja/app/routes/app_pages.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';

class UploadBlogController extends GetxController {
  TextEditingController title = TextEditingController();
  TextEditingController description = TextEditingController();
  TextEditingController location = TextEditingController();
  TextEditingController category = TextEditingController();
  TextEditingController price = TextEditingController();
  TextEditingController phone = TextEditingController();
  final FirebaseFunctions _functions = FirebaseFunctions();
  File? imageFile;

  Future<void> pickImage() async {
    try {
      ImagePicker _picker = ImagePicker();

      await _picker.pickImage(source: ImageSource.gallery).then((value) async {
        if (value != null) {
          File? croppedFile = await ImageCropper().cropImage(
            sourcePath: value.path,
            aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
            compressQuality: 100,
            maxWidth: 700,
            maxHeight: 700,
            // saveCircleCroppedImage: true,
          );

          if (croppedFile != null) {
            imageFile = croppedFile;
            update();
          }
        }
      });
    } catch (e) {
      showAlert("$e");
    }
  }

  void createBlog() async {
    if (title.text.isNotEmpty && description.text.isNotEmpty) {
      if (imageFile != null && imageFile != "") {
        Indicator.showLoading();

        await _functions
            .uploadBlog(
          title.text,
          description.text,
          imageFile!,
          price.text,
          category.text,
          location.text,
          phone.text,
        )
            .then((value) {
          Indicator.closeLoading();
          showAlert("Your advert created sucessfully");
          // Get.back();
          Get.toNamed(Routes.HOME);
        });
      } else {
        showAlert("Image is required");
      }
    } else {
      showAlert("All fields are required");
    }
  }

  void editBlog(BlogsModel model) async {
    Indicator.showLoading();

    if (title.text.isNotEmpty && description.text.isNotEmpty) {
      if (imageFile == null) {
        Map<String, dynamic> map = {
          'title': title.text,
          'description': description.text,
        };

        await _functions.editBlog(model.id, map).then((value) {
          Get.toNamed(Routes.HOME);
          showAlert("Your ads Updated Sucessfully");
        });
      } else {
        String imageUrl = await _functions.uploadImage(imageFile!);

        Map<String, dynamic> map = {
          'title': title.text,
          'description': description.text,
          'img': imageUrl,
        };

        await _functions.editBlog(model.id, map).then((value) {
          Get.toNamed(Routes.HOME);
          showAlert("Your Advert Updated Sucessfully");
        });
      }
    } else {
      showAlert("All fields are required");
    }

    Indicator.closeLoading();
    updateData();
  }

  void updateData() {
    Get.back();
    Get.toNamed(Routes.HOME);
    if (Get.isRegistered<MyBlogsController>()) {
      final controller = Get.find<MyBlogsController>();

      controller.myBlogs = [];
      Indicator.showLoading();
      controller.getMyBlogData();
    }
  }
}
jxct1oxe

jxct1oxe1#

这我创建了reusable single-tone代码为我的整个应用程序选择媒体imagevideo。您可以尝试或修改根据您的要求。

// Dart imports:
import 'dart:io';

// Package imports:
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

// Project imports:
import 'package:app/utils/export_utils.dart';

class MediaPicker {
  MediaPicker._();

  static const supportedImageFormates = [".jpeg", ".png"];
  static const supportedVedioFormates = [".mp4"];
  static final picker = ImagePicker();

  // Single image / video selection
  static Future<File?> pickMedia({
    required ImageSource source,
    bool isVideo = false,
    bool isEditing = false,
  }) async {
    try {
      final pickMedia = !isVideo
          ? await picker.pickImage(source: source)
          : await picker.pickVideo(source: source);

      if (pickMedia != null) {
        return isEditing
            ? await editImage(file: File(pickMedia.path))
            : File(pickMedia.path);
      } else {
        return null;
      }
    } catch (ex) {
      "Pick Media error: $ex".printLog();
      return null;
    }
  }

  static Future<File> editImage({required File file}) async {
    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: file.path,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: 'Cropper',
          toolbarColor: ColorConst.themePrimaryColor,
          toolbarWidgetColor: ColorConst.white,
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: false,
        ),
        IOSUiSettings(
          title: 'Cropper',
        ),
      ],
    );

    if (croppedFile != null) {
      return File(croppedFile.path);
    } else {
      return file;
    }
  }
}
    • 用法**使用Futureasync方法在按钮点击上添加呼叫方法

x一个一个一个一个x一个一个二个x
确保为两个平台添加了以下权限

    • Andriod-安卓清单. xml**
<uses-permission android:name="android.permission.CAMERA"/> //Camera
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> // Read Storage
    • iOS流道/信息列表**
<key>NSCameraUsageDescription</key>
    <string>App require camera permission to update profile pic</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>App require gallery permission to update profile pic</string>

image_cropper中提到的 Package ,在<applcaiton>标签下的AndroidManifest.xml中添加以下代码

<activity
  android:name="com.yalantis.ucrop.UCropActivity"
  android:screenOrientation="portrait"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
rsaldnfx

rsaldnfx2#

我按照你的指示修改了它,它起作用了。下面是一个修改示例

Future<void> pickImage() async {
try {
  ImagePicker _picker = ImagePicker();

  await _picker.pickImage(source: ImageSource.gallery).then((value) async {
    if (value != null) {
      imageFile = File(value.path);
      showAlert(imageFile.toString());
      editImage(imageFile: imageFile);

      // cropImage(imageFile);
    } else {
      showAlert("No image selected");
    }
  });
} catch (e) {
  showAlert("$e");
}}
Future<void> editImage({required File? imageFile}) async {
final File? croppedFile = await ImageCropper().cropImage(
  sourcePath: imageFile!.path,
  androidUiSettings: AndroidUiSettings(
    toolbarTitle: 'Advert Image',
    toolbarColor: Colors.green.shade400,
    toolbarWidgetColor: Colors.white,
    initAspectRatio: CropAspectRatioPreset.original,
    lockAspectRatio: false,
  ),
  iosUiSettings: IOSUiSettings(
    title: 'Cropper',
  ),
);

if (croppedFile != null) {
  imageFile = File(croppedFile.path);
  update();
} else {
  // update();
}}

相关问题