Code explanation for chatbot
Code explanation for chatbot
This imports the Flutter framework, which contains essential classes for building apps using the
Flutter SDK.
main() is the entry point of the application. It calls the runApp() function with ChatBotApp as the
root widget to start the app.
ChatBotApp:
o A StatelessWidget that serves as the root widget of the app.
o MaterialApp:
Wraps the app with Material Design widgets.
debugShowCheckedModeBanner: false removes the debug banner in the top-right
corner.
title sets the app title.
theme defines the app's visual theme, using a blue primary color.
home points to ChatScreen, the main screen of the app.
ChatScreen:
o A StatefulWidget to manage dynamic chat messages.
o Calls _ChatScreenState to maintain state.
_ChatScreenState:
o Contains logic and UI for the chat interface.
o _controller:
A TextEditingController to handle user input from the text field.
o _messages:
A list of message objects (maps) with keys "sender" and "text".
Sending a Message
void _sendMessage() {
if (_controller.text.trim().isEmpty) return;
setState(() {
_messages.add({"sender": "user", "text": _controller.text.trim()});
_messages.add({"sender": "bot", "text":
_generateResponse(_controller.text.trim())});
});
_controller.clear();
}
_sendMessage():
o Triggers when the send button is pressed.
o Checks for empty input:
If the input is empty, the function exits early.
o Updates _messages:
Adds the user's message.
Adds a bot-generated response by calling _generateResponse().
o Clears the input field:
Resets _controller for the next message.
Generating Responses
String _generateResponse(String userMessage) {
if (userMessage.toLowerCase().contains("hello")) {
return "Hello! How can I help you today?";
} else if (userMessage.toLowerCase().contains("how are you")) {
return "I'm just a bot, but I'm doing great!";
} else {
return "I'm sorry, I didn't understand that.";
}
}
_generateResponse():
o Takes the user's message as input and returns a simple hardcoded response based on
keywords.
Building the UI
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Basic Chatbot'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _messages.length,
itemBuilder: (context, index) {
final message = _messages[index];
final isUserMessage = message["sender"] == "user";
return Align(
alignment: isUserMessage ? Alignment.centerRight :
Alignment.centerLeft,
child: Container(
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
decoration: BoxDecoration(
color: isUserMessage ? Colors.blue[100] : Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
child: Text(
message["text"]!,
style: TextStyle(fontSize: 16),
),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: 'Type a message...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
),
SizedBox(width: 10),
IconButton(
icon: Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
),
],
),
),
],
),
);
}
}
UI Structure:
o Scaffold:
Provides the basic layout for the app.
AppBar: Displays the app title.
Column:
Contains the chat messages and input field.
o Chat Messages:
ListView.builder:
Dynamically generates message widgets from _messages.
Message Style:
Aligns messages based on the sender (user or bot).
User messages have a blue background, bot messages are grey.
o Input Field:
TextField:
Captures user input.
IconButton:
Sends the message when clicked.