firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.6k stars 3.95k forks source link

[FIREBASE_STORAGE] uploadTask.cancel() Unhandled Exception #12385

Closed pureimpro closed 6 months ago

pureimpro commented 6 months ago

Bug report

Describe the bug Unhandled Exception when cancel() an UploadTask (on Android), even if cancel operation is in a try/catch block :

I/flutter ( 5648): uploadTask!.snapshotEvents.listen error: **e: type 'Null' is not a subtype of type 'Map<dynamic, dynamic>', stackTrace: #0      new MethodChannelTask.mapNativeStream (package:firebase_storage_platform_interface/src/method_channel/method_channel_task.dart:71:49)
I/flutter ( 5648): <asynchronous suspension>
I/flutter ( 5648): #1      _AsBroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:469:3)
I/flutter ( 5648): <asynchronous suspension>**

Dart SDK 3.3.0 Flutter SDK 3.19.0 Debug mode

Steps to reproduce

Pickup a file with FilePicker, firebaseStorageReference.putFile(), then cancel the uploadTask before it is completed

The sample code below worked in previous versions of flutter and firebase_storage (but I do not remember which ones)

Neither FirebaseException catch block, nor PlatformException catch block handle the exception raised by cancel operation

Expected behavior

Exception thrown by uploadTask.cancel() catched by try/catch block and do not interrupt code execution in the IDE

Sample project

Code below reproduces the error


Additional context

File? image;
FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.image);

if (result != null) {
  image = File(result.files.single.path!);
}

if (image == null) return;

try {
  Reference firebaseStorageRef = FirebaseStorage.instance.ref().child('files').child('myFile.jpg');

  UploadTask uploadTask = firebaseStorageRef.putFile(image!);

  uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {
    switch (taskSnapshot.state) {
      case TaskState.running:
        printLog("uploadFile uploadTask TaskState.running");
        break;
      case TaskState.paused:
        printLog("uploadFile uploadTask TaskState.paused");
        break;
      case TaskState.success:
        printLog("uploadFile uploadTask TaskState.success");
        break;
      case TaskState.canceled:
        printLog("uploadFile uploadTask TaskState.canceled");
        break;
      case TaskState.error:
        printLog("uploadFile uploadTask TaskState.error");
        break;
    }
  }, onError: (Object e, StackTrace stackTrace) {
    printLog("uploadTask!.snapshotEvents.listen error: e: $e, stackTrace: $stackTrace");
  }, cancelOnError: true);

  printLog("### uploadFile uploadTask completed");
} on FirebaseException catch (e) {
  printLog("FirebaseException error occured during file upload");

} on PlatformException catch (e) {
  printLog("PlatformException error occured during file upload");
} 

Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` PS C:\Temp\mon_projet_flutter_1\levelz> flutter doctor -v [√] Flutter (Channel stable, 3.19.0, on Microsoft Windows [version 10.0.19045.4046], locale fr-FR) • Flutter version 3.19.0 on channel stable at C:\Temp\flutter_windows_v1.9.1+hotfix.2-stable\flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision bae5e49bc2 (7 days ago), 2024-02-13 17:46:18 -0800 • Engine revision 04817c99c9 • Dart version 3.3.0 • DevTools version 2.31.1 [√] Windows Version (Installed version of Windows is version 10 or higher) [√] Android toolchain - develop for Android devices (Android SDK version 34.0.0) • Android SDK at C:\Users\Famille\AppData\Local\Android\Sdk • Platform android-34, build-tools 34.0.0 • ANDROID_HOME = C:\Users\Famille\AppData\Local\Android\Sdk • Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java • Java version OpenJDK Runtime Environment (build 17.0.7+0-b2043.56-10550314) • All Android licenses accepted. [√] Chrome - develop for the web • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe [√] Android Studio (version 2023.1) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 17.0.7+0-b2043.56-10550314) [√] VS Code (version 1.86.2) • VS Code at C:\Users\Famille\AppData\Local\Programs\Microsoft VS Code • Flutter extension version 3.82.0 [√] Connected device (3 available) • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 13 (API 33) (emulator) • Chrome (web) • chrome • web-javascript • Google Chrome 121.0.6167.185 • Edge (web) • edge • web-javascript • Microsoft Edge 121.0.2277.128 [√] Network resources • All expected network resources are available. • No issues found! PS C:\Temp\mon_projet_flutter_1\levelz> ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` PS C:\Temp\mon_projet_flutter_1\levelz> flutter pub deps -- --style=compact Dart SDK 3.3.0 Flutter SDK 3.19.0 myApp 0.20240207.2210+2024.02.07.0 dependencies: - audio_service 0.18.12 [audio_service_platform_interface audio_service_web audio_session rxdart flutter_cache_manager clock js flutter flutter_web_plugins] - audio_session 0.1.18 [flutter flutter_web_plugins rxdart meta] - cached_network_image 3.3.1 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image] - cloud_firestore 4.15.5 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta] - cloud_functions 4.6.5 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter] - confetti 0.7.0 [flutter vector_math] - connectivity_plus 5.0.2 [flutter flutter_web_plugins connectivity_plus_platform_interface js meta nm] - csv 5.1.1 - cupertino_icons 1.0.6 - email_validator 2.1.17 - extended_nested_scroll_view 6.2.1 [flutter visibility_detector] - feature_discovery 0.14.1 [flutter provider shared_preferences] - file_picker 6.1.1 [flutter flutter_web_plugins flutter_plugin_android_lifecycle plugin_platform_interface ffi path win32] - firebase_analytics 10.8.6 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter] - firebase_app_check 0.2.1+14 [firebase_app_check_platform_interface firebase_app_check_web firebase_core firebase_core_platform_interface flutter] - firebase_auth 4.17.5 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta] - firebase_core 2.25.4 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_crashlytics 3.4.15 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace] - firebase_dynamic_links 5.4.14 [firebase_core firebase_core_platform_interface firebase_dynamic_links_platform_interface flutter meta plugin_platform_interface] - firebase_messaging 14.7.16 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - firebase_performance 0.9.3+14 [firebase_core firebase_core_platform_interface firebase_performance_platform_interface firebase_performance_web flutter] - firebase_remote_config 4.3.14 [firebase_core firebase_core_platform_interface firebase_remote_config_platform_interface firebase_remote_config_web flutter] - firebase_storage 11.6.6 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter] - flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine] - flutter_launcher_icons 0.13.1 [args checked_yaml cli_util image json_annotation path yaml] - flutter_linkify 6.0.0 [flutter linkify] - flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math] - flutter_markdown 0.6.20 [flutter markdown meta path] - flutter_riverpod 2.4.10 [collection flutter meta riverpod state_notifier] - flutter_typeahead 5.0.1 [flutter flutter_keyboard_visibility pointer_interceptor] - font_awesome_flutter 10.7.0 [flutter] - google_mobile_ads 4.0.0 [meta flutter webview_flutter_android webview_flutter_wkwebview webview_flutter] - google_sign_in 6.2.1 [flutter google_sign_in_android google_sign_in_ios google_sign_in_platform_interface google_sign_in_web] - http 1.2.0 [async http_parser meta web] - intl 0.18.1 [clock meta path] - introduction_screen 3.1.12 [flutter collection dots_indicator flutter_keyboard_visibility] - just_audio 0.9.36 [just_audio_platform_interface just_audio_web audio_session rxdart path path_provider async uuid crypto meta flutter] - markdown 7.2.1 [args meta] - package_info_plus 5.0.1 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface web win32] - path 1.9.0 - path_provider 2.1.2 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows] - permission_handler 11.3.0 [flutter meta permission_handler_android permission_handler_apple permission_handler_html permission_handler_windows permission_handler_platform_interface] - purchases_flutter 6.21.0 [flutter freezed_annotation json_annotation] - qr_flutter 4.1.0 [flutter qr] - rate_my_app 2.0.0 [shared_preferences flutter_rating_bar flutter] - riverpod_annotation 2.3.4 [meta riverpod] - rxdart 0.27.7 - share_plus 7.2.2 [cross_file meta mime flutter flutter_web_plugins share_plus_platform_interface file url_launcher_web url_launcher_windows url_launcher_linux url_launcher_platform_interface ffi win32] - shared_preferences 2.2.2 [flutter shared_preferences_android shared_preferences_foundation shared_preferences_linux shared_preferences_platform_interface shared_preferences_web shared_preferences_windows] - sign_in_with_apple 5.0.0 [flutter meta sign_in_with_apple_platform_interface sign_in_with_apple_web] - theme_provider 0.6.0 [flutter shared_preferences] - transparent_image 2.0.1 - url_launcher 6.2.4 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] dev dependencies: - build_runner 2.4.8 [analyzer args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml] - custom_lint 0.6.2 [analyzer analyzer_plugin args async ci cli_util collection freezed_annotation json_annotation meta package_config path pub_semver pubspec_parse rxdart uuid yaml] - flutter_lints 3.0.1 [lints] - flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math leak_tracker_flutter_testing async boolean_selector characters collection leak_tracker leak_tracker_testing material_color_utilities meta source_span stream_channel string_scanner term_glyph vm_service] - integration_test 0.0.0 [flutter flutter_driver flutter_test path vm_service async boolean_selector characters clock collection fake_async file leak_tracker leak_tracker_flutter_testing leak_tracker_testing matcher material_color_utilities meta source_span stack_trace stream_channel string_scanner sync_http term_glyph test_api vector_math webdriver] - riverpod_generator 2.3.11 [analyzer build build_config collection crypto meta path riverpod_analyzer_utils riverpod_annotation source_gen] - riverpod_lint 2.3.9 [analyzer analyzer_plugin collection custom_lint_builder meta path riverpod riverpod_analyzer_utils source_span yaml] transitive dependencies: - _fe_analyzer_shared 67.0.0 [meta] - _flutterfire_internals 1.3.22 [collection firebase_core firebase_core_platform_interface flutter meta] - analyzer 6.4.1 [_fe_analyzer_shared collection convert crypto glob meta package_config path pub_semver source_span watcher yaml] - analyzer_plugin 0.11.3 [analyzer collection dart_style pub_semver yaml] - archive 3.4.10 [crypto path pointycastle] - args 2.4.2 - async 2.11.0 [collection meta] - audio_service_platform_interface 0.1.1 [flutter plugin_platform_interface meta] - audio_service_web 0.1.1 [audio_service_platform_interface rxdart js flutter flutter_web_plugins] - boolean_selector 2.1.1 [source_span string_scanner] - build 2.4.1 [analyzer async convert crypto glob logging meta package_config path] - build_config 1.1.1 [checked_yaml json_annotation path pubspec_parse yaml] - build_daemon 4.0.1 [built_collection built_value crypto http_multi_server logging path pool shelf shelf_web_socket stream_transform watcher web_socket_channel] - build_resolvers 2.4.2 [analyzer async build collection convert crypto graphs logging package_config path pool pub_semver stream_transform yaml] - build_runner_core 7.3.0 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta package_config path pool timing watcher yaml] - built_collection 5.1.1 - built_value 8.9.1 [built_collection collection fixnum meta] - cached_network_image_platform_interface 4.0.0 [flutter flutter_cache_manager] - cached_network_image_web 1.1.1 [cached_network_image_platform_interface flutter flutter_cache_manager] - characters 1.3.0 - checked_yaml 2.0.3 [json_annotation source_span yaml] - ci 0.1.0 - cli_util 0.4.1 [meta path] - clock 1.1.1 - cloud_firestore_platform_interface 6.1.6 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - cloud_firestore_web 3.10.5 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js] - cloud_functions_platform_interface 5.5.16 [firebase_core flutter meta plugin_platform_interface] - cloud_functions_web 4.6.16 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - code_builder 4.10.0 [built_collection built_value collection matcher meta] - collection 1.18.0 - connectivity_plus_platform_interface 1.2.4 [flutter meta plugin_platform_interface] - convert 3.1.1 [typed_data] - cross_file 0.3.3+8 [meta web] - crypto 3.0.3 [typed_data] - custom_lint_builder 0.6.2 [analyzer analyzer_plugin collection custom_lint custom_lint_core glob hotreloader meta package_config path pubspec_parse rxdart] - custom_lint_core 0.6.2 [analyzer analyzer_plugin collection custom_lint glob matcher meta package_config path pubspec_parse source_span yaml] - dart_style 2.3.4 [analyzer args collection path pub_semver source_span] - dbus 0.7.10 [args ffi meta xml] - dots_indicator 2.1.2 [flutter] - fake_async 1.3.1 [clock collection] - ffi 2.1.2 - file 7.0.0 [meta path] - firebase_analytics_platform_interface 3.9.6 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_analytics_web 0.5.5+18 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - firebase_app_check_platform_interface 0.1.0+16 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_app_check_web 0.1.0+16 [_flutterfire_internals firebase_app_check_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - firebase_auth_platform_interface 7.1.5 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_auth_web 5.9.5 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser js meta web] - firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface] - firebase_core_web 2.11.4 [firebase_core_platform_interface flutter flutter_web_plugins js meta web] - firebase_crashlytics_platform_interface 3.6.22 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_dynamic_links_platform_interface 0.2.6+22 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_platform_interface 4.5.24 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 3.6.5 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta web] - firebase_performance_platform_interface 0.1.4+22 [_flutterfire_internals firebase_core flutter plugin_platform_interface] - firebase_performance_web 0.1.4+22 [_flutterfire_internals firebase_core firebase_core_web firebase_performance_platform_interface flutter flutter_web_plugins js] - firebase_remote_config_platform_interface 1.4.22 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_remote_config_web 1.4.22 [firebase_core firebase_core_web firebase_remote_config_platform_interface flutter flutter_web_plugins js] - firebase_storage_platform_interface 5.1.9 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_storage_web 3.7.0 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta web] - fixnum 1.1.0 - flutter_cache_manager 3.3.1 [clock collection file flutter http path path_provider rxdart sqflite uuid] - flutter_driver 0.0.0 [file flutter flutter_test fuchsia_remote_debug_protocol path meta vm_service webdriver async boolean_selector characters clock collection leak_tracker leak_tracker_flutter_testing leak_tracker_testing matcher material_color_utilities platform process source_span stack_trace stream_channel string_scanner sync_http term_glyph test_api vector_math] - flutter_keyboard_visibility 5.4.3 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_linux flutter_keyboard_visibility_macos flutter_keyboard_visibility_web flutter_keyboard_visibility_windows flutter] - flutter_keyboard_visibility_linux 1.0.0 [flutter_keyboard_visibility_platform_interface flutter] - flutter_keyboard_visibility_macos 1.0.0 [flutter_keyboard_visibility_platform_interface flutter] - flutter_keyboard_visibility_platform_interface 2.0.0 [flutter meta plugin_platform_interface] - flutter_keyboard_visibility_web 2.0.0 [flutter_keyboard_visibility_platform_interface flutter_web_plugins flutter] - flutter_keyboard_visibility_windows 1.0.0 [flutter_keyboard_visibility_platform_interface flutter] - flutter_plugin_android_lifecycle 2.0.17 [flutter] - flutter_rating_bar 4.0.1 [flutter] - flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math] - freezed_annotation 2.4.1 [collection json_annotation meta] - frontend_server_client 3.2.0 [async path] - fuchsia_remote_debug_protocol 0.0.0 [process vm_service file meta path platform] - glob 2.1.2 [async collection file path string_scanner] - google_identity_services_web 0.3.0+2 [meta web] - google_sign_in_android 6.1.21 [flutter google_sign_in_platform_interface] - google_sign_in_ios 5.7.4 [flutter google_sign_in_platform_interface] - google_sign_in_platform_interface 2.4.5 [flutter plugin_platform_interface] - google_sign_in_web 0.12.3+2 [flutter flutter_web_plugins google_identity_services_web google_sign_in_platform_interface http web] - graphs 2.3.1 [collection] - hotreloader 4.2.0 [collection logging path stream_transform vm_service watcher] - http_multi_server 3.2.1 [async] - http_parser 4.0.2 [collection source_span string_scanner typed_data] - image 4.1.7 [archive meta xml] - io 1.0.4 [meta path string_scanner] - js 0.6.7 [meta] - json_annotation 4.8.1 [meta] - just_audio_platform_interface 4.2.2 [flutter plugin_platform_interface] - just_audio_web 0.4.9 [just_audio_platform_interface flutter flutter_web_plugins] - leak_tracker 10.0.0 [clock collection meta path vm_service] - leak_tracker_flutter_testing 2.0.1 [flutter leak_tracker leak_tracker_testing matcher meta] - leak_tracker_testing 2.0.1 [leak_tracker matcher meta] - linkify 5.0.0 - lints 3.0.0 - logging 1.2.0 - matcher 0.12.16+1 [async meta stack_trace term_glyph test_api] - material_color_utilities 0.8.0 [collection] - meta 1.11.0 - mime 1.0.5 - nested 1.0.0 [flutter] - nm 0.5.0 [dbus] - octo_image 2.0.0 [flutter] - package_config 2.1.0 [path] - package_info_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface] - path_provider_android 2.2.2 [flutter path_provider_platform_interface] - path_provider_foundation 2.3.2 [flutter path_provider_platform_interface] - path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_platform_interface 2.1.2 [flutter platform plugin_platform_interface] - path_provider_windows 2.2.1 [ffi flutter path path_provider_platform_interface win32] - permission_handler_android 12.0.5 [flutter permission_handler_platform_interface] - permission_handler_apple 9.4.0 [flutter permission_handler_platform_interface] - permission_handler_html 0.1.1 [flutter flutter_web_plugins permission_handler_platform_interface] - permission_handler_platform_interface 4.2.0 [flutter meta plugin_platform_interface] - permission_handler_windows 0.2.1 [flutter permission_handler_platform_interface] - petitparser 6.0.2 [meta] - platform 3.1.4 - plugin_platform_interface 2.1.8 [meta] - pointer_interceptor 0.9.3+7 [flutter] - pointycastle 3.7.4 [collection convert js] - pool 1.5.1 [async stack_trace] - process 5.0.2 [file path platform] - provider 6.1.1 [collection flutter nested] - pub_semver 2.1.4 [collection meta] - pubspec_parse 1.2.3 [checked_yaml collection json_annotation pub_semver yaml] - qr 3.0.1 [meta] - riverpod 2.5.0 [meta stack_trace state_notifier] - riverpod_analyzer_utils 0.5.1 [analyzer collection crypto custom_lint_core freezed_annotation meta path source_span] - share_plus_platform_interface 3.3.1 [cross_file flutter meta mime plugin_platform_interface path_provider uuid] - shared_preferences_android 2.2.1 [flutter shared_preferences_platform_interface] - shared_preferences_foundation 2.3.5 [flutter shared_preferences_platform_interface] - shared_preferences_linux 2.3.2 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface] - shared_preferences_platform_interface 2.3.2 [flutter plugin_platform_interface] - shared_preferences_web 2.2.2 [flutter flutter_web_plugins shared_preferences_platform_interface web] - shared_preferences_windows 2.3.2 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface] - shelf 1.4.1 [async collection http_parser path stack_trace stream_channel] - shelf_web_socket 1.0.4 [shelf stream_channel web_socket_channel] - sign_in_with_apple_platform_interface 1.0.0 [flutter plugin_platform_interface meta] - sign_in_with_apple_web 1.0.1 [flutter flutter_web_plugins sign_in_with_apple_platform_interface js] - sky_engine 0.0.99 - source_gen 1.5.0 [analyzer async build dart_style glob path source_span yaml] - source_span 1.10.0 [collection path term_glyph] - sprintf 7.0.0 - sqflite 2.3.2 [flutter sqflite_common path] - sqflite_common 2.5.3 [synchronized path meta] - stack_trace 1.11.1 [path] - state_notifier 1.0.0 [meta] - stream_channel 2.1.2 [async] - stream_transform 2.1.0 - string_scanner 1.2.0 [source_span] - sync_http 0.3.1 - synchronized 3.1.0+1 - term_glyph 1.2.1 - test_api 0.6.1 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph] - timing 1.0.1 [json_annotation] - typed_data 1.3.2 [collection] - url_launcher_android 6.3.0 [flutter url_launcher_platform_interface] - url_launcher_ios 6.2.4 [flutter url_launcher_platform_interface] - url_launcher_linux 3.1.1 [flutter url_launcher_platform_interface] - url_launcher_macos 3.1.0 [flutter url_launcher_platform_interface] - url_launcher_platform_interface 2.3.2 [flutter plugin_platform_interface] - url_launcher_web 2.2.3 [flutter flutter_web_plugins url_launcher_platform_interface web] - url_launcher_windows 3.1.1 [flutter url_launcher_platform_interface] - uuid 4.3.3 [crypto sprintf meta fixnum] - vector_math 2.1.4 - visibility_detector 0.4.0+2 [flutter] - vm_service 13.0.0 - watcher 1.1.0 [async path] - web 0.4.2 - web_socket_channel 2.4.3 [async crypto stream_channel web] - webdriver 3.0.3 [matcher path stack_trace sync_http] - webview_flutter 4.7.0 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview] - webview_flutter_android 3.15.0 [flutter webview_flutter_platform_interface] - webview_flutter_platform_interface 2.10.0 [flutter meta plugin_platform_interface] - webview_flutter_wkwebview 3.12.0 [flutter path webview_flutter_platform_interface] - win32 5.2.0 [ffi] - xdg_directories 1.0.4 [meta path] - xml 6.5.0 [collection meta petitparser] - yaml 3.1.2 [collection source_span string_scanner] PS C:\Temp\mon_projet_flutter_1\levelz> ```

pureimpro commented 6 months ago

also tested with the firebase_storage example. same behaviour Maybe this issue is linked with https://github.com/firebase/flutterfire/pull/12322 ?

darshankawar commented 6 months ago

@pureimpro Can you provide us complete runnable code sample that we can directly copy paste and run to verify ? Also, please try the plugin example and check if using it, you still get the same error or not.

pureimpro commented 6 months ago

hi @darshankawar. I've tested with plugin example, same issue. I added print stacktrace to the plugin example, otherwise, only the error is displayed. This displays the same error that in my app when the task is running and you click on the cancel button :

[+1928 ms] D/UploadTask( 6611): Increasing chunk size to 16777216
[   +3 ms] E/StorageException( 6611): StorageException has occurred.
[        ] E/StorageException( 6611): The operation was cancelled.
[        ] E/StorageException( 6611):  Code: -13040 HttpResult: 0
[+19114 ms] I/flutter ( 6611): error: type 'Null' is not a subtype of type 'Map<dynamic, dynamic>'
[+3390 ms] I/flutter ( 6611): stacktrace : #0      new MethodChannelTask.mapNativeStream (package:firebase_storage_platform_interface/src/method_channel/method_channel_task.dart:71:49)
[        ] I/flutter ( 6611): <asynchronous suspension>
[        ] I/flutter ( 6611): #1      _AsBroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:469:3)
[        ] I/flutter ( 6611): <asynchronous suspension>

This is the full code :

Click To Expand ``` // Copyright 2022, the Chromium project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:io'; import 'package:bombtrack/services/utils.dart'; import 'package:file_picker/file_picker.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:share_plus/share_plus.dart'; import 'firebase_options_alpha.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // if (defaultTargetPlatform != TargetPlatform.windows) { // // window currently don't support storage emulator // final emulatorHost = // (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) // ? '10.0.2.2' // : 'localhost'; // await FirebaseStorage.instance.useStorageEmulator(emulatorHost, 9199); // } runApp(StorageExampleApp()); } /// Enum representing the upload task types the example app supports. enum UploadType { /// Uploads a randomly generated string (as a file) to Storage. string, /// Uploads a file from the device. file, /// Clears any tasks from the list. clear, } /// The entry point of the application. /// /// Returns a [MaterialApp]. class StorageExampleApp extends StatelessWidget { StorageExampleApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Storage Example App', theme: ThemeData.dark(), // Disable the banner to make the "+" button more visible. debugShowCheckedModeBanner: false, home: Scaffold( body: TaskManager(), ), ); } } /// A StatefulWidget which keeps track of the current uploaded files. class TaskManager extends StatefulWidget { // ignore: public_member_api_docs TaskManager({Key? key}) : super(key: key); @override State createState() { return _TaskManager(); } } class _TaskManager extends State { List _uploadTasks = []; /// The user selects a file, and the task is added to the list. Future uploadFile(File? file) async { if (file == null) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('No file was selected'), ), ); return null; } UploadTask uploadTask; // Create a Reference to the file Reference ref = FirebaseStorage.instance .ref() .child('test_files') .child('some-image.jpg'); final metadata = SettableMetadata( // contentType: 'image/jpeg', customMetadata: {'picked-file-path': file.path}, ); if (kIsWeb) { uploadTask = ref.putData(await file.readAsBytes(), metadata); } else { uploadTask = ref.putFile(io.File(file.path), metadata); } return Future.value(uploadTask); } /// A new string is uploaded to storage. UploadTask uploadString() { const String putStringText = 'This upload has been generated using the putString method! Check the metadata too!'; // Create a Reference to the file Reference ref = FirebaseStorage.instance .ref() .child('flutter-tests') .child('/put-string-example.txt'); // Start upload of putString return ref.putString( putStringText, metadata: SettableMetadata( contentLanguage: 'en', customMetadata: {'example': 'putString'}, ), ); } /// Handles the user pressing the PopupMenuItem item. Future handleUploadType(UploadType type) async { switch (type) { case UploadType.string: setState(() { _uploadTasks = [..._uploadTasks, uploadString()]; }); break; case UploadType.file: // final file = await ImagePicker().pickImage(source: ImageSource.gallery); List image = await Utils.getImageFile(fileType: FileType.any); UploadTask? task = await uploadFile(image[0]); if (task != null) { setState(() { _uploadTasks = [..._uploadTasks, task]; }); } break; case UploadType.clear: setState(() { _uploadTasks = []; }); break; } } void _removeTaskAtIndex(int index) { setState(() { _uploadTasks = _uploadTasks..removeAt(index); }); } Future _downloadBytes(Reference ref) async { final bytes = await ref.getData(); // Download... // await saveAsBytes(bytes!, 'some-image.jpg'); } Future _downloadLink(Reference ref) async { final link = await ref.getDownloadURL(); await Clipboard.setData( ClipboardData( text: link, ), ); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( 'Success!\n Copied download URL to Clipboard!', ), ), ); } Future _downloadFile(Reference ref) async { final io.Directory systemTempDir = io.Directory.systemTemp; final io.File tempFile = io.File('${systemTempDir.path}/temp-${ref.name}'); if (tempFile.existsSync()) await tempFile.delete(); await ref.writeToFile(tempFile); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Success!\n Downloaded ${ref.name} \n from bucket: ${ref.bucket}\n ' 'at path: ${ref.fullPath} \n' 'Wrote "${ref.fullPath}" to tmp-${ref.name}', ), ), ); } Future _delete(Reference ref) async { await ref.delete(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Success!\n deleted ${ref.name} \n from bucket: ${ref.bucket}\n ' 'at path: ${ref.fullPath} \n'), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Storage Example App'), actions: [ PopupMenuButton( onSelected: handleUploadType, icon: const Icon(Icons.add), itemBuilder: (context) => [ const PopupMenuItem( // ignore: sort_child_properties_last child: Text('Upload string'), value: UploadType.string, ), const PopupMenuItem( // ignore: sort_child_properties_last child: Text('Upload local file'), value: UploadType.file, ), if (_uploadTasks.isNotEmpty) const PopupMenuItem( // ignore: sort_child_properties_last child: Text('Clear list'), value: UploadType.clear, ), ], ), ], ), body: _uploadTasks.isEmpty ? const Center(child: Text("Press the '+' button to add a new file.")) : ListView.builder( itemCount: _uploadTasks.length, itemBuilder: (context, index) => UploadTaskListTile( task: _uploadTasks[index], onDismissed: () => _removeTaskAtIndex(index), onDownloadLink: () async { return _downloadLink(_uploadTasks[index].snapshot.ref); }, onDownload: () async { if (kIsWeb) { return _downloadBytes(_uploadTasks[index].snapshot.ref); } else { return _downloadFile(_uploadTasks[index].snapshot.ref); } }, onDelete: () async { return _delete(_uploadTasks[index].snapshot.ref); }, ), ), ); } } /// Displays the current state of a single UploadTask. class UploadTaskListTile extends StatelessWidget { // ignore: public_member_api_docs const UploadTaskListTile({ Key? key, required this.task, required this.onDismissed, required this.onDownload, required this.onDownloadLink, required this.onDelete, }) : super(key: key); /// The [UploadTask]. final UploadTask /*!*/ task; /// Triggered when the user dismisses the task from the list. final VoidCallback /*!*/ onDismissed; /// Triggered when the user presses the download button on a completed upload task. final VoidCallback /*!*/ onDownload; /// Triggered when the user presses the "link" button on a completed upload task. final VoidCallback /*!*/ onDownloadLink; /// Triggered when the user presses the "delete" button on a completed upload task. final VoidCallback /*!*/ onDelete; /// Displays the current transferred bytes of the task. String _bytesTransferred(TaskSnapshot snapshot) { return '${snapshot.bytesTransferred}/${snapshot.totalBytes}'; } @override Widget build(BuildContext context) { return StreamBuilder( stream: task.snapshotEvents, builder: ( BuildContext context, AsyncSnapshot asyncSnapshot, ) { Widget subtitle = const Text('---'); TaskSnapshot? snapshot = asyncSnapshot.data; TaskState? state = snapshot?.state; if (asyncSnapshot.hasError) { if (asyncSnapshot.error is FirebaseException && // ignore: cast_nullable_to_non_nullable (asyncSnapshot.error as FirebaseException).code == 'canceled') { subtitle = const Text('Upload canceled.'); } else { // ignore: avoid_print print("error: ${asyncSnapshot.error}"); print("stacktrace : ${asyncSnapshot.stackTrace}"); subtitle = const Text('Something went wrong.'); } } else if (snapshot != null) { subtitle = Text('$state: ${_bytesTransferred(snapshot)} bytes sent'); } return Dismissible( key: Key(task.hashCode.toString()), onDismissed: ($) => onDismissed(), child: ListTile( title: Text('Upload Task #${task.hashCode}'), subtitle: subtitle, trailing: Row( mainAxisSize: MainAxisSize.min, children: [ if (state == TaskState.running) IconButton( icon: const Icon(Icons.pause), onPressed: task.pause, ), if (state == TaskState.running) IconButton( icon: const Icon(Icons.cancel), onPressed: task.cancel, // onPressed: () async { // try { // await task.cancel(); // } catch (e) { // debugPrint("CATCHED e: $e"); // } // }, ), if (state == TaskState.paused) IconButton( icon: const Icon(Icons.file_upload), onPressed: task.resume, ), if (state == TaskState.success) IconButton( icon: const Icon(Icons.file_download), onPressed: onDownload, ), if (state == TaskState.success) IconButton( icon: const Icon(Icons.link), onPressed: onDownloadLink, ), if (state == TaskState.success) IconButton( icon: const Icon(Icons.delete), onPressed: onDelete, ), ], ), ), ); }, ); } } ```

In the StreamBuilder Widget, when cancel button is clicked in the UI :

        if (asyncSnapshot.hasError) {               <<< is TRUE because cancelling an uploadTask throws an exception
          if (asyncSnapshot.error is FirebaseException &&
              // ignore: cast_nullable_to_non_nullable
              (asyncSnapshot.error as FirebaseException).code == 'canceled') {    <<< is FALSE because it is not a FirebaseException
            subtitle = const Text('Upload canceled.');
          } else {                              <<< fallback to the else statement with an uncaught platform error (IDE stops in debug mode)
            // ignore: avoid_print
            print("error: ${asyncSnapshot.error}");
            print("stacktrace : ${asyncSnapshot.stackTrace}");
            subtitle = const Text('Something went wrong.');
          }
        } 
darshankawar commented 6 months ago

Thanks for the update. Using above details and running on Android emulator, I was able to replicate the reported behavior.

pureimpro commented 6 months ago

Thank you @darshankawar for your feeback. I will also try on iOS emulator. Do you think this issue may be related to https://github.com/firebase/flutterfire/pull/12322 ?

russellwheatley commented 6 months ago

I've just tried this many times in the example app and didn't experience the exception you are seeing.

As you can see, it correctly states "upload cancelled" which means a FirebaseException was propagated here: https://github.com/firebase/flutterfire/blob/master/packages/firebase_storage/firebase_storage/example/lib/main.dart#L327-L328

I am running on a macOS 14.0, Flutter 3.19.0, android 10.

Screenshot_20240228-103932

russellwheatley commented 6 months ago

I just realised this PR: https://github.com/firebase/flutterfire/pull/12322 hasn't been released yet and is probably why it works for me. It fixes the cancel() method.

pureimpro commented 6 months ago

Thank you @russellwheatley, PR12322 is what i suggested to be related with. If this PR fixes this issue, do you know when it will be released in a new version of firebase_storage package ?

russellwheatley commented 6 months ago

@pureimpro - it has been released about an hour ago 👍

pureimpro commented 6 months ago

issue fixed ! thank you @russellwheatley @darshankawar 👍