creating a chat message ui in flutter
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ChatGPT Clone',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
TextEditingController _controller = TextEditingController();
List<Message> _messages = [];
void _sendMessage(String text) {
setState(() {
_messages.add(Message(text: text, isUser: true));
// Simulate AI response (you can replace this with your actual AI interaction)
_messages.add(Message(text: 'AI response: Your message is "$text"', isUser: false));
});
_controller.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ChatGPT Clone'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _messages.length,
itemBuilder: (context, index) {
return ListTile(
title: Align(
alignment: _messages[index].isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: _messages[index].isUser ? Colors.blue : Colors.grey.shade300,
borderRadius: BorderRadius.circular(8.0),
),
child: Text(
_messages[index].text,
style: TextStyle(fontSize: 16),
),
),
),
);
},
),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: 'Type your message...',
),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: () {
if (_controller.text.isNotEmpty) {
_sendMessage(_controller.text);
}
},
),
],
),
),
],
),
);
}
}
class Message {
final String text;
final bool isUser;
Message({required this.text, required this.isUser});
}
Comments
Post a Comment