'Image is not being upload to Firebase Storage from Flutter Web

I tried to do this but this is showing me this exception in the console. This is the error im facing

TypeError: appImpl.storage is not a function
    at Object.getStorageInstance (http://localhost:63570/packages/firebase_storage_web/src/interop/storage.dart.lib.js:802:65)
    at firebase_storage_web.FirebaseStorageWeb.new.get delegate [as delegate] (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:213:56)
    at new reference_web.ReferenceWeb.new (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:159:28)
    at firebase_storage_web.FirebaseStorageWeb.new.[_createReference] (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:243:14)
    at http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:238:19
    at Object.guardWebExceptions (http://localhost:63570/packages/firebase_core/src/internals.dart.lib.js:79:19)
    at Object.guard (http://localhost:63570/packages/firebase_storage_web/src/utils/errors.dart.lib.js:23:22)
    at firebase_storage_web.FirebaseStorageWeb.new.ref (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:235:21)
    at firebase_storage.FirebaseStorage.__.ref (http://localhost:63570/packages/firebase_storage/firebase_storage.dart.lib.js:130:71)
    at categories_content._categoriesState.new.uploadImageToFirebase (http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:290:61)
    at uploadImageToFirebase.next (<anonymous>)
    at runBody (http://localhost:63570/dart_sdk.js:40646:34)
    at Object._async [as async] (http://localhost:63570/dart_sdk.js:40677:7)
    at categories_content._categoriesState.new.uploadImageToFirebase (http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:289:20)
    at http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:311:36
    at ink_well._InkResponseState.new.[_handleTap] (http://localhost:63570/packages/flutter/src/material/icon_button.dart.lib.js:41358:31)
    at tap.TapGestureRecognizer.new.invokeCallback (http://localhost:63570/packages/flutter/src/gestures/recognizer.dart.lib.js:190:18)
    at tap.TapGestureRecognizer.new.handleTapUp (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:411:40)
    at tap.TapGestureRecognizer.new.[_checkUp] (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:217:12)
    at tap.TapGestureRecognizer.new.handlePrimaryPointer (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:166:23)
    at tap.TapGestureRecognizer.new.handleEvent (http://localhost:63570/packages/flutter/src/gestures/recognizer.dart.lib.js:426:16)
    at pointer_router.PointerRouter.new.[_dispatch] (http://localhost:63570/packages/flutter/src/gestures/pointer_router.dart.lib.js:86:9)
    at http://localhost:63570/packages/flutter/src/gestures/pointer_router.dart.lib.js:112:26
    at LinkedMap.new.forEach (http://localhost:63570/dart_sdk.js:27731:11)
    at pointer_router.PointerRouter.new.[_dispatchEventToRoutes] (http://localhost:63570/packages/flutter/src/gestures/pointer_router.dart.lib.js:110:29)
    at pointer_router.PointerRouter.new.route (http://localhost:63570/packages/flutter/src/gestures/pointer_router.dart.lib.js:105:37)
    at binding$5.WidgetsFlutterBinding.new.handleEvent (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:367:26)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:355:24)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:63570/packages/flutter/src/rendering/layer.dart.lib.js:5431:13)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:331:14)
    at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:305:43)
    at binding$5.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:295:14)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:63570/packages/flutter/src/gestures/binding.dart.lib.js:286:54)
    at Object.invoke1 (http://localhost:63570/dart_sdk.js:190931:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:63570/dart_sdk.js:171547:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:63570/dart_sdk.js:172463:49)
    at http://localhost:63570/dart_sdk.js:172901:28
    at http://localhost:63570/dart_sdk.js:172857:16
    at loggedHandler (http://localhost:63570/dart_sdk.js:172562:11)
TypeError: appImpl.storage is not a function
    at Object.getStorageInstance (http://localhost:63570/packages/firebase_storage_web/src/interop/storage.dart.lib.js:802:65)
    at firebase_storage_web.FirebaseStorageWeb.new.get delegate [as delegate] (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:213:56)
    at new reference_web.ReferenceWeb.new (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:159:28)
    at firebase_storage_web.FirebaseStorageWeb.new.[_createReference] (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:243:14)
    at http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:238:19
    at Object.guardWebExceptions (http://localhost:63570/packages/firebase_core/src/internals.dart.lib.js:79:19)
    at Object.guard (http://localhost:63570/packages/firebase_storage_web/src/utils/errors.dart.lib.js:23:22)
    at firebase_storage_web.FirebaseStorageWeb.new.ref (http://localhost:63570/packages/firebase_storage_web/src/reference_web.dart.lib.js:235:21)
    at firebase_storage.FirebaseStorage.__.ref (http://localhost:63570/packages/firebase_storage/firebase_storage.dart.lib.js:130:71)
    at categories_content._categoriesState.new.uploadImageToFirebase (http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:290:61)
    at uploadImageToFirebase.next (<anonymous>)
    at runBody (http://localhost:63570/dart_sdk.js:40646:34)
    at Object._async [as async] (http://localhost:63570/dart_sdk.js:40677:7)
    at categories_content._categoriesState.new.uploadImageToFirebase (http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:289:20)
    at http://localhost:63570/packages/responsive_admin_dashboard/screens/components/categories_content.dart.lib.js:311:36
    at ink_well._InkResponseState.new.[_handleTap] (http://localhost:63570/packages/flutter/src/material/icon_button.dart.lib.js:41358:31)
    at tap.TapGestureRecognizer.new.invokeCallback (http://localhost:63570/packages/flutter/src/gestures/recognizer.dart.lib.js:190:18)
    at tap.TapGestureRecognizer.new.handleTapUp (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:411:40)
    at tap.TapGestureRecognizer.new.[_checkUp] (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:217:12)
    at tap.TapGestureRecognizer.new.handlePrimaryPointer (http://localhost:63570/packages/flutter/src/gestures/tap.dart.lib.js:166:23)
    at tap.TapGestureRecognizer.new.handleEvent 

Here's my code of .dart file where i wrote the code for uploading the image

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:responsive_admin_dashboard/constants/constants.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:responsive_admin_dashboard/constants/responsive.dart';
import 'package:responsive_admin_dashboard/screens/components/analytic_cards.dart';
import 'package:responsive_admin_dashboard/screens/components/custom_appbar.dart';
import 'package:responsive_admin_dashboard/screens/components/top_referals.dart';
import 'package:responsive_admin_dashboard/screens/components/users.dart';
import 'package:responsive_admin_dashboard/screens/components/users_by_device.dart';
import 'package:responsive_admin_dashboard/screens/components/viewers.dart';

import 'discussions.dart';

class CategoriesContent extends StatefulWidget {
  CategoriesContent({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _categoriesState();
}

class _categoriesState extends State<CategoriesContent> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _catName = TextEditingController();
  dynamic image;
  String fileName = "";

  pickImage() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.image,
      allowMultiple: false,
    );

    if (result != null) {
      setState(() {
        image = result.files.first.bytes;
        fileName = result.files.first.name;
      });
    } else {
      print("No image selected");
    }
  }

  uploadImageToFirebase() async {
    firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
        .ref('gs://sachthemotive-9c1ae.appspot.com/$fileName');
    try {
      await ref.putData(image);
    } on firebase_storage.FirebaseException catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        padding: EdgeInsets.all(appPadding),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              Text("Add Category"),
              Padding(
                padding: const EdgeInsets.all(30.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Container(
                      width: 200,
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.red, width: 2),
                      ),
                      child: InkWell(
                        onTap: () {
                          pickImage();
                        },
                        child: image == null
                            ? Center(
                                child: Icon(Icons.arrow_upward_rounded),
                              )
                            : Image.memory(
                                image,
                                fit: BoxFit.cover,
                              ),
                      ),
                    ),
                    SizedBox(
                      width: 40.0,
                    ),
                    Column(
                      children: [
                        Container(
                          width: 200,
                          child: TextFormField(
                            controller: _catName,
                            validator: (value) {
                              if (value!.isEmpty) {
                                return "Enter Category Name";
                              }
                              return null;
                            },
                            decoration: InputDecoration(
                                labelText: "Enter Category",
                                contentPadding: EdgeInsets.zero),
                          ),
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        TextButton(
                          onPressed: () {
                            uploadImageToFirebase();
                          },
                          child: Text("Upload"),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Here's the Pubspec.yaml where I added some dependencies.

name: responsive_admin_dashboard
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  flutter_svg: ^0.22.0
  fl_chart: ^0.36.1
  provider: ^5.0.0
  flutter_dropzone: ^3.0.5
  file_picker: ^4.5.1
  firebase_storage: ^10.2.10
  firebase_core: ^1.14.0
  firebase_auth: ^3.3.12
  cloud_firestore: ^3.1.11

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg
  assets:
    - assets/images/
    - assets/icons/

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

Here's the Index.html where I added the firebase connection to my Flutter web.

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.

    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
  -->
  <base href="/">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="responsive_admin_dashboard">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <title>responsive_admin_dashboard</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    var serviceWorkerVersion = null;
    var scriptLoaded = false;
    function loadMainDartJs() {
      if (scriptLoaded) {
        return;
      }
      scriptLoaded = true;
      var scriptTag = document.createElement('script');
      scriptTag.src = 'main.dart.js';
      scriptTag.type = 'application/javascript';
      document.body.append(scriptTag);
    }

    if ('serviceWorker' in navigator) {
      // Service workers are supported. Use them.
      window.addEventListener('load', function () {
        // Wait for registration to finish before dropping the <script> tag.
        // Otherwise, the browser will load the script multiple times,
        // potentially different versions.
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => {
            function waitForActivation(serviceWorker) {
              serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                }
              });
            }
            if (!reg.active && (reg.installing || reg.waiting)) {
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing ?? reg.waiting);
            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
            } else {
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            }
          });

        // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plaint <script> tag.
        setTimeout(() => {
          if (!scriptLoaded) {
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          }
        }, 4000);
      });
    } else {
      // Service workers not supported. Just drop the <script> tag.
      loadMainDartJs();
    }
  </script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script>
  var firebaseConfig = {
    apiKey: "AIzaSyBGkjZwgHq4ZCs7DCEkX0xkxEpx9Cpzw7Q",
    authDomain: "sachthemotive-9c1ae.firebaseapp.com",
    projectId: "sachthemotive-9c1ae",
    storageBucket: "sachthemotive-9c1ae.appspot.com",
    messagingSenderId: "38185614362",
    appId: "1:38185614362:web:e3af00acc7bef84344a5a3",
    measurementId: "G-3PKPRQ92SL"
  };

  firebase.initializeApp(firebaseConfig);
  var storage = getStorage(firebaseApp);
</script>
</body>

</html>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source