the local chat app to support two sides:
- You (messages on the right, blue bubble)
- Friend / Bot (messages on the left, grey bubble)
We’ll simulate a “friend reply” automatically whenever you send a message.
Step 2: Chat App with Sender & Receiver
Replace your main.dart
with this:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Chat App',
theme: ThemeData(primarySwatch: Colors.blue),
home: ChatScreen(),
);
}
}
// Message Model
class Message {
final String text;
final bool isMe;
Message({required this.text, required this.isMe});
}
class ChatScreen extends StatefulWidget {
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final List<Message> _messages = [];
final TextEditingController _controller = TextEditingController();
void _sendMessage() {
if (_controller.text.trim().isEmpty) return;
setState(() {
_messages.add(Message(text: _controller.text.trim(), isMe: true));
});
// clear input
_controller.clear();
// simulate friend reply after 1 second
Future.delayed(const Duration(seconds: 1), () {
setState(() {
_messages.add(Message(text: "Friend: Got your message!", isMe: false));
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Chat App")),
body: Column(
children: [
// chat messages
Expanded(
child: ListView.builder(
reverse: true,
itemCount: _messages.length,
itemBuilder: (context, index) {
final message = _messages[_messages.length - 1 - index];
return Align(
alignment:
message.isMe ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: message.isMe ? Colors.blueAccent : Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
child: Text(
message.text,
style: TextStyle(
color: message.isMe ? Colors.white : Colors.black,
fontSize: 16,
),
),
),
);
},
),
),
// input box
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
color: Colors.grey[200],
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: "Type a message...",
border: InputBorder.none,
),
onSubmitted: (_) => _sendMessage(),
),
),
IconButton(
icon: const Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
)
],
),
)
],
),
);
}
}
New Features
- Messages have two sides:
- Your messages → Right side (blue bubble, white text).
- Friend messages → Left side (grey bubble, black text).
- Automatic fake reply after 1 second.
- Chat feels like a two-person conversation.