所有消息时间戳在消息发送时保持更新到当前时间



下面是我的代码在扑动,当我发送消息的所有时间戳为每条消息更新到当前时间,我如何确保时间不改变任何旧消息?我已经正确地拔出了时间戳,只是错过了我做错的事情来保存单个时间戳。我没有使用firebase时间戳而是使用dart给我的DateTime

import 'dart:ffi';
import 'package:bardsf/components/card_data.dart';
import 'package:bardsf/screens/admin/admin_chat.dart';
import 'package:bardsf/screens/main_screens/qr_screen.dart';
import 'package:bardsf/screens/workouts/workout_selector.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:bardsf/components/reusable_cards.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../chat/chat_selector_screen.dart';
import 'package:bardsf/screens/chat/chat_screen.dart';
import 'package:intl/intl.dart';

late String messageText;
class HomePageScreen extends StatefulWidget {
static const String id = 'home_page_screen';

@override
_HomePageScreenState createState() => _HomePageScreenState();
}
class _HomePageScreenState extends State<HomePageScreen> {
final messageTextController = TextEditingController();
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
late User loggedInUser;
static const TextStyle optionStyle = TextStyle(
fontSize: 30, fontWeight: FontWeight.bold);
@override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
}
} catch (e) {
print (e);
}
}
void messagesStream() async {
await for (var snapshot in _firestore.collection('messages').orderBy(
'timestamp').snapshots()) {
for (var message in snapshot.docs) {

print(message.data().cast());
}
}
}

@override
Widget build(BuildContext context) {
return Container(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/bar1.jpg"), fit: BoxFit.fill,
)
),
child: Scaffold(
backgroundColor: Colors.white.withOpacity(0.5),

body: SafeArea(

child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ReusableCard(
colour: Colors.white,
cardChild: CardData(
label: 'The Bar',
labeltwo: 'Member Access 24/7', icon: IconData(10),
), onPress: () {},
),
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot) {
List<MessageBubble> messageBubbles = [];
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
}
final messages = snapshot.data!.docs;
for (var message in messages) {
final messageText = message['text'];
final messageSender = message['sender'];
final currentUser = loggedInUser.email;

final messageBubble = MessageBubble(
sender: 'The Bar Gym',
text: messageText,
isMe: currentUser == messageSender,
daterTimer: DateTime.now().millisecondsSinceEpoch,
);
messageBubbles.add(messageBubble);
}

return Expanded(
child: Padding(
padding: const EdgeInsets.all(40.0),
child: Container(
color: Colors.white.withOpacity(0.6),
child: ListView(
reverse: false,
padding: EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
children: messageBubbles,
),
),
),
);
},

),

]
),
),
),
),
);
}
}
class MessageBubble extends StatelessWidget {

MessageBubble({required this.sender,required this.text,required this.isMe, required this.daterTimer });
final String sender;
final String text;
final bool isMe;
final int daterTimer;
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('M/d' ' ' 'K:m'' ''a');
var date = DateTime.fromMillisecondsSinceEpoch(timestamp);
var diff = date.difference(now);
var time = '';

if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else {
if (diff.inDays == 1) {
time = (diff.inDays/360).toString() + 'DAY AGO';
} else {
time = (diff.inDays/360).toString() + 'DAYS AGO';
}
}
return time;
}

@override
Widget build(BuildContext context) {
return  Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: isMe ? CrossAxisAlignment.stretch : CrossAxisAlignment.start,
children: <Widget>[
Row(
children: [
Expanded(
child: Text(sender,
style: TextStyle(
fontSize: 12.0,
color: Colors.red,
),
),
),
Expanded(child: Text('${readTimestamp(daterTimer)}',
style: TextStyle(color: Colors.black)
),
),
],
),
Material(
// borderRadius: isMe ? BorderRadius.only(topLeft: Radius.circular(30.0),
//   bottomLeft: Radius.circular(30.0),
//   bottomRight: Radius.circular(30.0),
//   topRight: Radius.circular(30.0)
// ) : BorderRadius.only(topRight: Radius.circular(30.0),
//   bottomLeft: Radius.circular(30.0),
//   bottomRight: Radius.circular(30.0),
//   topLeft: Radius.circular(30.0),
// ),
elevation: 5.0,
color: isMe ? Colors.transparent : Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 10.0),
child: Text('$text',
style: TextStyle( fontSize: 15.0,
fontWeight: FontWeight.bold,
color: isMe ? Colors.white : Colors.black,),
),
),
),
],
),
);
}
}

您的错误在这一行:

daterTimer: DateTime.now().millisecondsSinceEpoch,

似乎您正在重写您正在从Firestore读取的值。应该是这样的:

daterTimer: message['timestamp'];, 

根据具体情况调整

如果没有帮助,请告诉我。

编辑1:

基本上,你不是从Firestore读取时间戳,你只是读取现在的时间。

试试这个:

daterTimer: (json['timestamp'] == null) ? null : (json['timestamp'] as Timestamp).toDate(),

如果它不工作,你需要告诉我什么类型是'时间戳'字段在Firestore以及你正在使用的代码写到Firestore。

编辑2:

我打错字了。试试这个:
daterTimer: (message['timestamp'] == null) ? null : (message['timestamp'] as Timestamp).toDate(),

我必须改变这些行,它工作

daterTimer: (message['timestamp'] == null) ? null : (message['timestamp'] as Timestamp).toDate(),

final DateTime? daterTimer;

Expanded(child: Text('${daterTimer}',

相关内容

  • 没有找到相关文章

最新更新