Flutter Basics
Project Structure
Section titled “Project Structure”Standard Flutter project organization for maintainability.
lib/├── main.dart # App entry point├── models/ # Data models/classes├── widgets/ # Reusable widgets├── screens/ # Full page widgets├── services/ # API services, database├── utils/ # Helper functions, constants├── providers/ # State management providers└── themes/ # App themes, stylingWidgets
Section titled “Widgets”Stateless Widget
Section titled “Stateless Widget”Widget that doesn’t require mutable state.
class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); }}Stateful Widget
Section titled “Stateful Widget”Widget that maintains mutable state.
class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState();}
class _MyWidgetState extends State<MyWidget> { @override Widget build(BuildContext context) { return Container(); }}Basic Widgets
Section titled “Basic Widgets”Commonly used built-in widgets.
Container() # Box with decoration, padding, marginsColumn() # Vertical layout of childrenRow() # Horizontal layout of childrenStack() # Overlapping children layoutListView() # Scrollable listGridView() # Scrollable gridText() # Display textImage() # Display imagesIcon() # Display iconsButton() # Various button typesTextField() # Text inputState Management
Section titled “State Management”setState (Local State)
Section titled “setState (Local State)”Simple state management for local widget state.
int _counter = 0;
void _incrementCounter() { setState(() { _counter++; });}Provider (Recommended)
Section titled “Provider (Recommended)”Simple yet powerful state management solution.
// Provider setupChangeNotifierProvider(create: (_) => MyModel()),
// Consumer usageConsumer<MyModel>( builder: (context, model, child) => Text(model.value),)
// Provider.of usagevar model = Provider.of<MyModel>(context);Riverpod (Provider 2.0)
Section titled “Riverpod (Provider 2.0)”Improved provider pattern with compile-time safety.
final counterProvider = StateProvider<int>((ref) => 0);
class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final count = ref.watch(counterProvider); return Text('$count'); }}Navigation
Section titled “Navigation”Basic Navigation
Section titled “Basic Navigation”Navigate between screens.
// Push new screenNavigator.push(context, MaterialPageRoute(builder: (_) => SecondScreen()));
// Push with argumentsNavigator.pushNamed(context, '/details', arguments: 'data');
// Pop screenNavigator.pop(context);
// Push and remove untilNavigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => HomeScreen()), (route) => false);Named Routes
Section titled “Named Routes”Declare and use named routes.
// MaterialApp setupMaterialApp( routes: { '/': (context) => HomeScreen(), '/details': (context) => DetailsScreen(), },)
// NavigationNavigator.pushNamed(context, '/details');GoRouter (Advanced)
Section titled “GoRouter (Advanced)”Declarative routing package.
final _router = GoRouter( routes: [ GoRoute(path: '/', builder: (context, state) => HomeScreen()), GoRoute(path: '/details', builder: (context, state) => DetailsScreen()), ],);HTTP & APIs
Section titled “HTTP & APIs”http Package
Section titled “http Package”Make HTTP requests to APIs.
import 'package:http/http.dart' as http;
// GET requestvar response = await http.get(Uri.parse('https://api.example.com/data'));
// POST requestvar response = await http.post( Uri.parse('https://api.example.com/data'), body: {'key': 'value'},);
// Handle responseif (response.statusCode == 200) { var data = jsonDecode(response.body);}Dio (Advanced HTTP)
Section titled “Dio (Advanced HTTP)”Powerful HTTP client with interceptors.
var dio = Dio();var response = await dio.get('https://api.example.com/data');JSON Serialization
Section titled “JSON Serialization”Convert JSON to Dart objects.
// Model classclass User { final String name; final int age;
User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) { return User( name: json['name'], age: json['age'], ); }
Map<String, dynamic> toJson() => { 'name': name, 'age': age, };}
// Usagevar user = User.fromJson(jsonDecode(response.body));var json = jsonEncode(user.toJson());Forms & Validation
Section titled “Forms & Validation”Form Widget
Section titled “Form Widget”Create and validate forms.
final _formKey = GlobalKey<FormState>();final _nameController = TextEditingController();
Form( key: _formKey, child: Column( children: [ TextFormField( controller: _nameController, validator: (value) { if (value!.isEmpty) return 'Please enter name'; return null; }, ), ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { // Form is valid } }, child: Text('Submit'), ), ], ),)Local Storage
Section titled “Local Storage”Shared Preferences
Section titled “Shared Preferences”Store simple key-value pairs.
final prefs = await SharedPreferences.getInstance();await prefs.setString('key', 'value');var value = prefs.getString('key');SQLite (sqflite)
Section titled “SQLite (sqflite)”Local relational database.
var database = await openDatabase('my_db.db');await database.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)');Hive (NoSQL)
Section titled “Hive (NoSQL)”Lightweight and fast key-value database.
await Hive.openBox('myBox');var box = Hive.box('myBox');box.put('key', 'value');var value = box.get('key');Theming & Styling
Section titled “Theming & Styling”MaterialApp Theme
Section titled “MaterialApp Theme”Define app-wide theme.
MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, brightness: Brightness.light, textTheme: TextTheme(bodyText2: TextStyle(fontSize: 16)), ), darkTheme: ThemeData(brightness: Brightness.dark),)Custom Themes
Section titled “Custom Themes”Create reusable theme data.
class AppThemes { static final light = ThemeData.light().copyWith( primaryColor: Colors.blue, accentColor: Colors.orange, );
static final dark = ThemeData.dark().copyWith( primaryColor: Colors.blueGrey, accentColor: Colors.amber, );}Animations
Section titled “Animations”Implicit Animations
Section titled “Implicit Animations”Simple built-in animations.
AnimatedContainer( duration: Duration(seconds: 1), width: _expanded ? 200 : 100, height: _expanded ? 200 : 100,)
AnimatedOpacity( opacity: _visible ? 1.0 : 0.0, duration: Duration(seconds: 1),)Explicit Animations
Section titled “Explicit Animations”Custom controlled animations.
AnimationController( duration: Duration(seconds: 2), vsync: this,);
Animation<double> animation = CurvedAnimation( parent: _controller, curve: Curves.easeIn,);Platform Specific
Section titled “Platform Specific”Platform Detection
Section titled “Platform Detection”Check which platform app is running on.
import 'dart:io';
if (Platform.isIOS) { // iOS specific code} else if (Platform.isAndroid) { // Android specific code}Platform Channels
Section titled “Platform Channels”Communicate with native code.
// Flutter sidestatic const platform = MethodChannel('com.example/app');var result = await platform.invokeMethod('nativeMethod');
// Native side (Android/iOS)// Implement method channel handlerTesting
Section titled “Testing”Widget Tests
Section titled “Widget Tests”Test individual widgets.
testWidgets('Widget test', (WidgetTester tester) async { await tester.pumpWidget(MyApp()); expect(find.text('Hello'), findsOneWidget);});Unit Tests
Section titled “Unit Tests”Test business logic.
test('Unit test', () { expect(1 + 1, 2);});Integration Tests
Section titled “Integration Tests”Test complete app flows.
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Integration test', (tester) async { await tester.pumpWidget(MyApp()); // Test complete user flows});Debugging
Section titled “Debugging”Common Debugging
Section titled “Common Debugging”Essential debugging techniques.
print('Debug message'); # Console outputdebugPrint('Message'); # Flutter debug printassert(condition); # Runtime assertions
# DevTools - Flutter's debugging suite# flutter run --debug# Open DevTools in browserLogging
Section titled “Logging”Structured logging.
import 'package:logger/logger.dart';
var logger = Logger();logger.d('Debug message');logger.i('Info message');logger.w('Warning message');logger.e('Error message');Performance
Section titled “Performance”Performance Best Practices
Section titled “Performance Best Practices”Tips for smooth app performance.
// Use const constructorsconst Text('Hello')
// Avoid rebuilds with const widgetsconst MyWidget()
// Use ListView.builder for long listsListView.builder( itemCount: items.length, itemBuilder: (context, index) => ListTile(title: Text(items[index])),)
// Use keys wiselyKey('unique_key')
// Profile app performance# flutter run --profilePackages
Section titled “Packages”Essential Packages
Section titled “Essential Packages”Must-have packages for Flutter development.
dependencies: provider: ^6.0.0 # State management http: ^0.13.0 # HTTP requests shared_preferences: ^2.0.0 # Local storage hive: ^2.0.0 # NoSQL database flutter_hooks: ^0.18.0 # React hooks pattern go_router: ^5.0.0 # Declarative routing cached_network_image: ^3.0.0 # Image caching intl: ^0.17.0 # Internationalization flutter_bloc: ^8.0.0 # BLoC pattern riverpod: ^1.0.0 # Provider 2.0Dev Dependencies
Section titled “Dev Dependencies”Development and testing packages.
dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^2.0.0 build_runner: ^2.0.0 json_serializable: ^6.0.0 hive_generator: ^1.0.0Useful Commands
Section titled “Useful Commands”Flutter CLI
Section titled “Flutter CLI”Essential Flutter commands.
flutter create project_name # Create new projectflutter run # Run appflutter build apk # Build Android APKflutter build ios # Build iOS appflutter test # Run testsflutter pub get # Get packagesflutter clean # Clean projectflutter doctor # Check Flutter installation