firebase – Check authentication state using stream not working in Flutter

I’m using GoogleSignIn.

On my splash screen, I’m using StreamBuilder to check whether the user is logged in or not, and based on that data I’m trying to show the Login Screen or Home Screen.

When I uninstall and reinstall the app it shows the Login Screen for the first time. And then after it always shows me the Home Screen even if I logged out from the app.

Below is my code for Splash Screen:

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
        if (snapshot.hasData) {
          print(snapshot.hasData);
          return AnimatedSplashScreen(
            splashIconSize: SizeConfig.blockSizeVertical * 16,
            splashTransition: SplashTransition.fadeTransition,
            nextScreen: HomeScreen(),
            splash: kLogoImage,
            duration: 800,
          );
        } else {
          print(snapshot.hasData);
          return AnimatedSplashScreen(
            splashIconSize: SizeConfig.blockSizeVertical * 16,
            splashTransition: SplashTransition.fadeTransition,
            nextScreen: LoginScreen(),
            splash: kLogoImage,
            duration: 800,
          );
        }
      },
    );
  }
}

Below is my code for Home Screen:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final GoogleSignIn googleSignIn = GoogleSignIn();
  User firebaseUser;

  signOut() async {
    await googleSignIn.signOut();
    Navigator.pushReplacementNamed(context, MyRoutes.loginScreen);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: (
          Center(
            child: Text('Hello'),
          ),
          MaterialButton(
              child: Text('Log out'),
              color: Colors.red,
              onPressed: () {
                signOut();
              })
        ),
      ),
    );
  }
}

WKWebView WKNavigationDelegate Not Being Called on Next.js Firebase Hosting Site

I’m using the WKNavigationDelegate method below to monitor the current url so that I can pop the WKWebView off the stack when the user hits a certain url.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            print("DELEGATE CALLED")
            guard let url = navigationAction.request.url else {
                print("GUARD CALLED FOR .allow")
                decisionHandler(.allow)
                return
            }
            
            print(url)
            
            if url.absoluteString.contains("/about") {
                print("IF CALLED FOR .cancel")
                decisionHandler(.cancel)
                parent.showingWebViewTest = false
            } else {
                print("ELSE CALLED FOR .allow")
                decisionHandler(.allow)
            }
        }

When I use this method with a url that’s not part of my project. It seems to work well. Below is the print output when hitting the base url and then when I hit the url I am monitoring. The WKWebView pops off as expected when the monitored url is hit.

Base URL

DELEGATE CALLED https://www.flocycling.com/ ELSE CALLED FOR .allow
DELEGATE CALLED https://www.flocycling.com/ ELSE CALLED FOR .allow
DELEGATE CALLED https://flocycling.com/ ELSE CALLED FOR .allow

Monitored URL

DELEGATE CALLED
https://flocycling.com/pages/about
IF CALLED FOR .cancel
2021-04-16 13:03:12.310439-0700 Global Seafood Exchange(79393:6686501) WF: _userSettingsForUser : (null)
2021-04-16 13:03:12.310584-0700 Global Seafood Exchange(79393:6686501) WF: _WebFilterIsActive returning: NO
DELEGATE CALLED
https://www.flocycling.com/
ELSE CALLED FOR .allow
DELEGATE CALLED
https://flocycling.com/
ELSE CALLED FOR .allow

However, when I try and use this method for a site I am building on NextJS that is hosted on Firebase, the delegate method is called once on initial site load and then isn’t called again as I navigate the site. The print output for the site hosted on Firebase Hosting built on NextJS is below.

DELEGATE CALLED
https://www.testsiteformyapp.com/
ELSE CALLED FOR .allow
DELEGATE CALLED
https://testsiteformyapp.com/
ELSE CALLED FOR .allow
2021-04-16 13:08:45.586447-0700 Test Site(79510:6699787) WF: _userSettingsForUser : (null)
2021-04-16 13:08:45.587173-0700 Test Site(79510:6699787) WF: _WebFilterIsActive returning: NO
2021-04-16 13:08:45.646099-0700 Test Site(79510:6699787) (Process) 0x7ffc78067220 - (pageProxyID=6, webPageID=7, PID=79515) WebPageProxy::didFailProvisionalLoadForFrame: frameID = 3, domain = NSURLErrorDomain, code = -999
DELEGATE CALLED
https://www.testsiteformyapp.com/
ELSE CALLED FOR .allow
DELEGATE CALLED
https://testsiteformyapp.com/
ELSE CALLED FOR .allow
DELEGATE CALLED
https://testsiteformyapp.firebaseapp.com/__/auth/iframe?apiKey=*********************&appName=%5BDEFAULT%5D&v=8.2.5&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en_US.MWM3Xj_RD9s.O%2Fam%3DAQ%2Fd%3D1%2Fct%3Dzgms%2Frs%3DAGLTcCOUmnuCcTtedasW7L1tq37fs4eoIg%2Fm%3D__features__#id=I0_1618603726774&_gfid=I0_1618603726774&parent=https%3A%2F%2Ftestsiteformyapp.com&pfname=&rpctoken=69235721
ELSE CALLED FOR .allow
2021-04-16 13:09:01.047437-0700 Test Site(79510:6701010) () nw_protocol_get_quic_image_block_invoke dlopen libquic failed

I’m not sure if this is related to NextJS or Firebase or something else completely. Any help would be greatly appreciated.

Google Data Studio – “(not set)” value when using Custom Dimension from Google Analytics in Firebase

I’m using Google Analytics in Firebase and I want to make a report in Google Data Studio. I created one custom dimension for an event but in Google Data Studio I only see “(not set)” value for this dimension.

I already tried:

  • Waiting 24h (I waited more than 3 days)
  • Register more users (now I sent data from 8 devices and I see 8 unique users in the analytics)

Here are two screenshots, the first one is from Custom Definitions page in Firebase Console and the second one is one chart from Google Data Studio.

Custom Definitions Page

Chart in Google data Studio

firebase – Flutter modo eficiente ta lista de preferencias

Necesito crear una lista de preferencias o habilidades (lista de etiquetas o tags) de un usuario y deseo saber cual es la forma mas eficiente para obtener la lista de sugerencias. Tomando en cuenta que estoy usando firebase. Es mejor usar SQLLite y sincronizar con firebase (la lista) o firebase en modo offline seria la mejor opcion (actualizando la lista)? alguna referencia.

react – Não consigo coletar os dados do firebase firestore, alguém poderia me ajudar?

App.js

import React, { useEffect, useState } from 'react';
import './App.css';
import LivesRow from './components/LivesRow';
import FeaturedLive from './components/FeaturedLive'
import Header from './components/Header'
import Api from './Api'

export default () => {
  const (livesList, setLivesList) = useState(());
  const (indxLive, setIndxLive) = useState(0);

  useEffect(() => {
    const getList = async () => {
      let results = await Api.getLivesList();
      console.log(results);
      setLivesList(results);
    }

    getList();
  }, ());

  console.log(livesList);

  return(
    <div className="page">
      <Header />
      <FeaturedLive item={livesList(indxLive)} />
      <section className="list">
          <LivesRow items={livesList} click={(indx) => setIndxLive(indx)}/>
      </section>
    </div>
  );
}

Api.js

import firebase from 'firebase/app';
import 'firebase/firebase-firestore';
import firebaseConfig from './FirebaseConfig';

const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();

export default {
    getLivesList:async () => {
        let list = ();

        let results = await db.collection('Lives').get();
        results.forEach(result => {
            let data = result.data();

            list.push({
                title: data.title,
                expositor: data.expositor,
                cargo: data.cargo,
                date: data.date,
                vagas: data.vagas,
                img: data.img,
                indx: data.indx
            });
        });

        return list;
    }
}

FeaturedLive.js

import React from 'react';
import './FeaturedLive.css';

export default ({item}) => {
    let description = item.description;
    if(description.length > 200){
        description = description.substring(0, 200)+'...';
    }

    return(
        <section className="featured" style={{
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundImage: `url(${item.img})`
        }}>
            <div className="featured--vertical">
                <div className="featured--horizontal">
                    <div className="featured--title">{item.title}</div>
                    <div className="featured--speaker">
                        <div className="featured--expositor">{item.expositor}</div>
                        <div className="featured--cargo">{item.cargo}</div>
                    </div>
                    <div className="featured--date">{item.date}</div>
                    <div className="featured--description">{description}</div>
                    <div className="featured--vagas">VAGAS: {item.vagas}</div>
                    <div className="featured--button">
                        <a href="" className="featured--watchbutton">Assistir</a>
                    </div>
                </div>
            </div>
        </section>
    );
}

Erro

TypeError: Cannot read property ‘description’ of undefined
push../src/components/FeaturedLive.js.webpack_exports.default
http://localhost:3000/static/js/main.chunk.js:686:26
683 | /* harmony default export */ webpack_exports(“default”) = (({
684 | item
685 | }) => {
686 | let description = item.description;
| ^ 687 |
688 | if (description.length > 200) {
689 | description = description.substring(0, 200) +

firebase – Module ‘cloud_firestore’ not found

I am coding an app that is made on Flutter. I use Firebase Firestore as a database. I added cloud_firestore as a dependency in pubspec.yaml. When I build the apk for android it works perfectly fine, but in Xcode when I’m trying to build the app for iOS I have an error ( attached image ) ‘Module cloud_firestore’ not found, all the other dependencies are working. I’ve tried everything: pod install, pod update, remove Podfile, remove Podfile.lock, I even created a blank app and added cloud_firestore as dependency and it still happens.

javascript – Como fazer para descobrir qual regra é do usuario no firebase

Fala galera, tudo na paz?
Como é possível eu poder colocar a permissão de escrever, ler, atualizar só se a role dele for igual a do roles/1 que no meu caso esta com o name: 'admin'.

a campo role do usuário é referenciado pelo collection roles

E como eu faço para verificar isso depois em js no reactjs. Agradeço a ajuda desde já

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
     match /property/{property} {
      allow read, write: if request.auth =! null && request.auth.role = /roles/1;
    }
  }
}

inserir a descrição da imagem aqui

firebase – Show sent and received messages in left and right sides with Javascript

I have created a chat app in Firebase using Javas Script. I can successfully show the messages sent and received from the two relevant users, but I’m unable to show the messages in the two sides like a normal chat application. Here I have used a list to populate the chats from the firebase real-time database

var docid= localStorage.getItem("docid");
var patid= localStorage.getItem("patId");

firebase.database().ref("DoctorChat").on("child_added", function (snapshot) {
var html = "";

if((snapshot.val().senderId == docid && snapshot.val().receiverId == patid) || (snapshot.val().senderId == patid && snapshot.val().receiverId == docid))
{
        // give each message a unique ID
        html += "<li class='list_left' id='" + snapshot.key + "'>";
        
        // show delete button if message is sent by me
        if (snapshot.val().senderId == docid) {
            html += "<button data-id='" + snapshot.key + "' onclick='deleteMessage(this);'>";
            html += "Delete";
            html += "</button>";
            alert(snapshot.key);
            document.getElementById('" + snapshot.key + "').className = 'list_right';
        }
        else
        {
            document.getElementById('" + snapshot.key + "').className = 'list_left';
        }
        
        html += snapshot.val().msg;
        html += "</li>";
        
        document.getElementById("messages").innerHTML += html;

        }
        
    });
    function deleteMessage(self) {
        // get message ID
        var messageId = self.getAttribute("data-id");

        // delete message
        firebase.database().ref("DoctorChat").child(messageId).remove();
    }

    // attach listener for delete message
    firebase.database().ref("DoctorChat").on("child_removed", function (snapshot) {
        // remove message node
        document.getElementById("message-" + snapshot.key).innerHTML = "This message was deleted";
    });`

**************************************************

    <style>
.list_right {
  color: black;
  text-align: right;
}

.list_left {
  color: black;
  text-align: left;
}
    </style>

**************************************

<div id="wrapper">
        <div id="menu">
            <p class="welcome">Welcome, Chat App <b></b></p>

            <div></div>
        </div>

        <div id="chatbox">
            <ul id="messages">

            </ul>
        </div>

        </div>