miguelpruivo / flutter_file_picker

File picker plugin for Flutter, compatible with mobile (iOS & Android), Web, Desktop (Mac, Linux, Windows) platforms with Flutter Go support.
MIT License
1.34k stars 674 forks source link

App crash on file pick in android #286

Closed maxbhoria closed 4 years ago

maxbhoria commented 4 years ago

Hi i am not able to pick file app get crashed when i select any file.

I an using android device.

Issue printed in console

E/AndroidRuntime( 1459): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference E/AndroidRuntime( 1459): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:92) E/AndroidRuntime( 1459): at java.lang.Thread.run(Thread.java:919)

maxbhoria commented 4 years ago

@miguelpruivo I tried with simulator app still crashing.

miguelpruivo commented 4 years ago

@maxbhoria I don't know what else to tell you, other than completely get rid of pub cache on your machine and rebuild again. As you can see, I can't replicate on my end. Would you mind trying with the plugin's example app on simulator and record it with the logs if possible?

Thanks.

maxbhoria commented 4 years ago

@maxbhoria I don't know what else to tell you, other than completely get rid of pub cache on your machine and rebuild again. As you can see, I can't replicate on my end. Would you mind trying with the plugin's example app on simulator and record it with the logs if possible?

Thanks.

i already tried with your example it was working fine in my device also and also i replace my android folder with you example android folder than it works for me. I am not getting what exactly happening.

miguelpruivo commented 4 years ago

@maxbhoria follow this steps and see if it helps.

maxbhoria commented 4 years ago

ok i will try these

Iamstanlee commented 4 years ago

@maxbhoria found any solution?, I'm facing same issue and i've tested on two different devices

maxbhoria commented 4 years ago

Hello I commented this code in plugin FilePickerDeligate.java, will it create any further issue in my application?

// if (type.equals("dir") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); // }

you can do this if you do not want to pick folder

Thanks

skiryuk commented 4 years ago

I have the same problem. Any idea?

v1.11.0+2

Syncing files to device MI 8 Lite... W/Gralloc3( 3235): mapper 3.x is not supported W/Looper ( 3235): Slow Looper main: doFrame is 349ms late because of 2 msg, msg 1 took 359ms (seq=10 late=38ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver) I/ru.beeline.dol( 3235): ProcessProfilingInfo new_methods=490 is saved saved_to_disk=1 resolve_classes_delay=8000 D/FilePickerDelegate( 3235): Selected type / I/Timeline( 3235): Timeline: Activity_launch_request time:243034211 D/FlutterView( 3235): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@71e4910 I/FilePickerDelegate( 3235): [SingleFilePick] File URI:content://com.android.providers.media.documents/document/image%3A108732 E/FilePickerUtils( 3235): Getting for API 19 or abovecontent://com.android.providers.media.documents/document/image%3A108732 E/AndroidRuntime( 3235): FATAL EXCEPTION: Thread-4 E/AndroidRuntime( 3235): Process: ru.beeline.dol, PID: 3235 E/AndroidRuntime( 3235): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference E/AndroidRuntime( 3235): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106) E/AndroidRuntime( 3235): at java.lang.Thread.run(Thread.java:919) E/FilePickerUtils( 3235): Document URI E/FilePickerUtils( 3235): Media Document URI I/FilePickerUtils( 3235): Image Media Document URI E/MQSEventManagerDelegate( 3235): failed to get MQSService. I/FilePickerDelegate( 3235): Absolute file path:/storage/emulated/0/VK/Downloads/wkl7KXuYpNA.jpg I/Process ( 3235): Sending signal. PID: 3235 SIG: 9

maxbhoria commented 4 years ago

I have the same problem. Any idea?

v1.11.0+2

Syncing files to device MI 8 Lite... W/Gralloc3( 3235): mapper 3.x is not supported W/Looper ( 3235): Slow Looper main: doFrame is 349ms late because of 2 msg, msg 1 took 359ms (seq=10 late=38ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver) I/ru.beeline.dol( 3235): ProcessProfilingInfo new_methods=490 is saved saved_to_disk=1 resolve_classesdelay=8000 D/FilePickerDelegate( 3235): Selected type /_ I/Timeline( 3235): Timeline: Activity_launch_request time:243034211 D/FlutterView( 3235): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@71e4910 I/FilePickerDelegate( 3235): [SingleFilePick] File URI:content://com.android.providers.media.documents/document/image%3A108732 E/FilePickerUtils( 3235): Getting for API 19 or abovecontent://com.android.providers.media.documents/document/image%3A108732 E/AndroidRuntime( 3235): FATAL EXCEPTION: Thread-4 E/AndroidRuntime( 3235): Process: ru.beeline.dol, PID: 3235 E/AndroidRuntime( 3235): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference E/AndroidRuntime( 3235): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106) E/AndroidRuntime( 3235): at java.lang.Thread.run(Thread.java:919) E/FilePickerUtils( 3235): Document URI E/FilePickerUtils( 3235): Media Document URI I/FilePickerUtils( 3235): Image Media Document URI E/MQSEventManagerDelegate( 3235): failed to get MQSService. I/FilePickerDelegate( 3235): Absolute file path:/storage/emulated/0/VK/Downloads/wkl7KXuYpNA.jpg I/Process ( 3235): Sending signal. PID: 3235 SIG: 9

Hello I commented this code in plugin FilePickerDeligate.java,

// if (type.equals("dir") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); // }

you can do this if you do not want to pick folder

Thanks

miguelpruivo commented 4 years ago

If this is affecting multiple users I’d be glad to help, just need to figure what’s triggering the issue, this is, being able to replicate it.

So if anyone manage to create a sample app and replicate it with simulator, please share the details.

Thank you!

skiryuk commented 4 years ago

I have the same problem. Any idea? v1.11.0+2 Syncing files to device MI 8 Lite... W/Gralloc3( 3235): mapper 3.x is not supported W/Looper ( 3235): Slow Looper main: doFrame is 349ms late because of 2 msg, msg 1 took 359ms (seq=10 late=38ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver) I/ru.beeline.dol( 3235): ProcessProfilingInfo new_methods=490 is saved saved_to_disk=1 resolve_classesdelay=8000 D/FilePickerDelegate( 3235): Selected type /_ I/Timeline( 3235): Timeline: Activity_launch_request time:243034211 D/FlutterView( 3235): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@71e4910 I/FilePickerDelegate( 3235): [SingleFilePick] File URI:content://com.android.providers.media.documents/document/image%3A108732 E/FilePickerUtils( 3235): Getting for API 19 or abovecontent://com.android.providers.media.documents/document/image%3A108732 E/AndroidRuntime( 3235): FATAL EXCEPTION: Thread-4 E/AndroidRuntime( 3235): Process: ru.beeline.dol, PID: 3235 E/AndroidRuntime( 3235): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference E/AndroidRuntime( 3235): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106) E/AndroidRuntime( 3235): at java.lang.Thread.run(Thread.java:919) E/FilePickerUtils( 3235): Document URI E/FilePickerUtils( 3235): Media Document URI I/FilePickerUtils( 3235): Image Media Document URI E/MQSEventManagerDelegate( 3235): failed to get MQSService. I/FilePickerDelegate( 3235): Absolute file path:/storage/emulated/0/VK/Downloads/wkl7KXuYpNA.jpg I/Process ( 3235): Sending signal. PID: 3235 SIG: 9

Hello I commented this code in plugin FilePickerDeligate.java,

// if (type.equals("dir") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); // }

you can do this if you do not want to pick folder

Thanks

Thanks, It works! Good workaround. I will try to make an example for reproduce error and more details

Nikhil27b commented 4 years ago

My app also crash String _filePath;

void getFilePath() async { try { String filePath = await FilePicker.getFilePath( type: FileType.any, ); if (filePath == '') { return; } print("File path: " + filePath); setState(() { this._filePath = filePath; }); } on PlatformException catch (e) { print("Error while picking the file: " + e.toString()); } }

this is my code

maxbhoria commented 4 years ago

My app also crash String _filePath;

void getFilePath() async { try { String filePath = await FilePicker.getFilePath( type: FileType.any, ); if (filePath == '') { return; } print("File path: " + filePath); setState(() { this._filePath = filePath; }); } on PlatformException catch (e) { print("Error while picking the file: " + e.toString()); } }

this is my code

please share console log.

praharshbhatt commented 4 years ago

Getting the same issue

miguelpruivo commented 4 years ago

I could add a null check for that line of code in Android, but I don't like adding null checks without understanding what may be triggering them because it could hide other potential issues.

Where that issue happens, it shouldn't ever be null. So if anyone manages to replicate this issue with an Android emulator, let me know the details so I can actually debug it and implement a definitive fix and not just a workaround.

So far, only users with some physical devices had this, which doesn't help at all. @praharshbhatt did you get it on emulator?

Thanks!

praharshbhatt commented 4 years ago

Yes, got this in the emulator. Tried on multiple API versions.

nikitaIndianic commented 4 years ago

I am also fashing same issue when i choose photo from recent folder app getting crashed.

maxbhoria commented 4 years ago

@miguelpruivo Please fix this issue many users are reporting it. I already shared you my sample code in which i am getting error. You can try different system. Thanks

nikitaIndianic commented 4 years ago

it's giving error on this line if (type.equals("dir") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); }

miguelpruivo commented 4 years ago

If you manage to replicate it on the emulator, please, give me the details for it.

I’ve not yet fixed it because I wasn’t able to reproduce it. 😕

nikitaIndianic commented 4 years ago

2020-06-24 15:20:22.149 1876-2000/system_process E/TaskPersister: File error accessing recents directory (directory doesn't exist?). 2020-06-24 15:20:24.922 18016-18195/com.svc_app E/FilePickerUtils: Getting for API 19 or abovecontent://com.android.providers.media.documents/document/image%3A96 2020-06-24 15:20:24.926 18016-18196/com.svc_app E/AndroidRuntime: FATAL EXCEPTION: Thread-5 Process: com.svc_app, PID: 18016 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106) at java.lang.Thread.run(Thread.java:764) 2020-06-24 15:20:24.934 18016-18195/com.svc_app E/FilePickerUtils: Document URI 2020-06-24 15:20:24.934 18016-18195/com.svc_app E/FilePickerUtils: Media Document URI

i tried in emulator android version 9 & 10 also tried in real device oneplus 5t android version 10 min sdk version 21 compileSdkVersion 29 targetSdkVersion 29

also tried different filepicker version for now fliepicker version file_picker: ^1.12.0

nikitaIndianic commented 4 years ago

Screenshot_1592992744 see when i tried to pick image from that particular folder i am getting crash

miguelpruivo commented 4 years ago

@nikitaIndianic thanks, I'm looking into it. Does that happen only with that folder?

nikitaIndianic commented 4 years ago

i tried with nexus 5x emulator in this device i am getting crash while selection image from download folder too.

miguelpruivo commented 4 years ago

@nikitaIndianic just tried creating a new 5x emulator with the settings you gave me and it works flawlessly. There must be something else triggering the issue.

If you look into the source code, you see that the type can't be null where it is saying it is, as I have a type null check just a few lines before that. Oddly, in your activity result, the type becomes null magically.

Does that happen in a brand new Flutter project? Would you mind to try please?

nikitaIndianic commented 4 years ago

yes i have tried in new project but getting same issue. yes i am too confused because before that it's working fine.

miguelpruivo commented 4 years ago

@nikitaIndianic post your flutter doctor -v here please.

nikitaIndianic commented 4 years ago

[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.15.3 19D76, locale en-IN) • Flutter version 1.12.13+hotfix.9 at /Users/indianic/flutterSDk/flutter • Framework revision f139b11009 (3 months ago), 2020-03-30 13:57:30 -0700 • Engine revision af51afceb8 • Dart version 2.7.2

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3) • Android SDK at /Users/indianic/Library/Android/sdk • Android NDK location not configured (optional; useful for native profiling support) • Platform android-29, build-tools 29.0.3 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1) • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 11.3.1, Build version 11C504 • CocoaPods version 1.9.2

[✓] Android Studio (version 3.6) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin version 45.1.1 • Dart plugin version 192.8052 • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] Connected device (1 available) • Android SDK built for x86 64 • emulator-5556 • android-x64 • Android 10 (API 29) (emulator)

• No issues found!

miguelpruivo commented 4 years ago

@nikitaIndianic hum, you are in an old stable that's more than 6 months old, despite having a few earlier hotfixes (I'm currently on the latest 1.17). Would you mind trying flutter upgrade and try afterwards? Might be related.

nikitaIndianic commented 4 years ago

i used this version bcs in latest stable version giving issue while we long press on edittext it is not giving paste option. still let me try with latest version

miguelpruivo commented 4 years ago

@nikitaIndianic that's weird. Copy/paste is working properly for me. Let me know if it made any difference.

nikitaIndianic commented 4 years ago

yes in latest version it's working [✓] Flutter (Channel stable, v1.17.3, on Mac OS X 10.15.3 19D76, locale en-IN) • Flutter version 1.17.3 at /Users/indianic/flutterSDk/flutter • Framework revision b041144f83 (3 weeks ago), 2020-06-04 09:26:11 -0700 • Engine revision ee76268252 • Dart version 2.8.4

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3) • Android SDK at /Users/indianic/Library/Android/sdk • Platform android-29, build-tools 29.0.3 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1) • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 11.3.1, Build version 11C504 • CocoaPods version 1.9.2

[✓] Android Studio (version 3.6) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin version 45.1.1 • Dart plugin version 192.8052 • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] Connected device (1 available) • Android SDK built for x86 64 • emulator-5556 • android-x64 • Android 10 (API 29) (emulator)

• No issues found!

nikitaIndianic commented 4 years ago

but i am facing issue with copy/paste will you please verify once is it option working on latest stable version

miguelpruivo commented 4 years ago

Ok, so basically this is an issue with Flutter on older versions, surprisingly. @maxbhoria would you mind upgrading Flutter to latest stable as well and see if its working for you? Thanks!

maxbhoria commented 4 years ago

Ok, so basically this is an issue with Flutter on older versions, surprisingly. @maxbhoria would you mind upgrading Flutter to latest stable as well and see if its working for you? Thanks!

@miguelpruivo Sure, I will try this later and update here.

Thanks

i-tick commented 4 years ago

Im also facing the same issue app crashes after picking a file

maxbhoria commented 4 years ago

but i am facing issue with copy/paste will you please verify once is it option working on latest stable version

read this and try

miguelpruivo commented 4 years ago

To anyone experiencing this, please make sure you update to latest Flutter stable (currently 1.17).

vijayFxbytes commented 4 years ago

I am too facing the same issue app crashes after picking a file. Please help me.

skiryuk commented 4 years ago

I am too facing the same issue app crashes after picking a file. Please help me.

Hi, try upgrade your flutter version

vijayFxbytes commented 4 years ago

Thx. It is working.

miguelpruivo commented 4 years ago

Closing as we’ve finally found the solution. To anyone reading/experiencing this:

Please update to latest Flutter stable version and it should be fixed.

Thanks!

maxbhoria commented 4 years ago

Closing as we’ve finally found the solution. To anyone reading/experiencing this:

Please update to latest Flutter stable version and it should be fixed.

Thanks!

i would like to thank to @miguelpruivo and @nikitaIndianic who finally find the reason behind this problem.

Thanks

miguelpruivo commented 4 years ago

@maxbhoria thanks for reporting, I'll refer this on the Wiki troubleshooting section as well.

MuGiMac commented 4 years ago

Same here bro,..

File image; void selectimage() async { image=await FilePicker.getFile();

setState(() {
  image=image;
  imagepath=basename(image.path);
  uploadimagefile(image.readAsBytesSync(),imagepath);
});

}

it just keep exits,................................

V/MusicPlayerPlugin(16068): Activity Save Instance State I/FilePickerDelegate(16068): [SingleFilePick] File URI:content://com.android.externalstorage.documents/document/primary%3AIMG_20171213_095703670_HDR-01.jpeg E/FilePickerUtils(16068): Getting for API 19 or abovecontent://com.android.externalstorage.documents/document/primary%3AIMG_20171213_095703670_HDR-01.jpeg E/AndroidRuntime(16068): FATAL EXCEPTION: Thread-7 E/AndroidRuntime(16068): Process: com.example.ebplayer, PID: 16068 E/AndroidRuntime(16068): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference E/AndroidRuntime(16068): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106) E/AndroidRuntime(16068): at java.lang.Thread.run(Thread.java:764) V/MusicPlayerPlugin(16068): Activity Started V/MusicPlayerPlugin(16068): Activity Resumed E/FilePickerUtils(16068): Document URI E/FilePickerUtils(16068): External Document URI E/FilePickerUtils(16068): Primary External Document URI I/FilePickerDelegate(16068): Absolute file path:/storage/emulated/0/IMG_20171213_095703670_HDR-01.jpeg I/Process (16068): Sending signal. PID: 16068 SIG: 9 Lost connection to device.

miguelpruivo commented 4 years ago

@DarK-C0deR Please update to latest Flutter stable version (1.17.x) and it should be fixed.

MuGiMac commented 4 years ago

Tnq u Bro,...

charismatest commented 1 year ago

I am experiencing this issue on Android 8 (Galaxy A5) and 14 (emulator), getting this error after selecting a file:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

BonDizard commented 8 months ago

Please help me even for me crash is happening after picking image I'm a beginner so I'm following this course but the guy who did the course did not have crash but I'm getting now idk y.

Flutter 3.19.3 • channel stable

I/flutter ( 7623): granted D/FilePickerDelegate( 7623): Selected type image/* D/BLASTBufferQueue( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#1 destructor() D/BufferQueueConsumer( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#1(BLAST Consumer)1 disconnect D/BLASTBufferQueue( 7623): VRI[MainActivity]#0 destructor() D/BufferQueueConsumer( 7623): VRI[MainActivity]#0(BLAST Consumer)0 disconnect D/CompatibilityChangeReporter( 7623): Compat change id reported: 78294732; UID 10480; state: ENABLED D/BufferQueueConsumer( 7623): connect: controlledByApp=false E/OpenGLRenderer( 7623): Unable to match the desired swap behavior. D/BufferQueueConsumer( 7623): connect: controlledByApp=false D/BLASTBufferQueue( 7623): VRI[MainActivity]#2 acquireNextBufferLocked size=1080x2400 mFrameNumber=1 applyTransaction=true mTimestamp=131279244526977(auto) mPendingTransactions.size=0 graphicBufferId=32740535697414 transform=0 D/BLASTBufferQueue( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#3 acquireNextBufferLocked size=1080x2349 mFrameNumber=1 applyTransaction=true mTimestamp=131279249779285(auto) mPendingTransactions.size=0 graphicBufferId=32740535697415 transform=0 E/BitmapFactory( 7623): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Media/WhatsApp Images/IMG-20240316-WA0000.jpg: open failed: EACCES (Permission denied) E/AndroidRuntime( 7623): FATAL EXCEPTION: Thread-6 E/AndroidRuntime( 7623): Process: com.example.reddit_clone, PID: 7623 E/AndroidRuntime( 7623): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference E/AndroidRuntime( 7623): at com.mr.flutter.plugin.filepicker.FileUtils.compressImage(FileUtils.java:106) E/AndroidRuntime( 7623): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:104) E/AndroidRuntime( 7623): at java.lang.Thread.run(Thread.java:1012) I/Process ( 7623): Sending signal. PID: 7623 SIG: 9 Lost connection to device.


import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/material.dart';
import 'package:reddit_clone/core/common/error_text.dart';
import 'package:reddit_clone/core/common/loader.dart';
import 'package:reddit_clone/core/constants/constants.dart';
import 'package:reddit_clone/core/utils.dart';
import 'package:reddit_clone/features/community/controller/community_controller.dart';
import 'package:reddit_clone/models/community_model.dart';
import 'package:reddit_clone/theme/pallet.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';

class EditCommunityScreen extends ConsumerStatefulWidget {
  final String name;
  const EditCommunityScreen({
    super.key,
    required this.name,
  });

  @override
  ConsumerState<EditCommunityScreen> createState() =>
      _EditCommunityScreenState();
}

class _EditCommunityScreenState extends ConsumerState<EditCommunityScreen> {
  File? bannerFile;
  File? profileFile;

  void test() async {
    final plugin = DeviceInfoPlugin();
    final android = await plugin.androidInfo;

    final storageStatus = android.version.sdkInt < 33
        ? await Permission.storage.request()
        : PermissionStatus.granted;

    if (storageStatus == PermissionStatus.granted) {
      print("granted");
    }
    if (storageStatus == PermissionStatus.denied) {
      print("denied");
    }
    if (storageStatus == PermissionStatus.permanentlyDenied) {
      openAppSettings();
    }
  }

  @override
  void initState() {
    super.initState();
    test();
  }

  void save(Community community) {
    ref.read(communityControllerProvider.notifier).editCommunity(
          profileFile: profileFile,
          bannerFile: bannerFile,
          context: context,
          community: community,
        );
  }

  void selectBannerImage() async {
    final res = await pickImage();
    if (res != null) {
      setState(() {
        final filePath = res.files.first.path;
        if (filePath != null) {
          bannerFile = File(filePath);
        } else {
          // Fallback to default image if file path is null
          bannerFile = File('assets/images/google.png');
          print('File path is null');
        }
      });
    }
  }

  void selectProfileImage() async {
    final res = await pickImage();
    if (res != null) {
      setState(() {
        final filePath = res.files.first.path;
        if (filePath != null) {
          profileFile = File(filePath);
        } else {
          // Fallback to default image if file path is null
          profileFile = File('assets/images/google.png');
          print('File path is null');
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ref.watch(getCommunityNameByNameProvider(widget.name)).when(
          data: (community) => Scaffold(
            backgroundColor: Pallete.darkModeAppTheme.backgroundColor,
            appBar: AppBar(
              title: const Text("Edit Community"),
              actions: [
                TextButton(
                  onPressed: () {
                    save(community);
                  },
                  child: const Text(
                    'Save',
                  ),
                ),
              ],
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SizedBox(
                height: 300,
                child: Column(
                  children: [
                    Stack(
                      children: [
                        GestureDetector(
                          onTap: () {
                            selectBannerImage();
                          },
                          child: DottedBorder(
                            borderType: BorderType.RRect,
                            radius: const Radius.circular(10),
                            dashPattern: const [10, 4],
                            strokeCap: StrokeCap.round,
                            color: Pallete
                                .darkModeAppTheme.textTheme.bodySmall!.color!,
                            child: Container(
                              width: double.infinity,
                              height: 150,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: bannerFile != null
                                  ? Image.file(bannerFile!)
                                  : community.banner.isEmpty ||
                                          community.banner ==
                                              Constants.bannerDefault
                                      ? const Center(
                                          child: Icon(
                                            Icons.camera_alt_outlined,
                                            size: 40,
                                          ),
                                        )
                                      : Image.network(community.banner),
                            ),
                          ),
                        ),
                        Positioned(
                          bottom: 20,
                          left: 20,
                          child: GestureDetector(
                            onTap: () {
                              selectProfileImage();
                            },
                            child: profileFile != null
                                ? CircleAvatar(
                                    backgroundImage: FileImage(profileFile!),
                                    radius: 32,
                                  )
                                : CircleAvatar(
                                    backgroundImage:
                                        NetworkImage(community.avatar),
                                    radius: 32,
                                  ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          error: (error, stackTrace) => ErrorText(
            error: error.toString(),
          ),
          loading: () => const Loader(),
        );
  }
}

//the below is the method for picking image


Future<FilePickerResult?> pickImage() async {
  final image = await FilePicker.platform.pickFiles(type: FileType.image);

  return image;
}