The Chat widget is the primary component for rendering a chat interface in flutter_chat_ui. It requires three core properties to function:
messages: A list of messages to be rendered. These must be based on the abstract message types defined in flutter_chat_types. Custom message types must be mapped to these supported types.onSendPressed: A callback function triggered when the user sends a message. It receives a PartialText object. The developer is responsible for converting this PartialText into a full TextMessage (including author, id, and text) to maintain control over message metadata.user: A User object (requiring at least an id) used to identify the current user and determine message authorship.
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<types.Message> _messages = [];
final _user = const types.User(id: '82091008-a484-4a89-ae75-a22bf8d6f3ac');
@override
Widget build(BuildContext context) => Scaffold(
body: Chat(
messages: _messages,
onSendPressed: _handleSendPressed,
user: _user,
),
);
void _addMessage(types.Message message) {
setState(() {
_messages.insert(0, message);
});
}
void _handleSendPressed(types.PartialText message) {
final textMessage = types.TextMessage(
author: _user,
createdAt: DateTime.now().millisecondsSinceEpoch,
id: DateTime.now().toString(), // Use a unique ID (e.g., uuid package)
text: message.text,
);
_addMessage(textMessage);
}
}