Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Configurar Google Firebase en proyecto Flutter

Tiempo de lectura: 4 minutos

Hoy vamos a aprender cómo podemos configurar Google Firebase en un proyecto Flutter.

Lo primero que tenemos que hacer es crear nuestro proyecto Firebase, para ello vamos a https://firebase.google.com/

Y pulsamos en Ir a la consola:

Elegimos Agregar Proyecto

Elegimos un nombre para la APP. Podemos elegir si queremos activar Google Analytics.

Esperamos a que el proyecto se configure y pulsamos en continuar:

Ahora instalamos Firebase CLI: https://firebase.google.com/docs/cli?hl=es-419#setup_update_cli

Descargamos el que necesitemos según el Sistema Operativo, en mi caso utilizo Windows:

Ahora, en Windows me ha impedido instalarlo, pulsamos en que es seguro y que nos deje ejecutar.

Empezará a instalar:

Ahora nos pedirá autenticarnos con nuestra cuenta Google, elegimos una y listo:

Una vez instalado, vamos a nuestro proyecto y usamos el siguiente comando:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dart pub global activate flutterfire_cli
dart pub global activate flutterfire_cli
dart pub global activate flutterfire_cli

Esperamos a que se configure.

Nos aparecerá un Warning como este:

Tendremos que añadir este Path que indica, en el caso de Windows, de la siguiente forma:

Abre el Menú de Inicio:

  • Haz clic en el botón de inicio de Windows en la esquina inferior izquierda de tu pantalla.

Configuración del Sistema:

  • Escribe «Variables de entorno» y selecciona Editar las variables de entorno del sistema

Variables de entorno:

  • En la ventana que se abre, buscamos la opción de «Variables de entorno…»

Editar la Variable PATH:

  • En la sección «Variables del sistema», busca la variable llamada «Path» y haz clic en «Editar».

Agregar la Ruta:

  • Buscamos la variable de sistema llamada Path:
  • Pulsamos en editar y añadimos la nueva:
  • C:\Users\user\AppData\Local\Pub\Cache\bin (que aparece en el Warning que te muestra en pantalla). Cambia user por tu nombre de usuario.

Guardar y Cerrar:

  • Haz clic en «Aceptar» para cerrar la ventana de edición y luego en «Aceptar» nuevamente para cerrar la ventana de «Propiedades del sistema».

Cerrar y Abrir Terminales Nuevamente:

  • Cierra cualquier terminal que estés utilizando y ábrela nuevamente para que los cambios surtan efecto.
  • También es importante reiniciar la máquina para que se establezca la configuración.

En MAC:

Instalamos Firebase Tools:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install -g firebase-tools
npm install -g firebase-tools
npm install -g firebase-tools

Instalmos FlutterFire CLI

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dart pub global activate flutterfire_cli
dart pub global activate flutterfire_cli
dart pub global activate flutterfire_cli

Y ahora configuramos la variable de entorno:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export PATH="$PATH":"$HOME/.pub-cache/bin"
export PATH="$PATH":"$HOME/.pub-cache/bin"
export PATH="$PATH":"$HOME/.pub-cache/bin"

Para dejarla siempre fija, editamos .zshrc:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
vi ~/.zshrc
vi ~/.zshrc
 vi ~/.zshrc

Y añadimos la línea al final:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export PATH="$PATH":"$HOME/.pub-cache/bin"
export PATH="$PATH":"$HOME/.pub-cache/bin"
export PATH="$PATH":"$HOME/.pub-cache/bin"

Finalmente aplicamos la configuración:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
source ~/.zshrc
source ~/.zshrc
source ~/.zshrc

Ahora añadimos firebase_core (https://pub.dev/packages/firebase_core)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutter pub add firebase_core
flutter pub add firebase_core
flutter pub add firebase_core

Ahora hacemos login en FireBase:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
firebase login
firebase login
firebase login

Y ahora usamos el comando para configurar el proyecto:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutterfire configure
flutterfire configure
flutterfire configure

Si nos aparece el siguiente error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command.
COMMAND: firebase --version
ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see https://firebase.google.com/docs/cli#install_the_firebase_cli for how to install it.
FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command. COMMAND: firebase --version ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see https://firebase.google.com/docs/cli#install_the_firebase_cli for how to install it.
FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command.
COMMAND: firebase --version
ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see https://firebase.google.com/docs/cli#install_the_firebase_cli for how to install it.

Instalamos lo siguiente:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install -g firebase-tools
npm install -g firebase-tools
npm install -g firebase-tools

*Recuerda tener nodejs instalado: https://nodejs.org/en

Si da este error

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Exception: /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- xcodeproj (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from -e:1:in `<main>'
Exception: /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- xcodeproj (LoadError) from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require' from -e:1:in `<main>'
Exception: /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- xcodeproj (LoadError)
        from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from -e:1:in `<main>'

Instalar:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sudo gem install xcodeproj
sudo gem install xcodeproj
sudo gem install xcodeproj

Y ya empezará a configurarse:

Ahora, seleccionamos el proyecto que hemos creado anteriormente.

Elegimos las plataformas que nos interesen:

En mi caso las dejo por defecto.

Y esperamos a que se configure.

Ahora vamos con el código que hará que las notificaciones funcionen.

Creamos una clase llamada FirebaseInitializer.dart

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'package:firebase_core/firebase_core.dart';
import '../../firebase_options.dart';
class FirebaseInitializer {
static Future<void> initialize() async {
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
print('Firebase initialized successfully');
} catch (e) {
print('Error initializing Firebase: $e');
}
}
}
import 'package:firebase_core/firebase_core.dart'; import '../../firebase_options.dart'; class FirebaseInitializer { static Future<void> initialize() async { try { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); print('Firebase initialized successfully'); } catch (e) { print('Error initializing Firebase: $e'); } } }
import 'package:firebase_core/firebase_core.dart';
import '../../firebase_options.dart';

class FirebaseInitializer {
  static Future<void> initialize() async {
    try {
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
      print('Firebase initialized successfully');
    } catch (e) {
      print('Error initializing Firebase: $e');
    }
  }
}

Una vez creada, tenemos que ir a nuestra clase principal y añadimos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() async {
await FirebaseInitializer.initialize();
}
void main() async { await FirebaseInitializer.initialize(); }
void main() async {
   await FirebaseInitializer.initialize();
}

Con esto se inicializa Firebase en nuestra APP.

0

Deja un comentario