-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauction_chat.dart
More file actions
80 lines (71 loc) · 2.09 KB
/
auction_chat.dart
File metadata and controls
80 lines (71 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class AuctionChat extends StatefulWidget {
final String auctionId;
AuctionChat({required this.auctionId});
@override
_AuctionChatState createState() => _AuctionChatState();
}
class _AuctionChatState extends State<AuctionChat> {
final _auth = FirebaseAuth.instance;
final _db = FirebaseDatabase.instance.reference();
final _controller = TextEditingController();
List<Map<String, dynamic>> messages = [];
@override
void initState() {
super.initState();
_db
.child("chats/auctions/${widget.auctionId}")
.orderByChild("timestamp")
.onValue
.listen((event) {
final data = Map<String, dynamic>.from(event.snapshot.value ?? {});
final msgList = data.entries
.map((e) => Map<String, dynamic>.from(e.value))
.toList();
setState(() {
messages = msgList;
});
});
}
void sendMessage() {
final user = _auth.currentUser;
if (_controller.text.trim().isEmpty || user == null) return;
final msg = {
'text': _controller.text.trim(),
'sender': user.email ?? "anonymous",
'timestamp': DateTime.now().millisecondsSinceEpoch,
};
_db.child("chats/auctions/${widget.auctionId}").push().set(msg);
_controller.clear();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView(
children: messages.map((msg) {
return ListTile(
title: Text(msg['text']),
subtitle: Text("From: ${msg['sender']}"),
);
}).toList(),
),
),
Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: InputDecoration(labelText: "Type message"),
),
),
IconButton(onPressed: sendMessage, icon: Icon(Icons.send)),
],
)
],
);
}
}