Answer the question
In order to leave comments, you need to log in
How to fix Firebase Database connection was forcefully killed by the server error?
I'm trying to make chat on flutter + firebase. Never worked with firebase. I created a project and databases through the Google console, configured everything according to the instructions from there. Chat on flutter did according to this guide. An error appears on 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
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();
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question