【问题标题】:flutter app is not connection with firebase database颤振应用程序未与firebase数据库连接
【发布时间】:2021-04-07 05:47:30
【问题描述】:

Firebase 未正确初始化。您是否将“google-services.json”文件添加到项目中?

我将“google-services.json”文件添加到同一路径。 我的存储数据实时数据库

并在主代码中添加此代码,我看到这是一个解决方案,但我的问题没有解决

 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
    }

}

我所有的库都是最新版本

型号代码

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'];
  }

}

用户界面代码

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('ارسال'),
                          )
                        ],
                      ))
                ],
              );
            }));
  }
}

希望问题已经澄清

【问题讨论】:

    标签: android firebase flutter dart firebase-realtime-database


    【解决方案1】:

    除了将Google-Services 添加到您的Gradle 文件之外,我认为您可能还需要添加其他内容,例如Firebase-Database 如需更多帮助,请参阅this set-up guide

    【讨论】:

    • 我已经不止一次按照这些步骤操作,看了很多视频,所有的命令都是我添加的
    • 你做了这些最后的步骤吗? firebase.google.com/docs/flutter/…
    • 我添加了所有的库,甚至那些我没用过的库都没有用
    猜你喜欢
    • 2022-10-09
    • 1970-01-01
    • 2021-04-18
    • 2020-02-20
    • 2021-07-15
    • 2020-07-05
    • 1970-01-01
    • 2022-10-06
    • 2020-11-14
    相关资源
    最近更新 更多