未创建 Firebase 应用程序“[DEFAULT]” - 仅在将图像上传到 Firebase 存储时才在 Flutter 和 Firebase 中调用 Firebase.initializeApp()

问题描述 投票:0回答:1

我仅在 firebasestorage 中收到此错误,而不是在 firestore 中收到此错误

What the error looks like

Pubspec.yaml 文件:

name: find_missing_people
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter 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 is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: ">=3.1.0 <4.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  cloud_firestore: ^4.12.1
  cupertino_icons: ^1.0.2
  firebase_auth: ^4.12.0
  firebase_core: ^2.22.0
  firebase_dart: ^1.1.1
  firebase_database: ^10.3.4
  flutter:
    sdk: flutter
  geocoding: ^2.1.1
  geolocator: ^10.1.0
  google_sign_in: ^6.1.5
  image: ^4.1.3
  image_picker: ^1.0.4
  lottie: ^2.7.0
  permission_handler: ^11.0.1

dev_dependencies:
  flutter_lints: ^2.0.0
  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 packages.
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:
    - assets/logo.svg
    - assets/google_logo.png
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg
  # 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: Lobster
      fonts:
        - asset: fonts/Lobster-Regular.ttf
    #       - asset: fonts/Schyler-Italic.ttf
    #         style: italic
    - family: Tanker
      fonts:
        - asset: fonts/Tanker-Regular.ttf

    - family: montserrat
      fonts:
        - asset: fonts\monsterrat\Montserrat-Medium.ttf
          weight: 500
        # - asset: fonts/montserrat/Montserrat-ThinItalic.ttf
        #   style: italic
        #   weight: 100
        # - asset: fonts/montserrat/Montserrat-ExtraLight.ttf
        #   weight: 200
        # - asset: fonts/montserrat/Montserrat-ExtraLightItalic.ttf
        #   style: italic
        #   weight: 200
        # - asset: fonts/montserrat/Montserrat-Light.ttf
        #   weight: 300
        # - asset: fonts/montserrat/Montserrat-LightItalic.ttf
        #   style: italic
        #   weight: 300
        # - asset: fonts/montserrat/Montserrat-Regular.ttf
        #   weight: 400
        # - asset: fonts/montserrat/Montserrat-Medium.ttf
        #   weight: 500
        # - asset: fonts/montserrat/Montserrat-MediumItalic.ttf
        #   style: italic
        #   weight: 500
        # - asset: fonts/montserrat/Montserrat-SemiBold.ttf
        #   weight: 600
        # - asset: fonts/montserrat/Montserrat-SemiBoldItalic.ttf
        #   style: italic
        #   weight: 600
        # - asset: fonts/montserrat/Montserrat-Bold.ttf
        #   weight: 700
        # - asset: fonts/montserrat/Montserrat-BoldItalic.ttf
        #   style: italic
        #   weight: 700
        # - asset: fonts/montserrat/Montserrat-ExtraBold.ttf
        #   weight: 800
        # - asset: fonts/montserrat/Montserrat-Black.ttf
        #   weight: 900
        # - asset: fonts/montserrat/Montserrat-BlackItalic.ttf
        #   style: italic
        #   weight: 900
  # 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

**addperson.dart(这是调用函数的地方) **

import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:find_missing_people/utils/addMissing.dart';
import 'package:find_missing_people/utils/colors.dart';
//import 'package:firebase_core/firebase_core.dart';
import 'package:find_missing_people/utils/pickImage.dart';
import 'package:find_missing_people/widgets/text_input_field.dart';
import 'package:firebase_dart/firebase_dart.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class addPerson extends StatefulWidget {
  addPerson({super.key});

  @override
  State<addPerson> createState() => _addPersonState();
}

class _addPersonState extends State<addPerson> {
  final TextEditingController _namecontroller = TextEditingController();
  final TextEditingController _fathercontroller = TextEditingController();
  final TextEditingController _heightcontroller = TextEditingController();
  final TextEditingController _agecontroller = TextEditingController();
  // final TextEditingController _locationcontroller = TextEditingController();
  final TextEditingController _phonecontroller = TextEditingController();
  Uint8List? _image;

  void addImage() async {
    Uint8List img = await pickImage(ImageSource.camera);
    setState(() {
      _image = img;
    });
  }

  // Future<String> uploadImage(String path, Uint8List file) async {
  //   if (file.isNotEmpty) {
  //     Reference ref = _storage.ref().child("missingPeopleImgs/$path");
  //     UploadTask uploadTask = ref.putData(file);
  //     TaskSnapshot snapshot = await uploadTask;
  //     String downloadUrl = await snapshot.ref.getDownloadURL();
  //     return downloadUrl;
  //   } else {
  //     return "whaaaa";
  //   }
  // }

  void addUser() async {
    String resp = "Some error ocuured";

    try {
      if (_namecontroller.text != "" ||
          _fathercontroller.text != "" ||
          _heightcontroller.text != "" ||
          _agecontroller.text != "" ||
          _phonecontroller.text != "") {
        String imgUrl =
            await StoreData().uploadImage(_namecontroller.text, _image!);
        await FirebaseFirestore.instance.collection("missing").add({
          "name": _namecontroller.text,
          "father_name": _fathercontroller.text,
          "height": _heightcontroller.text,
          "age": _agecontroller.text,
          "phone": _phonecontroller.text,
          "image": imgUrl
        });
        resp = 'Success';
      } else {
        resp = "Enter all fields";
      }
    } catch (err) {
      resp = err.toString();
    }

    if (resp == 'Success') {
      _namecontroller.clear();
      _fathercontroller.clear();
      _heightcontroller.clear();
      _agecontroller.clear();
      _phonecontroller.clear();
    }
    // ignore: use_build_context_synchronously
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                resp,
                style: const TextStyle(
                    color: Colors.white,
                    fontFamily: "montserrat",
                    fontSize: 30),
              ),
            ),
            backgroundColor: theYellowColor,
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Add Person')),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          children: [
            const SizedBox(
              height: 40,
            ),
            _image != null
                ? GestureDetector(
                    onTap: addImage,
                    child: CircleAvatar(
                      radius: 90,
                      backgroundImage: MemoryImage(_image!),
                    ),
                  )
                : IconButton(
                    onPressed: addImage,
                    icon: const Icon(Icons.add_a_photo_outlined),
                    iconSize: 150,
                  ),
            const SizedBox(
              height: 20,
            ),
            TextFieldInput(
                textEditingController: _namecontroller,
                hintText: "Name",
                textInputType: TextInputType.name),
            const SizedBox(
              height: 20,
            ),
            TextFieldInput(
                textEditingController: _fathercontroller,
                hintText: "Father's Name",
                textInputType: TextInputType.name),
            const SizedBox(
              height: 20,
            ),
            TextFieldInput(
                textEditingController: _heightcontroller,
                hintText: "Height",
                textInputType: TextInputType.name),
            const SizedBox(
              height: 20,
            ),
            TextFieldInput(
                textEditingController: _agecontroller,
                hintText: "Age",
                textInputType: TextInputType.name),
            // const SizedBox(
            //   height: 20,
            // ),
            // TextFieldInput(
            //     textEditingController: _locationcontroller,
            //     hintText: "Location",
            //     textInputType: TextInputType.name),
            const SizedBox(
              height: 20,
            ),
            TextFieldInput(
                textEditingController: _phonecontroller,
                hintText: "Phone number",
                textInputType: TextInputType.name),
            const SizedBox(
              height: 40,
            ),
            Center(
              child: GestureDetector(
                onTap: addUser,
                child: Container(
                  width: double.infinity,
                  height: 60,
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(15)),
                    color: theYellowColor,
                  ),
                  child: const Center(
                      child: Text(
                    "Submit",
                    style: TextStyle(
                      fontFamily: 'montserrat',
                      fontSize: 30,
                    ),
                  )),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

**main.dart **

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'utils/authCheck.dart';
import 'utils/colors.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'LAAPATA',
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: mobileBackgroundColor,
      ),
      home: const AuthCheck(),
    );
  }
}

看起来这是产生错误的部分。 如果删除这部分,那么它就可以正常工作

final FirebaseStorage _storage = FirebaseStorage.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;

class StoreData {
  Future<String> uploadImage(String childName, Uint8List file) async {
    Reference ref = _storage.ref().child(childName);
    UploadTask uploadTask = ref.putData(file);
    TaskSnapshot snapshot = await uploadTask;
    String downloadUrl = await snapshot.ref.getDownloadURL();
    return downloadUrl;
  }

仅当我尝试将图像上传到 Firebase 存储时才会显示该错误。但是,如果我只是将数据上传到 firestore,它就可以工作

我也尝试过更新所有软件包,但没有任何区别

还有什么需要请告诉我吗

flutter firebase firebase-storage
1个回答
0
投票

do this in main.dart before run app

© www.soinside.com 2019 - 2024. All rights reserved.