Build a Beautiful Todo App in Flutter - Complete Tutorial 2025
Build a Beautiful Todo App in Flutter - Complete Tutorial 2025
Welcome back, Flutter developers! 👋
Ready to build your first real, functional app? Today, we're creating a complete Todo List app from scratch! This isn't just a tutorial - by the end, you'll have a fully working app ready to add to your portfolio.
What makes this special? We'll use all the widgets from my previous post and add real functionality with local storage. Your tasks will be saved even after closing the app!
📱 What We're Building
A beautiful, modern Todo app with:
- ✅ Add new tasks
- ✅ Mark tasks as complete
- ✅ Delete tasks
- ✅ Data persists (saved locally)
- ✅ Clean, modern UI
- ✅ Smooth animations
Time needed: 45 minutes
Difficulty: Beginner-friendly
Lines of code: ~250 (clean and simple!)
🎯 What You'll Learn
By building this app, you'll master:
- State management with
setState() - Local data storage with SharedPreferences
- List operations (add, remove, update)
- TextField input handling
- ListView with custom widgets
- Checkbox functionality
- Bottom sheets for input
This project uses: Container, Text, ListView, TextField, Buttons, Card, Padding, Scaffold - all from our previous widget guide!
📋 Prerequisites
Before starting, make sure you have:
- ✅ Flutter installed (
flutter doctorshould pass) - ✅ VS Code or Android Studio
- ✅ Basic Dart knowledge
- ✅ Read my previous post on Flutter Widgets (optional but helpful!)
🚀 Step 1: Create New Project
Open your terminal and run:
flutter create todo_app
cd todo_app
Project Structure:
todo_app/
├── lib/
│ └── main.dart # Our main file
├── pubspec.yaml # Dependencies
└── android/ios/ # Platform files
📦 Step 2: Add Dependencies
Open pubspec.yaml and add SharedPreferences for local storage:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2 # For saving data locally
Save the file, then run:
flutter pub get
✅ Dependencies installed! Now let's code.
💻 Step 3: The Complete Code
Replace everything in lib/main.dart with this code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
void main() {
runApp(const TodoApp());
}
class TodoApp extends StatelessWidget {
const TodoApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Todo App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true,
),
home: const TodoHomePage(),
);
}
}
class TodoHomePage extends StatefulWidget {
const TodoHomePage({Key? key}) : super(key: key);
@override
State<TodoHomePage> createState() => _TodoHomePageState();
}
class _TodoHomePageState extends State<TodoHomePage> {
// List to store all todos
List<Map<String, dynamic>> todos = [];
// Controller for input field
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_loadTodos(); // Load saved todos when app starts
}
// Load todos from local storage
Future<void> _loadTodos() async {
final prefs = await SharedPreferences.getInstance();
final String? todosString = prefs.getString('todos');
if (todosString != null) {
setState(() {
todos = List<Map<String, dynamic>>.from(json.decode(todosString));
});
}
}
// Save todos to local storage
Future<void> _saveTodos() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('todos', json.encode(todos));
}
// Add new todo
void _addTodo() {
if (_controller.text.trim().isEmpty) return;
setState(() {
todos.add({
'title': _controller.text,
'completed': false,
'createdAt': DateTime.now().toString(),
});
});
_controller.clear();
_saveTodos();
Navigator.pop(context); // Close bottom sheet
}
// Toggle todo completion
void _toggleTodo(int index) {
setState(() {
todos[index]['completed'] = !todos[index]['completed'];
});
_saveTodos();
}
// Delete todo
void _deleteTodo(int index) {
setState(() {
todos.removeAt(index);
});
_saveTodos();
}
// Show bottom sheet to add todo
void _showAddTodoSheet() {
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) => Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
left: 20,
right: 20,
top: 20,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Add New Task',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
TextField(
controller: _controller,
autofocus: true,
decoration: InputDecoration(
hintText: 'Enter task name...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.edit),
),
onSubmitted: (_) => _addTodo(),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _addTodo,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: const Text(
'Add Task',
style: TextStyle(fontSize: 16),
),
),
const SizedBox(height: 20),
],
),
),
);
}
@override
Widget build(BuildContext context) {
// Count completed and pending tasks
final completedCount = todos.where((todo) => todo['completed']).length;
final pendingCount = todos.length - completedCount;
return Scaffold(
backgroundColor: Colors.grey[100],
// App Bar
appBar: AppBar(
title: const Text('My Todos'),
centerTitle: true,
elevation: 0,
actions: [
if (todos.isNotEmpty)
IconButton(
icon: const Icon(Icons.delete_sweep),
onPressed: () {
setState(() {
todos.clear();
});
_saveTodos();
},
tooltip: 'Clear all',
),
],
),
// Body
body: Column(
children: [
// Stats Card
Container(
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Colors.blue, Colors.blueAccent],
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.blue.withOpacity(0.3),
blurRadius: 8,
offset: const Offset(0, 4),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildStatItem('Total', todos.length.toString(), Icons.list),
Container(width: 1, height: 40, color: Colors.white30),
_buildStatItem('Pending', pendingCount.toString(), Icons.pending_actions),
Container(width: 1, height: 40, color: Colors.white30),
_buildStatItem('Done', completedCount.toString(), Icons.check_circle),
],
),
),
// Todo List
Expanded(
child: todos.isEmpty
? _buildEmptyState()
: ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16),
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return _buildTodoItem(todo, index);
},
),
),
],
),
// Floating Action Button
floatingActionButton: FloatingActionButton.extended(
onPressed: _showAddTodoSheet,
icon: const Icon(Icons.add),
label: const Text('Add Task'),
),
);
}
// Stat item widget
Widget _buildStatItem(String label, String value, IconData icon) {
return Column(
children: [
Icon(icon, color: Colors.white, size: 28),
const SizedBox(height: 8),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Text(
label,
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
),
],
);
}
// Empty state widget
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.inbox,
size: 120,
color: Colors.grey[300],
),
const SizedBox(height: 20),
Text(
'No tasks yet!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.grey[600],
),
),
const SizedBox(height: 10),
Text(
'Tap the button below to add your first task',
style: TextStyle(
fontSize: 16,
color: Colors.grey[500],
),
),
],
),
);
}
// Todo item widget
Widget _buildTodoItem(Map<String, dynamic> todo, int index) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
// Checkbox
leading: Checkbox(
value: todo['completed'],
onChanged: (_) => _toggleTodo(index),
shape: const CircleBorder(),
),
// Task title
title: Text(
todo['title'],
style: TextStyle(
fontSize: 16,
decoration: todo['completed']
? TextDecoration.lineThrough
: TextDecoration.none,
color: todo['completed'] ? Colors.grey : Colors.black,
),
),
// Delete button
trailing: IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
onPressed: () => _deleteTodo(index),
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
🎨 Understanding the Code
Let me break down the key parts:
1. Data Storage
List<Map<String, dynamic>> todos = [];
- Stores all todos as a list of maps
- Each todo has: title, completed status, creation time
2. Loading Data
Future<void> _loadTodos() async {
final prefs = await SharedPreferences.getInstance();
final String? todosString = prefs.getString('todos');
if (todosString != null) {
setState(() {
todos = List<Map<String, dynamic>>.from(json.decode(todosString));
});
}
}
- Loads saved todos when app starts
- Uses SharedPreferences (local storage)
- Converts JSON string back to list
3. Adding Todos
void _addTodo() {
if (_controller.text.trim().isEmpty) return;
setState(() {
todos.add({
'title': _controller.text,
'completed': false,
'createdAt': DateTime.now().toString(),
});
});
_controller.clear();
_saveTodos();
}
- Adds new todo to list
- Saves to storage
- Clears input field
4. UI Components
Stats Card:
- Shows total, pending, and completed tasks
- Beautiful gradient background
- Updates automatically
Todo List:
- Scrollable list of tasks
- Checkbox to mark complete
- Delete button for each task
- Strike-through for completed tasks
Bottom Sheet:
- Modern input dialog
- Opens when FAB is pressed
- TextField with submit button
🏃 Step 4: Run Your App
flutter run
That's it! Your Todo app is ready! 🎉
✨ Features Breakdown
1. Add Tasks
- Tap the floating button
- Type your task
- Press "Add Task" or hit Enter
- Task appears in list!
2. Complete Tasks
- Tap the checkbox
- Task gets strike-through
- Stats update automatically
3. Delete Tasks
- Tap the delete icon
- Task removed permanently
4. Data Persistence
- Close the app
- Reopen it
- All tasks are still there!
5. Clear All
- Tap the sweep icon in AppBar
- All tasks cleared at once
🎯 Key Concepts Used
State Management
setState(() {
// Update UI
});
- Updates the UI when data changes
- Simple and effective for small apps
Const Widgets
const Text('My Todos')
const SizedBox(height: 20)
- Better performance
- Reduced rebuilds
- Use wherever possible!
Async/Await
Future<void> _loadTodos() async {
await SharedPreferences.getInstance();
}
- Handles asynchronous operations
- Waits for data loading
💡 Pro Tips
Performance
✅ Use const constructors everywhere possible
✅ Dispose controllers in dispose() method
✅ Avoid rebuilding entire list
User Experience
✅ Show empty state when no tasks
✅ Clear input after adding task
✅ Confirm before clearing all tasks
✅ Smooth animations
Code Quality
✅ Extract widgets into methods
✅ Use meaningful variable names
✅ Add comments for complex logic
✅ Handle edge cases
🐛 Common Issues & Solutions
Issue 1: Data Not Saving
Problem: Tasks disappear after closing app
Solution:
// Make sure you call _saveTodos() after every change
_saveTodos();
Issue 2: Keyboard Overlaps Input
Problem: Bottom sheet covered by keyboard
Solution:
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
✅ Already handled in our code!
Issue 3: Empty String Added
Problem: Empty tasks getting added
Solution:
if (_controller.text.trim().isEmpty) return;
✅ Already handled!
🚀 Next Steps - Enhance Your App
Want to make it even better? Try these:
Easy (5-10 minutes each):
- Add Colors - Let users choose task colors
- Add Priority - High/Medium/Low priority tags
- Add Icons - Different icons for task types
- Dark Mode - Add theme toggle
Medium (20-30 minutes each):
- Categories - Group tasks (Work, Personal, Shopping)
- Due Dates - Add date picker for deadlines
- Search - Search through tasks
- Sort - Sort by date, priority, status
Advanced (1-2 hours each):
- Notifications - Remind user of pending tasks
- Cloud Sync - Save to Firebase
- Share - Share tasks with others
- Analytics - Track completion rate
📱 Make It Your Own
Customize Colors:
theme: ThemeData(
primarySwatch: Colors.purple, // Change to your favorite!
useMaterial3: true,
),
Change App Name:
In main.dart:
title: 'My Awesome Tasks', // Your custom name
Add Your Style:
Modify the gradient colors, card shapes, icons - make it unique!
🎓 What You've Learned
Congratulations! You now know:
✅ How to build a complete Flutter app
✅ State management with setState()
✅ Local data persistence
✅ List operations (CRUD)
✅ Bottom sheets and dialogs
✅ ListView with custom widgets
✅ TextField and input handling
✅ Checkbox functionality
✅ Using const for performance
This is a portfolio-ready project! 🎉
💬 Your Turn!
Now it's time to build and customize!
Share with me:
- Screenshot of your completed app
- What feature did you add?
- Any challenges you faced?
- What will you build next?
Comment below! I reply to everyone! 😊
🚀 Coming Up Next
In my next post, I'll cover:
"Flutter Weather App with API Integration - Live Data Tutorial"
We'll fetch real weather data from APIs and display it beautifully!
🎯 Challenge
Weekend Challenge:
- Build this Todo app
- Add one custom feature
- Share screenshot in comments
- I'll feature the best 3!
Deadline: Sunday midnight
Prize: Feature in next post + shoutout! 🏆
❓ FAQs
Q: Do I need to know advanced Flutter?
A: No! This tutorial is beginner-friendly.
Q: Will data be lost if I uninstall the app?
A: Yes, local storage clears on uninstall. Use cloud storage (Firebase) to persist.
Q: Can I publish this to Play Store?
A: Absolutely! It's a complete, functional app.
Q: How do I add more features?
A: Check the "Next Steps" section for enhancement ideas!
Q: Is this production-ready?
A: Yes! Add error handling and polish for production.
📚 Resources
Learn More:
My Previous Posts:
🎊 Final Thoughts
You just built a real, working app! That's huge! 🎉
Remember:
- Every expert started as a beginner
- Practice beats perfection
- Share your progress
- Help others learn
Keep coding, keep building! 💪
Happy Coding! 🚀
Vikul Tyagi
Building Flutter apps, one project at a time
Don't forget to:
- 🔖 Bookmark this tutorial
- 📢 Share with Flutter learners
- 💬 Comment your app screenshot
- ⭐ Star the GitHub repo
- 🔔 Subscribe for more tutorials
P.S. - Stuck somewhere? Comment with your error message, and I'll help you debug! I read every comment! 😊
Amazing Explain
ReplyDeleteThank you
DeleteAmazing 😍 explanation
ReplyDeleteThank you
DeleteNice Vikul
ReplyDeleteThank you
DeleteAmazing 😍 explanation
ReplyDeleteThank you
Delete