1

Trying to make a chat on flutter + firebase. I have never worked with firebase. I created a project and databases via Google console, configured everything according to the instructions from there. An error appears at startup:

W/PersistentConnection(11067): pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://my-testing-project-1020a-default-rtdb.europe-west1.firebasedatabase.app

Here is the full source:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await Firebase.initializeApp();    
    runApp(MyApp());
  } catch (e) {
    print(e);
  }
}

class MyApp extends StatelessWidget {
  final _firebaseRef = FirebaseDatabase().reference().child('сhats');
  final _txtCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('My chat')),
        body: Container(
          child: Center(
            child: Column(
              children: [
                Directionality(
                  textDirection: TextDirection.ltr,
                  child: StreamBuilder(
                    stream: _firebaseRef.onValue,
                    builder: (context, snap) {
                      print(snap);

                      if (snap.hasData && !snap.hasError) {
                        final event = snap.data as Event;
                        Map data = event.snapshot.value;

                        List item = [];

                        data.forEach((index, data) => item.add({"key": index, ...data}));

                        return ListView.builder(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          itemCount: item.length,
                          itemBuilder: (context, index) {
                            return ListTile(
                              title: Text(item[index]['message']),
                              trailing: Text(DateFormat("hh:mm:ss")
                                  .format(DateTime.fromMicrosecondsSinceEpoch(item[index]['timestamp'] * 1000))
                                  .toString()),
                              onTap: () => updateTimeStamp(item[index]['key']),
                              onLongPress: () => deleteMessage(item[index]['key']),
                            );
                          },
                        );
                      } else {
                        return Text('No data');
                      }
                    }
                  ),
                ),
                Container(child: Row(children: <Widget>[
                  Expanded(child: TextField(controller: _txtCtrl)),
                  SizedBox(
                    width: 80,
                    child: OutlinedButton(
                      child: Text("Add", textDirection: TextDirection.ltr),
                      onPressed: () => sendMessage()
                    ),
                  )
                ]))
              ],
            ),
          ),
        ),
      ),
    );
  }

  sendMessage() {
    _firebaseRef.push().set({
      "message": _txtCtrl.text,
      "timestamp": DateTime.now().millisecondsSinceEpoch
    });
  }

  updateTimeStamp(key) {
    _firebaseRef.child(key).update({"timestamp": DateTime.now().millisecondsSinceEpoch});
  }

  deleteMessage(key) {
    _firebaseRef.child(key).remove();
  }
}

google-services.json

And it also outputs such errors too:

W/DynamiteModule( 2551): Local module descriptor class for providerinstaller not found.
I/DynamiteModule( 2551): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 2551): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/ConnectivityManager.CallbackHandler( 2551): callback not found for CALLBACK_AVAILABLE message
Developer
  • 131
  • 1
  • 7
  • If you get an error message, please always search for that error message first: https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bflutter%5D++Database+lives+in+a+different+region.+Please+change+your+database+URL+to – Frank van Puffelen Dec 09 '21 at 15:20
  • @FrankvanPuffelen I found these questions, but it didn't help me! – Developer Dec 09 '21 at 15:21
  • Did you try specifying your database URL in the code (as the linked question suggests)? `final _firebaseRef = FirebaseDatabase(databaseURL: "https://my-testing-project-1020a-default-rtdb.europe-west1.firebasedatabase.app").reference().child('сhats');` If so, edit your question to show what you tried please. – Frank van Puffelen Dec 09 '21 at 15:48
  • @FrankvanPuffelen I set it in google-services.json: https://goo-gl.me/wHqj1 – Developer Dec 10 '21 at 07:44
  • The common cause of this problem is that it's not being picked up correctly from the config file, which is why I asked you to put the URL in the code in my previous comment. – Frank van Puffelen Dec 10 '21 at 16:36
  • @FrankvanPuffelen added. Reopen please... – Developer Dec 13 '21 at 10:35
  • Did you already try putting the URL in the code, as I suggested? Did that change the logging output from the app? – Frank van Puffelen Dec 13 '21 at 15:12
  • @FrankvanPuffelen I tried. No. – Developer Dec 13 '21 at 15:48
  • It seems quite unlikely that the same log output is given when you hard-code the correct URL. Can you edit your question and add at the bottom the code you now use to access the database and the log output you now get? – Frank van Puffelen Dec 13 '21 at 15:52
  • Had same problem. Replaced google-services.json. That was not enough. ```flutter clean``` and ```flutter pub get``` worked – Syed Umair Jul 31 '22 at 12:04

0 Answers0