A comprehensive template for building mobile applications using Context Engineering principles - the discipline of providing comprehensive context to AI assistants so they can build robust, production-ready mobile solutions.
# 1. Clone this template
git clone https://github.com/your-username/mobile-context-engineering.git
cd mobile-context-engineering
# 2. Set up Flutter environment
flutter doctor
flutter pub get
# 3. Set up Python environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements/backend.txt
# 4. Configure your environment
cp .env.example .env
# Edit .env with your API keys, database URLs, etc.
# 5. Set up your project rules (optional - template provided)
# Edit MOBILE_RULES.md to add your project-specific guidelines
# 6. Add examples (highly recommended)
# Place relevant mobile code examples in the examples/ folder
# 7. Create your initial feature request
# Edit INITIAL.md with your mobile app feature requirements
# 8. Generate a comprehensive Mobile Implementation Plan (MIP)
# In Claude Code, run:
/generate-mip INITIAL.md
# 9. Execute the MIP to implement your feature
# In Claude Code, run:
/execute-mip MIPs/your-feature-name.mdmobile-context-engineering/
├── .claude/
│ ├── commands/
│ │ ├── generate-mip.md # Generates Mobile Implementation Plans
│ │ └── execute-mip.md # Executes MIPs to implement features
│ └── settings.local.json # Claude Code permissions
├── MIPs/ # Mobile Implementation Plans
│ ├── templates/
│ │ └── mip_base.md # Base template for MIPs
│ └── EXAMPLE_social_app.md # Example of a complete MIP
├── examples/ # Your mobile code examples (critical!)
│ ├── flutter/
│ │ ├── README.md # Flutter patterns documentation
│ │ ├── widgets/ # Custom widget examples
│ │ ├── screens/ # Screen implementation patterns
│ │ ├── state_management/ # Provider/Riverpod/Bloc patterns
│ │ ├── services/ # API clients, local storage
│ │ └── utils/ # Helper functions, extensions
│ ├── python/
│ │ ├── README.md # Python backend patterns
│ │ ├── apis/ # FastAPI/Flask examples
│ │ ├── database/ # SQLite models and migrations
│ │ ├── auth/ # Authentication systems
│ │ └── services/ # Backend service patterns
│ ├── integration/ # Full-stack integration examples
│ └── tests/ # Testing patterns for mobile apps
│ ├── README.md # Testing documentation
│ ├── flutter_tests/ # Flutter testing patterns
│ ├── python_tests/ # Python testing patterns
│ └── integration_tests/ # End-to-end testing
├── requirements/ # Dependencies for different platforms
│ ├── flutter.yaml # Flutter dependencies
│ ├── backend.txt # Python backend requirements
│ └── development.txt # Development tools
├── MOBILE_RULES.md # Global rules for mobile development
├── INITIAL.md # Template for feature requests
├── INITIAL_EXAMPLE.md # Example mobile feature request
├── .env.example # Environment variable template
└── README.md # This file
Context Engineering for Mobile Apps represents a systematic approach to building mobile applications:
Traditional Approach:
- Write individual Flutter widgets without clear patterns
- Limited documentation and examples
- Inconsistent state management and API integration
- Like building with random building blocks
Context Engineering Approach:
- Comprehensive system with patterns, examples, and validation
- Consistent architecture across all mobile components
- Self-correcting implementation with testing
- Like having a detailed blueprint with all components organized
- Reduces Implementation Failures: Most mobile app failures come from missing context about proper patterns
- Ensures Best Practices: Follow Flutter and mobile development recommended patterns
- Enables Complex Applications: Build multi-feature mobile apps with proper context
- Self-Validating: Built-in testing ensures your mobile components work correctly
- Cross-Platform Consistency: Maintain consistency across Android and iOS
The MOBILE_RULES.md file contains project-wide rules for mobile development:
- Flutter Patterns: Widget composition, state management, navigation
- Backend Integration: API clients, data models, error handling
- Database Design: SQLite patterns, migrations, offline sync
- State Management: Provider/Riverpod/Bloc patterns and best practices
- Testing Requirements: Unit tests, widget tests, integration tests
- Performance: Optimization strategies, memory management
Place relevant mobile code examples in the examples/ folder:
examples/
├── flutter/
│ ├── widgets/
│ │ ├── custom_button.dart # Reusable button component
│ │ ├── data_list_view.dart # List view with pagination
│ │ └── form_field_wrapper.dart # Form input wrapper
│ ├── screens/
│ │ ├── login_screen.dart # Authentication screen
│ │ ├── home_screen.dart # Main dashboard
│ │ └── profile_screen.dart # User profile management
│ ├── state_management/
│ │ ├── provider_example.dart # Provider pattern
│ │ ├── riverpod_example.dart # Riverpod pattern
│ │ └── bloc_example.dart # Bloc pattern
│ └── services/
│ ├── api_client.dart # HTTP client wrapper
│ ├── local_storage.dart # Local storage service
│ └── auth_service.dart # Authentication service
├── python/
│ ├── apis/
│ │ ├── user_api.py # User management endpoints
│ │ ├── auth_api.py # Authentication endpoints
│ │ └── data_api.py # Data management endpoints
│ ├── database/
│ │ ├── models.py # SQLite models
│ │ ├── migrations.py # Database migrations
│ │ └── database.py # Database connection
│ └── services/
│ ├── auth_service.py # Backend auth logic
│ ├── data_service.py # Business logic
│ └── notification_service.py # Push notifications
└── integration/
├── api_integration.dart # Frontend-backend integration
├── offline_sync.dart # Offline data synchronization
└── real_time_updates.dart # WebSocket/real-time features
Edit INITIAL.md to describe your mobile app feature:
## FEATURE:
[Describe the mobile app feature you want to build]
## TECHNOLOGY STACK:
[List specific technologies: Flutter widgets, Python APIs, SQLite tables, etc.]
## EXAMPLES:
[Reference example files and explain patterns to follow]
## DOCUMENTATION:
[Include Flutter docs, API references, design patterns]
## TESTING REQUIREMENTS:
[Specify how to test widgets, APIs, and integrations]
## OTHER CONSIDERATIONS:
[Platform-specific requirements, performance needs, offline support]Run the generator in Claude Code:
/generate-mip INITIAL.mdThis will:
- Analyze your codebase for mobile development patterns
- Research Flutter and mobile development best practices
- Create a comprehensive implementation plan in
MIPs/your-feature-name.md - Include validation steps specific to mobile development
Run the executor in Claude Code:
/execute-mip MIPs/your-feature-name.mdThe system will:
- Read all context from the MIP
- Implement mobile components step by step
- Run validation tests for widgets and APIs
- Ensure all mobile development best practices are followed
// Example from examples/flutter/widgets/custom_button.dart
class CustomButton extends StatelessWidget {
final String text;
final VoidCallback? onPressed;
final bool isLoading;
const CustomButton({
Key? key,
required this.text,
this.onPressed,
this.isLoading = false,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: isLoading ? null : onPressed,
child: isLoading
? CircularProgressIndicator()
: Text(text),
);
}
}// Example from examples/flutter/state_management/provider_example.dart
class UserProvider extends ChangeNotifier {
User? _user;
bool _isLoading = false;
User? get user => _user;
bool get isLoading => _isLoading;
Future<void> loadUser(String userId) async {
_isLoading = true;
notifyListeners();
try {
_user = await ApiService.getUser(userId);
} catch (e) {
// Handle error
} finally {
_isLoading = false;
notifyListeners();
}
}
}# Example from examples/python/apis/user_api.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import User
router = APIRouter()
@router.get("/users/{user_id}")
async def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user// Example from examples/tests/flutter_tests/widget_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/widgets/custom_button.dart';
void main() {
group('CustomButton Tests', () {
testWidgets('should display text correctly', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: CustomButton(text: 'Test Button'),
),
);
expect(find.text('Test Button'), findsOneWidget);
});
testWidgets('should show loading indicator when loading', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: CustomButton(text: 'Test', isLoading: true),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
});
}# .env.example
# Flutter/Mobile Configuration
FLUTTER_ENV=development
API_BASE_URL=http://localhost:8000
WEBSOCKET_URL=ws://localhost:8000/ws
# Backend Configuration
DATABASE_URL=sqlite:///./app.db
SECRET_KEY=your-secret-key-here
JWT_SECRET=your-jwt-secret-here
# Third-party Services
FIREBASE_PROJECT_ID=your-firebase-project
GOOGLE_MAPS_API_KEY=your-maps-key
STRIPE_PUBLISHABLE_KEY=your-stripe-key
STRIPE_SECRET_KEY=your-stripe-secret
# Push Notifications
FCM_SERVER_KEY=your-fcm-server-key
APNS_KEY_ID=your-apns-key-id
APNS_TEAM_ID=your-apns-team-id
# Development
DEBUG=true
LOG_LEVEL=debug# requirements/flutter.yaml
dependencies:
flutter:
sdk: flutter
provider: ^6.0.5
riverpod: ^2.4.9
flutter_riverpod: ^2.4.9
dio: ^5.3.2
sqflite: ^2.3.0
shared_preferences: ^2.2.2
firebase_core: ^2.24.2
firebase_messaging: ^14.7.10
camera: ^0.10.5+5
image_picker: ^1.0.4
cached_network_image: ^3.3.0
flutter_secure_storage: ^9.0.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.4.2
integration_test:
sdk: flutter
flutter_driver:
sdk: flutter# requirements/backend.txt
fastapi==0.104.1
uvicorn==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
pydantic==2.5.0
python-jose==3.3.0
passlib==1.7.4
python-multipart==0.0.6
python-dotenv==1.0.0
pytest==7.4.3
pytest-asyncio==0.21.1
httpx==0.25.2# Install Flutter SDK
# Follow official Flutter installation guide
flutter doctor
# Get dependencies
flutter pub get
# Run on device/emulator
flutter run# Create virtual environment
python -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements/backend.txt
# Run database migrations
alembic upgrade head
# Start development server
uvicorn main:app --reload# Initialize SQLite database
python scripts/init_db.py
# Run migrations
alembic upgrade head
# Seed test data (optional)
python scripts/seed_data.py// WebSocket integration example
class WebSocketService {
late IOWebSocketChannel channel;
void connect() {
channel = IOWebSocketChannel.connect('ws://localhost:8000/ws');
channel.stream.listen((message) {
// Handle incoming messages
handleMessage(jsonDecode(message));
});
}
void sendMessage(Map<String, dynamic> message) {
channel.sink.add(jsonEncode(message));
}
}// Offline data synchronization
class OfflineSync {
static const String _pendingKey = 'pending_operations';
Future<void> queueOperation(Operation operation) async {
final prefs = await SharedPreferences.getInstance();
List<String> pending = prefs.getStringList(_pendingKey) ?? [];
pending.add(jsonEncode(operation.toJson()));
await prefs.setStringList(_pendingKey, pending);
}
Future<void> syncPendingOperations() async {
if (await hasInternetConnection()) {
final pending = await getPendingOperations();
for (final operation in pending) {
await executeOperation(operation);
}
await clearPendingOperations();
}
}
}# Backend push notification service
from firebase_admin import messaging
class NotificationService:
@staticmethod
async def send_notification(user_tokens: List[str], title: str, body: str):
message = messaging.MulticastMessage(
notification=messaging.Notification(title=title, body=body),
tokens=user_tokens,
)
response = messaging.send_multicast(message)
return responseThe template includes comprehensive testing patterns:
- Unit Tests: Test individual widgets and business logic
- Widget Tests: Test UI components in isolation
- Integration Tests: Test complete user workflows
- API Tests: Test backend endpoints and database operations
- Performance Tests: Validate app performance and memory usage
- Follow the established patterns in the examples/ folder
- Add comprehensive tests for new features
- Update documentation for new mobile components
- Ensure all validation steps pass
MIT License - feel free to use this template for your mobile app projects!