build a Chatbot App in Flutter.
I’ll first show you a local chatbot (rule-based) → then we can upgrade it with AI API (like OpenAI / Dialogflow) for real AI-powered conversations.
Step 1: Basic Chatbot (Local, Rule-Based)
lib/main.dart
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: 'Chatbot',
theme: ThemeData(primarySwatch: Colors.blue),
home: ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final List<Map<String, String>> _messages = [];
final TextEditingController _controller = TextEditingController();
void _sendMessage() {
if (_controller.text.trim().isEmpty) return;
String userMessage = _controller.text.trim();
setState(() {
_messages.add({"sender": "user", "text": userMessage});
});
_controller.clear();
_botReply(userMessage);
}
void _botReply(String userMessage) {
String reply = "I don’t understand. ";
// Simple rule-based responses
if (userMessage.toLowerCase().contains("hello")) {
reply = "Hi there! How can I help you?";
} else if (userMessage.toLowerCase().contains("how are you")) {
reply = "I’m just a bot, but I’m doing great! ";
} else if (userMessage.toLowerCase().contains("bye")) {
reply = "Goodbye! Have a great day!";
}
Future.delayed(const Duration(seconds: 1), () {
setState(() {
_messages.add({"sender": "bot", "text": reply});
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Chatbot")),
body: Column(
children: [
Expanded(
child: ListView.builder(
reverse: true,
itemCount: _messages.length,
itemBuilder: (context, index) {
final msg = _messages[_messages.length - 1 - index];
bool isUser = msg["sender"] == "user";
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isUser ? Colors.blueAccent : Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
child: Text(
msg["text"]!,
style: TextStyle(
color: isUser ? Colors.white : Colors.black,
),
),
),
);
},
),
),
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,
)
],
),
)
],
),
);
}
}
Features of This Chatbot:
- User messages appear on the right
- Bot replies on the left
- Simple AI-like responses