Abderrezak Douba
Abderrezak Douba

Reputation: 115

FirebaseException ([cloud_firestore/unavailable] The service is currently unavailable , and how to solve it

i created a simple app using flutter and firebase it all work well but when i click on profile icon from the navigationbar the app froze

Profile page code:

import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';

class profile extends StatefulWidget {
  const profile({Key? key,required this.userProfile}) : super(key: key);
  final String? userProfile;
  


  @override
  State<profile> createState() => _profileState();
}

class _profileState extends State<profile> {
  final userRef = FirebaseFirestore.instance.collection('users');

  buildprofileheader(){
    return FutureBuilder(future:userRef.doc(widget.userProfile).get(),
    builder: ((context, snapshot) {
      if(!snapshot.hasData){
        return CircularProgress();
      }
      UserModel user=UserModel.fromMap(Map);
      return Padding(padding:EdgeInsets.all(16.0),
      child: Column(
        children: [
                  Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(Icons.account_circle, size: 90,)
            ],
          ),
          Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(12.0),
            child: Text(
              user.Username as String,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize:16.0,
              ),
            ),
          ),
        ],
      ),
      );
    }),
       );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Profile",
          ),
        ),
        body: ListView(children: <Widget>[
          // buildprofileHeader(),
        ]));
  }
}

navigation Bar source code

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/user_model.dart';
import 'package:yumor/pages/Home_page.dart';
import 'package:yumor/pages/profile.dart';
import 'package:yumor/pages/search.dart';
import 'package:yumor/pages/upload.dart';

class BottomBar extends StatefulWidget {
const BottomBar({Key? key}) : super(key: key);

  @override
  State<BottomBar> createState() => _BottomBarState();
}

class _BottomBarState extends State<BottomBar> {
  List pages = [
    home_page(),
    search(),
    upload(),
    profile(userProfile:FirebaseAuth.instance.currentUser!.uid),
  ];
//  this current index means that this index depends on which one you click form 0 to 4
  int currentIndex = 0;
  void onTap(int index) {
    // currentindex equale to index to take value
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pages[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          selectedFontSize: 0,
          unselectedFontSize: 0,
          onTap: onTap,
          currentIndex: currentIndex,
          backgroundColor: Colors.white,
          selectedItemColor: Colors.black87,
          unselectedItemColor: Colors.grey.shade600.withOpacity(0.6),
          elevation: 0,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.home_outlined), label: 'home'),
            BottomNavigationBarItem(icon: Icon(Icons.search), label: 'search'),
            BottomNavigationBarItem(
                icon: Icon(Icons.add_box_outlined), label: 'add'),
            BottomNavigationBarItem(
                icon: Icon(Icons.person_outline_rounded), label: 'profile'),
          ]),
    );
  }
}

firebase user creation code

import 'package:flutter/foundation.dart';

class UserModel {
  String? uid;
  String? Username;
  String? email;
  String? photoUrl;
  

  UserModel(
      {this.uid, this.email, this.Username,  this.photoUrl});

  // receving data from the server
  factory UserModel.fromMap(Map) {
    return UserModel(
      uid: Map['userId'],
      Username: Map['Username'],
      email: Map['email'],
      photoUrl: Map['photoUrl'],
    );
  }

  // /// sending data to firestore
  Map<String, dynamic> toMap() {
    return {
      'userId': uid,
      'Username': Username,
      'email': email,
      'photoUrl': photoUrl,
    };
  }
}

error_patch.dart


  @patch
  @pragma("vm:external-name", "Error_throwWithStackTrace")
  external static Never _throw(Object error, StackTrace stackTrace);
}

NOTE flutter doctor -v [ [√] Flutter (Channel stable, 3.3.5, on Microsoft Windows [Version 10.0.19044.2130], locale en-US) • Flutter version 3.3.5 on channel stable at C:\Dart\flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision d9111f6402 (8 days ago), 2022-10-19 12:27:13 -0700 • Engine revision 3ad69d7be3 • Dart version 2.18.2 • DevTools version 2.15.0

Checking Android licenses is taking an unexpectedly long time...[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0) • Android SDK at C:\Users\Abdou\AppData\Local\Android\Sdk • Platform android-33, build-tools 33.0.0 • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840) • All Android licenses accepted.

[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe) ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[X] Visual Studio - develop for Windows X Visual Studio not installed; this is necessary for Windows development. Download at https://visualstudio.microsoft.com/downloads/. Please install the "Desktop development with C++" workload, including all of its default components

[√] Android Studio (version 2021.2) • 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 11.0.12+7-b1504.28-7817840)

[√] VS Code, 64-bit edition (version 1.72.2) • VS Code at C:\Program Files\Microsoft VS Code • Flutter extension version 3.50.0

[√] Connected device (3 available) • Android SDK built for x86 (mobile) • emulator-5554 • android-x86 • Android 7.0 (API 24) (emulator) • Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19044.2130] • Edge (web) • edge • web-javascript • Microsoft Edge 106.0.1370.52

[√] HTTP Host Availability • All required HTTP hosts are available ]

my pubspec.yaml

name: yumor
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 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.16.1 <3.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:
  cached_network_image: ^3.2.0
  cloud_firestore: ^3.1.10
  cupertino_icons: ^1.0.2
  email_validator: ^2.0.1
  firebase_auth: ^3.3.9
  firebase_core: ^1.13.1
  firebase_storage: ^10.2.15
  flutter:
    sdk: flutter
  flutter_native_splash: ^2.2.9
  flutter_svg: ^1.0.3
  fluttertoast: ^8.0.9
  get: ^4.6.5
  image_picker: ^0.8.5

dev_dependencies:
  
  flutter_lints: ^2.0.1
  flutter_test:
    sdk: flutter

flutter_native_splash:
  background_image: assets/splashcreen.png
  image: assets/start_logo.png



      

# 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:
    - assets/yumor-logo.png
    - assets/search_page.svg
    - assets/upload_page.svg
    - assets/user.png
  # 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

Upvotes: 0

Views: 242

Answers (1)

Aia Ashraf
Aia Ashraf

Reputation: 132

import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';

class profile extends StatefulWidget {
  const profile({Key? key,required this.userProfile}) : super(key: key);
  final String? userProfile;
  


  @override
  State<profile> createState() => _profileState();
}

class _profileState extends State<profile> {
  final userRef = FirebaseFirestore.instance.collection('users');
  final doc = await docRef.doc(docId).get();
    if (doc.exists) {
        data = doc.data();
    }
  buildprofileheader(){
    return FutureBuilder( return FutureBuilder(future:doc,
    builder: ((context, snapshot) {
      if(!snapshot.hasData){
        return CircularProgress();
      }
      UserModel user=UserModel.fromMap(Map);
      return Padding(padding:EdgeInsets.all(16.0),
      child: Column(
        children: [
                  Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(Icons.account_circle, size: 90,)
            ],
          ),
          Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(12.0),
            child: Text(
              user.Username as String,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize:16.0,
              ),
            ),
          ),
        ],
      ),
      );
    }),
       );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Profile",
          ),
        ),
        body: ListView(children: <Widget>[
          // buildprofileHeader(),
        ]));
  }
}

Upvotes: 1

Related Questions