flutter app is not connection with firebase database

727

In addition to adding Google-Services to your Gradle file, I think you may need to also add other things, like Firebase-Database See this set-up guide for more help.

Share:
727
Admin
Author by

Admin

Updated on December 26, 2022

Comments

  • Admin
    Admin over 1 year

    Firebase has not been correctly initialized. Have you added the "google-services.json" file to the project?

    I add the "google-services.json" file at a same path. my storage data Realtime database

    and add this code in a main i see this a solution but My problem was not solved

     WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
    

    /android/build.gradle

     buildscript {
          dependencies {
            // ... other dependencies
            classpath 'com.google.gms:google-services:4.3.3'
          }
        }
    

    /android/app/build.gradle

    android {
    
        defaultConfig {
            // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
            applicationId "com.example.flutter_app_test"
            minSdkVersion 16
            targetSdkVersion 29
            versionCode flutterVersionCode.toInteger()
            versionName flutterVersionName
        }
    
    }
    

    All my libraries are the latest version

    model code

    import 'package:firebase_database/firebase_database.dart';
    
    class Reporting_Emergency {
      String _id;
      String _name;
      String _phone;
      String _type;
      String _location;
      Reporting_Emergency(this._id, this._name, this._phone, this._type, this._location);
    
      Reporting_Emergency.Map(dynamic obj){
        this._name = obj['name'];
        this._phone = obj['phone'];
        this._type = obj['type'];
        this._location = obj['location'];
      }
    
      String get id => _id;
      String get name => _name;
      String get phone => _phone;
      String get type => _type;
      String get location => _location;
    
      Reporting_Emergency.fromSnapShot(DataSnapshot snapShot){
        _id = snapShot.value ['id'];
        _name = snapShot.value['name'];
        _phone = snapShot.value['phone'];
        _type = snapShot.value['type'];
        _location = snapShot.value['location'];
      }
    
    }
    

    ui code

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:marwa_app/component/myResponsiveLibrary.dart';
    import 'package:marwa_app/component/Logo.dart';
    import 'package:marwa_app/component/MyDrawer.dart';
    import 'package:geolocator/geolocator.dart';
    import 'package:firebase_database/firebase_database.dart';
    import 'package:marwa_app/model/reporting_model.dart';
    
    class Reporting extends StatefulWidget {
    
      @override
      _ReportingState createState() => _ReportingState();
    }
    
    final reportingRef = FirebaseDatabase.instance.reference().child("data");
    class _ReportingState extends State<Reporting> {
      final formKey = GlobalKey<FormState>();
      final scaffoldKey = GlobalKey<ScaffoldState>();
      List<Reporting_Emergency> items;
      StreamSubscription<Event> _onAdd;
    
      Reporting_Emergency _rep;
    
      TextEditingController _nameController;
      TextEditingController _phoneController;
      TextEditingController _typeController;
      double _lat;
      double _lon;
    
      // function to add new data
      _addFunction(Event event) {
        setState(() {
          items.add(new Reporting_Emergency.fromSnapShot(event.snapshot));
        });
      }
    
    
    
      BoxDecoration boxDecoration() {
        return BoxDecoration(
          color: MainModel().mainColor,
          borderRadius: BorderRadius.all(Radius.circular(40.0)),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.15),
              spreadRadius: 5,
              blurRadius: 5,
              offset: Offset(2, 2), // changes position of shadow
            ),
          ],
        );
      }
    
      TextStyle titleStyle() {
        return TextStyle(
            color: MainModel().whiteColor,
            fontSize: MainModel().setFont(MainModel().largeFont, getWidth()));
      }
    
      TextStyle textStyle() {
        return TextStyle(
          color: MainModel().whiteColor,
          fontSize: MainModel().setFont(MainModel().middleFont, getWidth()),
        );
      }
    
      double getWidth() {
        return MediaQuery.of(context).size.width;
      }
    
      @override
      void initState() {
        super.initState();
        items = new List();
        _onAdd = reportingRef.onChildAdded.listen(_addFunction);
    
        _nameController = new TextEditingController(text: _rep.name);
        _phoneController = new TextEditingController(text: _rep.phone);
        _typeController = new TextEditingController(text: _rep.type);
      }
    
      @override
      void dispose() {
        super.dispose();
        _onAdd.cancel();
      }
    
      @override
      Widget build(BuildContext context) {
        final widthScreen = MediaQuery.of(context).size.width;
        return Scaffold(
            key: scaffoldKey,
            backgroundColor: MainModel().mainColor,
            appBar: AppBar(
              backgroundColor: Color(0xff323266),
              leading: IconButton(
                  icon: Icon(
                    Icons.notifications_active,
                    color: MainModel().thirdColor,
                  ),
                  onPressed: () => {}),
              title: Logo(),
              centerTitle: true,
              actions: [
                Builder(
                  builder: (context) => IconButton(
                    icon: Icon(
                      Icons.menu,
                      color: MainModel().thirdColor,
                    ),
                    onPressed: () => Scaffold.of(context).openEndDrawer(),
                    tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
                  ),
                ),
              ],
            ),
            endDrawer: Drawer(
              child: MyDrawer(),
            ),
            body: ListView.builder(
    
                padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen)),
                itemCount: items.length,
                itemBuilder: (context, position) {
                  return Column(
                    children: [
                      Form(
                          key: formKey,
                          child: Column(
                            children: [
                              Directionality(
                                textDirection: TextDirection.rtl,
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20),
                                  margin: EdgeInsets.symmetric(horizontal: 20),
                                  alignment: Alignment.centerRight,
                                  decoration: boxDecoration(),
                                  child: TextFormField(
                                    controller: _nameController,
                                    textDirection: TextDirection.rtl,
                                    autofocus: true,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintStyle: textStyle(),
                                        hintText: 'الاسم الرباعي'),
                                    validator: (value) {
                                      if (value.isEmpty) {
                                        return "يرجى ادخل الاسم";
                                      } else {
                                        return null;
                                      }
                                    },
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                    top: MainModel().setPadding(
                                        MainModel().middlePadding, widthScreen)),
                              ),
                              Directionality(
                                textDirection: TextDirection.rtl,
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20),
                                  margin: EdgeInsets.symmetric(horizontal: 20),
                                  alignment: Alignment.centerRight,
                                  decoration: boxDecoration(),
                                  child: TextFormField(
                                    controller: _phoneController,
                                    keyboardType: TextInputType.number,
                                    textDirection: TextDirection.rtl,
                                    autofocus: true,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintStyle: textStyle(),
                                        hintText: 'رقم الهاتف'),
                                    validator: (value) {
                                      if (value.isEmpty) {
                                        return "يرجى ادخال رقم الهاتف";
                                      } else {
                                        return null;
                                      }
                                    },
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                    top: MainModel().setPadding(
                                        MainModel().middlePadding, widthScreen)),
                              ),
                              Directionality(
                                textDirection: TextDirection.rtl,
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20),
                                  margin: EdgeInsets.symmetric(horizontal: 20),
                                  alignment: Alignment.centerRight,
                                  decoration: boxDecoration(),
                                  child: TextFormField(
                                    controller: _typeController,
                                    textDirection: TextDirection.rtl,
                                    autofocus: true,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintStyle: textStyle(),
                                        hintText: 'نوع الابلاغ'),
                                    validator: (value) {
                                      if (value.isEmpty) {
                                        return "يرجى ادخال نوع الابلاغ (الحالة)";
                                      } else {
                                        return null;
                                      }
                                    },
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                    top: MainModel().setPadding(
                                        MainModel().middlePadding, widthScreen)),
                              ),
                              Container(
                                child: GestureDetector(
                                    onTap: () async {
                                      bool isLocationServiceEnabled =
                                          await Geolocator
                                              .isLocationServiceEnabled();
                                      if (isLocationServiceEnabled == true) {
                                        Position position =
                                            await Geolocator.getCurrentPosition(
                                                desiredAccuracy:
                                                    LocationAccuracy.high);
                                        _lon = position.longitude;
                                        _lat = position.latitude;
                                      } else {
                                        print(
                                            'امنح التطبيق من الوصول الى موقع... ثم اعد الارسال');
                                      }
                                    },
                                    child: Image.asset('images/location.png')),
                              ),
                              Padding(
                                  padding: EdgeInsets.only(
                                      bottom: MainModel().setPadding(
                                          MainModel().largePadding * 2,
                                          widthScreen))),
                              RaisedButton(
                                onPressed: () {
                                  if (_rep.id != null){
                                    reportingRef.child(_rep.id).set({
                                      'name': _nameController.text,
                                      'phone': _phoneController.text,
                                      'type': _typeController.text,
                                      'location': '$_lat + $_lon'
                                    }).then((_) => scaffoldKey.currentState.showSnackBar(SnackBar(
                                        content: Text('تم ارسال بياناتك .... '
                                            'سيتم التواصل معك من الجهات المختصة'))));
                                  }
                                },
                                child: Text('ارسال'),
                              )
                            ],
                          ))
                    ],
                  );
                }));
      }
    }
    

    I hope that the problem has been clarified

  • Admin
    Admin over 3 years
    I have followed the steps more than once and watched many videos, all of the commands I have added
  • Admin
    Admin over 3 years
    Did you do these last steps? firebase.google.com/docs/flutter/…
  • Admin
    Admin over 3 years
    I added all the libraries, even those that I didn't use, to no avail