Difficulty writing in cloud firestore

Asked

Viewed 225 times

-1

I managed to configure my android project to firebase, but when I test the firestore cloud nothing happens. I’m trying to write a text in the database,.

main:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main(){

  Firestore.instance
    .collection("usuarios")
    .document("pontuacao")
    .setData({"carlos" : "80", "silvana": "340"});



  runApp(App());


}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

pubspec.yaml

version: 1.0.0+1

environment:
  sdk: ">=2.1.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: ^0.1.2
  firebase_core: ^0.4.4+3
  cloud_firestore: ^0.13.4+2

App/build.Radle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "guerra.guerra"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'

Gradle/build.Radle

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

log

E/flutter ( 1511): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter ( 1511): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter ( 1511): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
E/flutter ( 1511): #0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:76:7)
E/flutter ( 1511): #1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:89:4)
E/flutter ( 1511): #2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
E/flutter ( 1511): #3      MethodChannel.setMethodCallHandler (package:flutter/src/services/platform_channel.dart:368:5)
E/flutter ( 1511): #4      new MethodChannelFirestore (package:cloud_firestore_platform_interface/src/method_channel/method_channel_firestore.dart:27:13)
E/flutter ( 1511): #5      FirestorePlatform.instance (package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart:63:19)
E/flutter ( 1511): #6      new Firestore (package:cloud_firestore/src/firestore.dart:26:42)
E/flutter ( 1511): #7      Firestore.instance (package:cloud_firestore/src/firestore.dart:29:36)
E/flutter ( 1511): #8      main (package:guerra/main.dart:6:13)
E/flutter ( 1511): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:239:25)
E/flutter ( 1511): #10     _rootRun (dart:async/zone.dart:1126:13)
E/flutter ( 1511): #11     _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 1511): #12     _runZoned (dart:async/zone.dart:1518:10)
E/flutter ( 1511): #13     runZoned (dart:async/zone.dart:1502:12)
E/flutter ( 1511): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:231:5)
E/flutter ( 1511): #15     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
E/flutter ( 1511): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
E/flutter ( 1511): 

2 answers

2

You did everything right, but how are you accessing the Firestore before the runApp() you need to add that code WidgetsFlutterBinding.ensureInitialized();

void main(){

  WidgetsFlutterBinding.ensureInitialized();

  Firestore.instance
    .collection("usuarios")
    .document("pontuacao")
    .setData({"carlos" : "80", "silvana": "340"});



  runApp(App());


}

Tip

Flutter makes things a lot easier for us, even in our mistakes... If you had paid a little more attention to the second line of the error, you would have noticed the following:

E/flutter ( 1511): If you’re running an application and need to access the Binary messenger before runApp() has been called (for example, During plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first.

0

The problem is that you are trying to use firebase before initializing the app and firebase itself. try it this way:

void main(){
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire
      future: Firebase.initializeApp(),
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return Text('ERRO');
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Firestore.instance
           .collection("usuarios")
           .document("pontuacao")
           .setData({"carlos" : "80", "silvana": "340"});

          return Container();
        }
        return CircularProgressIndicator();
      },
    );
  }
}

With this data will be saved after startup is completed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.