Flutter Interview Questions
41 questions with detailed answers
Question:
What are the advantages of Flutter?
Answer:
Advantages of Flutter:\n\n• Cross-platform development\n• Single codebase for multiple platforms\n• Fast development with hot reload\n• Native performance\n• Rich UI widgets\n• Strong community support\n• Backed by Google
Question:
Explain the difference between StatelessWidget and StatefulWidget.
Answer:
StatelessWidget vs StatefulWidget:\n\n**StatelessWidget:**\n• Immutable widget\n• Cannot change state\n• Rebuilt when parent changes\n• Used for static content\n\n**StatefulWidget:**\n• Mutable widget\n• Can change state using setState()\n• Has lifecycle methods\n• Used for dynamic content\n• Maintains state across rebuilds
Question:
How do you install Flutter?
Answer:
Flutter installation steps:\n\n1. **Download Flutter SDK** from official website\n2. **Extract** the zip file to desired location\n3. **Add Flutter to PATH** environment variable\n4. **Run flutter doctor** to check dependencies\n5. **Install Android Studio** or VS Code\n6. **Install Flutter plugin** in IDE\n7. **Set up Android SDK** and emulator\n8. **Verify installation** with flutter doctor
Question:
What are the advantages of Flutter?
Answer:
Advantages of Flutter:\n\n• Cross-platform development\n• Single codebase for multiple platforms\n• Fast development with hot reload\n• Native performance\n• Rich UI widgets\n• Strong community support\n• Backed by Google
Question:
Explain the difference between StatelessWidget and StatefulWidget.
Answer:
StatelessWidget vs StatefulWidget:\n\n**StatelessWidget:**\n• Immutable widget\n• Cannot change state\n• Rebuilt when parent changes\n• Used for static content\n\n**StatefulWidget:**\n• Mutable widget\n• Can change state using setState()\n• Has lifecycle methods\n• Used for dynamic content\n• Maintains state across rebuilds
Question:
How do you install Flutter?
Answer:
Flutter installation steps:\n\n1. **Download Flutter SDK** from official website\n2. **Extract** the zip file to desired location\n3. **Add Flutter to PATH** environment variable\n4. **Run flutter doctor** to check dependencies\n5. **Install Android Studio** or VS Code\n6. **Install Flutter plugin** in IDE\n7. **Set up Android SDK** and emulator\n8. **Verify installation** with flutter doctor
Question:
Explain Flutter widget lifecycle methods.
Answer:
Flutter StatefulWidget lifecycle methods:\n\n**createState()** - Creates mutable state\n**initState()** - Called once when widget inserted\n**didChangeDependencies()** - Called when dependencies change\n**build()** - Builds widget UI (called multiple times)\n**didUpdateWidget()** - Called when widget configuration changes\n**setState()** - Triggers rebuild\n**deactivate()** - Called when widget removed from tree\n**dispose()** - Called when widget permanently removed\n\n**Order:**\ncreateState() → initState() → didChangeDependencies() → build() → dispose()
Question:
How does navigation work in Flutter?
Answer:
Flutter navigation system:\n\n**Navigator class:**\n• Manages stack of routes\n• Push/pop operations\n• Named routes support\n\n**Basic navigation:**\n\n// Push new screen\nNavigator.push(context, MaterialPageRoute(\n builder: (context) => SecondScreen()\n));\n\n// Pop current screen\nNavigator.pop(context);\n\n\n**Named routes:**\n\n// Define routes\nroutes: {\n '/second': (context) => SecondScreen(),\n}\n\n// Navigate\nNavigator.pushNamed(context, '/second');\n\n\n**Passing data:**\n• Constructor parameters\n• Route arguments\n• Return values from pop()
Question:
What are Flutter layouts and how to use them?
Answer:
Flutter layout widgets:\n\n**Single child layouts:**\n• Container - Padding, margin, decoration\n• Center - Centers child widget\n• Align - Aligns child within parent\n• Padding - Adds padding around child\n\n**Multi-child layouts:**\n• Column - Vertical arrangement\n• Row - Horizontal arrangement\n• Stack - Overlapping widgets\n• Wrap - Wraps children to new line\n\n**Flexible layouts:**\n• Expanded - Takes available space\n• Flexible - Flexible space allocation\n• Flex - Custom flex layouts\n\n**Example:**\n\nColumn(\n children: [\n Text('Title'),\n Expanded(child: ListView(...)),\n ElevatedButton(...)\n ]\n)\n
Question:
Explain state management in Flutter.
Answer:
Flutter state management approaches:\n\n**Built-in solutions:**\n• setState() - Local widget state\n• InheritedWidget - Share data down tree\n• ValueNotifier - Simple reactive state\n\n**Popular packages:**\n• Provider - Dependency injection and state\n• Bloc - Business logic separation\n• Riverpod - Modern provider alternative\n• GetX - Complete solution\n• MobX - Reactive state management\n\n**Provider example:**\n\nclass Counter extends ChangeNotifier {\n int _count = 0;\n int get count => _count;\n \n void increment() {\n _count++;\n notifyListeners();\n }\n}\n\n// Usage\nConsumer(\n builder: (context, counter, child) {\n return Text('${counter.count}');\n }\n)\n
Question:
How to handle user input in Flutter?
Answer:
Flutter user input handling:\n\n**Text input:**\n\nTextField(\n controller: _controller,\n decoration: InputDecoration(\n labelText: 'Enter text',\n border: OutlineInputBorder()\n ),\n onChanged: (value) => print(value)\n)\n\n\n**Form validation:**\n\nForm(\n key: _formKey,\n child: TextFormField(\n validator: (value) {\n if (value?.isEmpty ?? true) {\n return 'Please enter text';\n }\n return null;\n }\n )\n)\n\n\n**Gesture detection:**\n\nGestureDetector(\n onTap: () => print('Tapped'),\n onLongPress: () => print('Long pressed'),\n child: Container(...)\n)\n\n\n**Button handling:**\n• ElevatedButton, TextButton, IconButton\n• onPressed callback\n• Disabled state when onPressed is null
Question:
What are Flutter animations and how to implement them?
Answer:
Flutter animation system:\n\n**Animation types:**\n• Implicit animations - Automatic transitions\n• Explicit animations - Manual control\n• Hero animations - Shared element transitions\n\n**Implicit animations:**\n\nAnimatedContainer(\n duration: Duration(seconds: 1),\n width: _isExpanded ? 200 : 100,\n height: _isExpanded ? 200 : 100,\n color: _isExpanded ? Colors.blue : Colors.red\n)\n\n\n**Explicit animations:**\n\nclass _MyWidgetState extends State \n with SingleTickerProviderStateMixin {\n AnimationController _controller;\n Animation _animation;\n \n @override\n void initState() {\n _controller = AnimationController(\n duration: Duration(seconds: 2),\n vsync: this\n );\n _animation = Tween(\n begin: 0.0,\n end: 1.0\n ).animate(_controller);\n }\n}\n\n\n**Common animated widgets:**\n• AnimatedOpacity, AnimatedPositioned\n• AnimatedBuilder, FadeTransition\n• SlideTransition, ScaleTransition
Question:
How to make HTTP requests in Flutter?
Answer:
Flutter HTTP requests:\n\n**Using http package:**\n\nimport 'package:http/http.dart' as http;\n\n// GET request\nFuture fetchData() async {\n final response = await http.get(\n Uri.parse('https://api.example.com/data')\n );\n \n if (response.statusCode == 200) {\n return response.body;\n } else {\n throw Exception('Failed to load data');\n }\n}\n\n// POST request\nFuture postData(Map data) async {\n final response = await http.post(\n Uri.parse('https://api.example.com/data'),\n headers: {'Content-Type': 'application/json'},\n body: jsonEncode(data)\n );\n return response.body;\n}\n\n\n**Using FutureBuilder:**\n\nFutureBuilder(\n future: fetchData(),\n builder: (context, snapshot) {\n if (snapshot.hasData) {\n return Text(snapshot.data!);\n } else if (snapshot.hasError) {\n return Text('Error: ${snapshot.error}');\n }\n return CircularProgressIndicator();\n }\n)\n
Question:
Explain Flutter themes and styling.
Answer:
Flutter themes and styling:\n\n**ThemeData:**\n\nMaterialApp(\n theme: ThemeData(\n primarySwatch: Colors.blue,\n accentColor: Colors.orange,\n fontFamily: 'Roboto',\n textTheme: TextTheme(\n headline1: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)\n )\n )\n)\n\n\n**Custom themes:**\n\nThemeData.light().copyWith(\n primaryColor: Colors.purple,\n buttonTheme: ButtonThemeData(\n buttonColor: Colors.purple,\n textTheme: ButtonTextTheme.primary\n )\n)\n\n\n**Using themes:**\n\n// Access theme\nfinal theme = Theme.of(context);\nText(\n 'Styled text',\n style: theme.textTheme.headline1\n)\n\n\n**Dark theme:**\n\nMaterialApp(\n theme: ThemeData.light(),\n darkTheme: ThemeData.dark(),\n themeMode: ThemeMode.system\n)\n\n\n**Custom styling:**\n• TextStyle for text appearance\n• BoxDecoration for containers\n• Material Design components
Question:
How to handle device orientation in Flutter?
Answer:
Flutter device orientation handling:\n\n**Detect orientation:**\n\n@override\nWidget build(BuildContext context) {\n final orientation = MediaQuery.of(context).orientation;\n \n if (orientation == Orientation.portrait) {\n return PortraitLayout();\n } else {\n return LandscapeLayout();\n }\n}\n\n\n**OrientationBuilder:**\n\nOrientationBuilder(\n builder: (context, orientation) {\n return GridView.count(\n crossAxisCount: orientation == Orientation.portrait ? 2 : 4,\n children: widgets\n );\n }\n)\n\n\n**Lock orientation:**\n\nimport 'package:flutter/services.dart';\n\n// Lock to portrait\nSystemChrome.setPreferredOrientations([\n DeviceOrientation.portraitUp,\n DeviceOrientation.portraitDown\n]);\n\n// Allow all orientations\nSystemChrome.setPreferredOrientations([\n DeviceOrientation.portraitUp,\n DeviceOrientation.portraitDown,\n DeviceOrientation.landscapeLeft,\n DeviceOrientation.landscapeRight\n]);\n\n\n**Responsive design:**\n• Use MediaQuery for screen dimensions\n• Flexible and Expanded widgets\n• LayoutBuilder for custom layouts
Question:
What is Flutter plugin development?
Answer:
Flutter plugin development:\n\n**Plugin types:**\n• Platform plugins - Access native APIs\n• Dart plugins - Pure Dart packages\n• Federated plugins - Multi-platform support\n\n**Create plugin:**\nbash\nflutter create --template=plugin my_plugin\n\n\n**Plugin structure:**\n\nmy_plugin/\n lib/my_plugin.dart # Dart API\n android/ # Android implementation\n ios/ # iOS implementation\n example/ # Example app\n\n\n**Method channel:**\n\n// Dart side\nclass MyPlugin {\n static const MethodChannel _channel = MethodChannel('my_plugin');\n \n static Future getPlatformVersion() async {\n final String version = await _channel.invokeMethod('getPlatformVersion');\n return version;\n }\n}\n\n\n**Android implementation:**\nkotlin\nclass MyPlugin: FlutterPlugin, MethodCallHandler {\n override fun onMethodCall(call: MethodCall, result: Result) {\n when (call.method) {\n \"getPlatformVersion\" -> {\n result.success(\"Android ${android.os.Build.VERSION.RELEASE}\")\n }\n }\n }\n}\n\n\n**Publishing:**\n• Add to pub.dev\n• Follow pub.dev guidelines\n• Include documentation
Question:
How to implement local storage in Flutter?
Answer:
Flutter local storage options:\n\n**SharedPreferences:**\n\nimport 'package:shared_preferences/shared_preferences.dart';\n\n// Save data\nFuture saveData() async {\n final prefs = await SharedPreferences.getInstance();\n await prefs.setString('username', 'john_doe');\n await prefs.setInt('age', 25);\n await prefs.setBool('isLoggedIn', true);\n}\n\n// Read data\nFuture getData() async {\n final prefs = await SharedPreferences.getInstance();\n return prefs.getString('username');\n}\n\n\n**SQLite database:**\n\nimport 'package:sqflite/sqflite.dart';\n\nclass DatabaseHelper {\n static Future _database() async {\n return openDatabase(\n 'my_database.db',\n version: 1,\n onCreate: (db, version) {\n return db.execute(\n 'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)'\n );\n }\n );\n }\n \n static Future insertUser(User user) async {\n final db = await _database();\n await db.insert('users', user.toMap());\n }\n}\n\n\n**File storage:**\n\nimport 'dart:io';\nimport 'package:path_provider/path_provider.dart';\n\nFuture writeFile(String data) async {\n final directory = await getApplicationDocumentsDirectory();\n final file = File('${directory.path}/data.txt');\n return file.writeAsString(data);\n}\n\n\n**Hive (NoSQL):**\n• Fast key-value database\n• Type-safe\n• No native dependencies
Question:
Explain Flutter testing strategies.
Answer:
Flutter testing strategies:\n\n**Test types:**\n• Unit tests - Test individual functions/classes\n• Widget tests - Test widget behavior\n• Integration tests - Test complete app flow\n\n**Unit testing:**\n\nimport 'package:flutter_test/flutter_test.dart';\n\nvoid main() {\n group('Calculator', () {\n test('should add two numbers', () {\n final calculator = Calculator();\n expect(calculator.add(2, 3), equals(5));\n });\n });\n}\n\n\n**Widget testing:**\n\nvoid main() {\n testWidgets('Counter increments smoke test', (WidgetTester tester) async {\n await tester.pumpWidget(MyApp());\n \n expect(find.text('0'), findsOneWidget);\n expect(find.text('1'), findsNothing);\n \n await tester.tap(find.byIcon(Icons.add));\n await tester.pump();\n \n expect(find.text('0'), findsNothing);\n expect(find.text('1'), findsOneWidget);\n });\n}\n\n\n**Integration testing:**\n\nvoid main() {\n group('App', () {\n testWidgets('full app test', (tester) async {\n app.main();\n await tester.pumpAndSettle();\n \n // Test complete user flow\n await tester.tap(find.byKey(Key('login_button')));\n await tester.pumpAndSettle();\n \n expect(find.text('Welcome'), findsOneWidget);\n });\n });\n}\n\n\n**Mocking:**\n• Use mockito package\n• Mock HTTP requests\n• Mock platform channels
Question:
How to optimize Flutter app performance?
Answer:
Flutter performance optimization:\n\n**Widget optimization:**\n• Use const constructors\n• Avoid rebuilding expensive widgets\n• Use RepaintBoundary for complex widgets\n• Implement shouldRebuild in custom widgets\n\n**List optimization:**\n\n// Use ListView.builder for large lists\nListView.builder(\n itemCount: items.length,\n itemBuilder: (context, index) {\n return ListTile(title: Text(items[index]));\n }\n)\n\n// Use ListView.separated for dividers\nListView.separated(\n itemBuilder: (context, index) => ItemWidget(items[index]),\n separatorBuilder: (context, index) => Divider(),\n itemCount: items.length\n)\n\n\n**Image optimization:**\n• Use appropriate image formats\n• Implement image caching\n• Use Image.network with cacheWidth/cacheHeight\n• Compress images\n\n**Memory management:**\n• Dispose controllers and streams\n• Use weak references\n• Avoid memory leaks in listeners\n\n**Build optimization:**\n• Use --release mode for production\n• Enable code splitting\n• Tree shaking for smaller bundles\n• Profile app with Flutter Inspector\n\n**Animation optimization:**\n• Use Transform instead of changing layout\n• Prefer Opacity over rebuilding\n• Use RepaintBoundary for animations
Question:
What are Flutter design patterns?
Answer:
Flutter design patterns:\n\n**BLoC Pattern:**\n\nclass CounterBloc {\n final _counterController = StreamController();\n final _actionController = StreamController();\n \n Stream get counter => _counterController.stream;\n Sink get action => _actionController.sink;\n \n CounterBloc() {\n _actionController.stream.listen(_handleAction);\n }\n \n void _handleAction(CounterAction action) {\n if (action == CounterAction.increment) {\n _counterController.add(_currentCount + 1);\n }\n }\n}\n\n\n**Provider Pattern:**\n\nclass UserProvider extends ChangeNotifier {\n User? _user;\n User? get user => _user;\n \n void setUser(User user) {\n _user = user;\n notifyListeners();\n }\n}\n\n\n**Repository Pattern:**\n\nabstract class UserRepository {\n Future getUser(String id);\n Future saveUser(User user);\n}\n\nclass ApiUserRepository implements UserRepository {\n @override\n Future getUser(String id) async {\n // API implementation\n }\n}\n\n\n**Singleton Pattern:**\n\nclass ApiService {\n static final ApiService _instance = ApiService._internal();\n factory ApiService() => _instance;\n ApiService._internal();\n}\n\n\n**Factory Pattern:**\n• Create objects without specifying exact class\n• Useful for creating different widget types\n• Platform-specific implementations
Question:
Explain Flutter widget lifecycle methods.
Answer:
Flutter StatefulWidget lifecycle methods:\n\n**createState()** - Creates mutable state\n**initState()** - Called once when widget inserted\n**didChangeDependencies()** - Called when dependencies change\n**build()** - Builds widget UI (called multiple times)\n**didUpdateWidget()** - Called when widget configuration changes\n**setState()** - Triggers rebuild\n**deactivate()** - Called when widget removed from tree\n**dispose()** - Called when widget permanently removed\n\n**Order:**\ncreateState() → initState() → didChangeDependencies() → build() → dispose()
Question:
How does navigation work in Flutter?
Answer:
Flutter navigation system:\n\n**Navigator class:**\n• Manages stack of routes\n• Push/pop operations\n• Named routes support\n\n**Basic navigation:**\n\n// Push new screen\nNavigator.push(context, MaterialPageRoute(\n builder: (context) => SecondScreen()\n));\n\n// Pop current screen\nNavigator.pop(context);\n\n\n**Named routes:**\n\n// Define routes\nroutes: {\n '/second': (context) => SecondScreen(),\n}\n\n// Navigate\nNavigator.pushNamed(context, '/second');\n\n\n**Passing data:**\n• Constructor parameters\n• Route arguments\n• Return values from pop()
Question:
What are Flutter layouts and how to use them?
Answer:
Flutter layout widgets:\n\n**Single child layouts:**\n• Container - Padding, margin, decoration\n• Center - Centers child widget\n• Align - Aligns child within parent\n• Padding - Adds padding around child\n\n**Multi-child layouts:**\n• Column - Vertical arrangement\n• Row - Horizontal arrangement\n• Stack - Overlapping widgets\n• Wrap - Wraps children to new line\n\n**Flexible layouts:**\n• Expanded - Takes available space\n• Flexible - Flexible space allocation\n• Flex - Custom flex layouts\n\n**Example:**\n\nColumn(\n children: [\n Text('Title'),\n Expanded(child: ListView(...)),\n ElevatedButton(...)\n ]\n)\n
Question:
Explain state management in Flutter.
Answer:
Flutter state management approaches:\n\n**Built-in solutions:**\n• setState() - Local widget state\n• InheritedWidget - Share data down tree\n• ValueNotifier - Simple reactive state\n\n**Popular packages:**\n• Provider - Dependency injection and state\n• Bloc - Business logic separation\n• Riverpod - Modern provider alternative\n• GetX - Complete solution\n• MobX - Reactive state management\n\n**Provider example:**\n\nclass Counter extends ChangeNotifier {\n int _count = 0;\n int get count => _count;\n \n void increment() {\n _count++;\n notifyListeners();\n }\n}\n\n// Usage\nConsumer(\n builder: (context, counter, child) {\n return Text('${counter.count}');\n }\n)\n
Question:
How to handle user input in Flutter?
Answer:
Flutter user input handling:\n\n**Text input:**\n\nTextField(\n controller: _controller,\n decoration: InputDecoration(\n labelText: 'Enter text',\n border: OutlineInputBorder()\n ),\n onChanged: (value) => print(value)\n)\n\n\n**Form validation:**\n\nForm(\n key: _formKey,\n child: TextFormField(\n validator: (value) {\n if (value?.isEmpty ?? true) {\n return 'Please enter text';\n }\n return null;\n }\n )\n)\n\n\n**Gesture detection:**\n\nGestureDetector(\n onTap: () => print('Tapped'),\n onLongPress: () => print('Long pressed'),\n child: Container(...)\n)\n\n\n**Button handling:**\n• ElevatedButton, TextButton, IconButton\n• onPressed callback\n• Disabled state when onPressed is null
Question:
What are Flutter animations and how to implement them?
Answer:
Flutter animation system:\n\n**Animation types:**\n• Implicit animations - Automatic transitions\n• Explicit animations - Manual control\n• Hero animations - Shared element transitions\n\n**Implicit animations:**\n\nAnimatedContainer(\n duration: Duration(seconds: 1),\n width: _isExpanded ? 200 : 100,\n height: _isExpanded ? 200 : 100,\n color: _isExpanded ? Colors.blue : Colors.red\n)\n\n\n**Explicit animations:**\n\nclass _MyWidgetState extends State \n with SingleTickerProviderStateMixin {\n AnimationController _controller;\n Animation _animation;\n \n @override\n void initState() {\n _controller = AnimationController(\n duration: Duration(seconds: 2),\n vsync: this\n );\n _animation = Tween(\n begin: 0.0,\n end: 1.0\n ).animate(_controller);\n }\n}\n\n\n**Common animated widgets:**\n• AnimatedOpacity, AnimatedPositioned\n• AnimatedBuilder, FadeTransition\n• SlideTransition, ScaleTransition
Question:
How to make HTTP requests in Flutter?
Answer:
Flutter HTTP requests:\n\n**Using http package:**\n\nimport 'package:http/http.dart' as http;\n\n// GET request\nFuture fetchData() async {\n final response = await http.get(\n Uri.parse('https://api.example.com/data')\n );\n \n if (response.statusCode == 200) {\n return response.body;\n } else {\n throw Exception('Failed to load data');\n }\n}\n\n// POST request\nFuture postData(Map data) async {\n final response = await http.post(\n Uri.parse('https://api.example.com/data'),\n headers: {'Content-Type': 'application/json'},\n body: jsonEncode(data)\n );\n return response.body;\n}\n\n\n**Using FutureBuilder:**\n\nFutureBuilder(\n future: fetchData(),\n builder: (context, snapshot) {\n if (snapshot.hasData) {\n return Text(snapshot.data!);\n } else if (snapshot.hasError) {\n return Text('Error: ${snapshot.error}');\n }\n return CircularProgressIndicator();\n }\n)\n
Question:
Explain Flutter themes and styling.
Answer:
Flutter themes and styling:\n\n**ThemeData:**\n\nMaterialApp(\n theme: ThemeData(\n primarySwatch: Colors.blue,\n accentColor: Colors.orange,\n fontFamily: 'Roboto',\n textTheme: TextTheme(\n headline1: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)\n )\n )\n)\n\n\n**Custom themes:**\n\nThemeData.light().copyWith(\n primaryColor: Colors.purple,\n buttonTheme: ButtonThemeData(\n buttonColor: Colors.purple,\n textTheme: ButtonTextTheme.primary\n )\n)\n\n\n**Using themes:**\n\n// Access theme\nfinal theme = Theme.of(context);\nText(\n 'Styled text',\n style: theme.textTheme.headline1\n)\n\n\n**Dark theme:**\n\nMaterialApp(\n theme: ThemeData.light(),\n darkTheme: ThemeData.dark(),\n themeMode: ThemeMode.system\n)\n\n\n**Custom styling:**\n• TextStyle for text appearance\n• BoxDecoration for containers\n• Material Design components
Question:
How to handle device orientation in Flutter?
Answer:
Flutter device orientation handling:\n\n**Detect orientation:**\n\n@override\nWidget build(BuildContext context) {\n final orientation = MediaQuery.of(context).orientation;\n \n if (orientation == Orientation.portrait) {\n return PortraitLayout();\n } else {\n return LandscapeLayout();\n }\n}\n\n\n**OrientationBuilder:**\n\nOrientationBuilder(\n builder: (context, orientation) {\n return GridView.count(\n crossAxisCount: orientation == Orientation.portrait ? 2 : 4,\n children: widgets\n );\n }\n)\n\n\n**Lock orientation:**\n\nimport 'package:flutter/services.dart';\n\n// Lock to portrait\nSystemChrome.setPreferredOrientations([\n DeviceOrientation.portraitUp,\n DeviceOrientation.portraitDown\n]);\n\n// Allow all orientations\nSystemChrome.setPreferredOrientations([\n DeviceOrientation.portraitUp,\n DeviceOrientation.portraitDown,\n DeviceOrientation.landscapeLeft,\n DeviceOrientation.landscapeRight\n]);\n\n\n**Responsive design:**\n• Use MediaQuery for screen dimensions\n• Flexible and Expanded widgets\n• LayoutBuilder for custom layouts
Question:
What is Flutter plugin development?
Answer:
Flutter plugin development:\n\n**Plugin types:**\n• Platform plugins - Access native APIs\n• Dart plugins - Pure Dart packages\n• Federated plugins - Multi-platform support\n\n**Create plugin:**\nbash\nflutter create --template=plugin my_plugin\n\n\n**Plugin structure:**\n\nmy_plugin/\n lib/my_plugin.dart # Dart API\n android/ # Android implementation\n ios/ # iOS implementation\n example/ # Example app\n\n\n**Method channel:**\n\n// Dart side\nclass MyPlugin {\n static const MethodChannel _channel = MethodChannel('my_plugin');\n \n static Future getPlatformVersion() async {\n final String version = await _channel.invokeMethod('getPlatformVersion');\n return version;\n }\n}\n\n\n**Android implementation:**\nkotlin\nclass MyPlugin: FlutterPlugin, MethodCallHandler {\n override fun onMethodCall(call: MethodCall, result: Result) {\n when (call.method) {\n \"getPlatformVersion\" -> {\n result.success(\"Android ${android.os.Build.VERSION.RELEASE}\")\n }\n }\n }\n}\n\n\n**Publishing:**\n• Add to pub.dev\n• Follow pub.dev guidelines\n• Include documentation
Question:
How to implement local storage in Flutter?
Answer:
Flutter local storage options:\n\n**SharedPreferences:**\n\nimport 'package:shared_preferences/shared_preferences.dart';\n\n// Save data\nFuture saveData() async {\n final prefs = await SharedPreferences.getInstance();\n await prefs.setString('username', 'john_doe');\n await prefs.setInt('age', 25);\n await prefs.setBool('isLoggedIn', true);\n}\n\n// Read data\nFuture getData() async {\n final prefs = await SharedPreferences.getInstance();\n return prefs.getString('username');\n}\n\n\n**SQLite database:**\n\nimport 'package:sqflite/sqflite.dart';\n\nclass DatabaseHelper {\n static Future _database() async {\n return openDatabase(\n 'my_database.db',\n version: 1,\n onCreate: (db, version) {\n return db.execute(\n 'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)'\n );\n }\n );\n }\n \n static Future insertUser(User user) async {\n final db = await _database();\n await db.insert('users', user.toMap());\n }\n}\n\n\n**File storage:**\n\nimport 'dart:io';\nimport 'package:path_provider/path_provider.dart';\n\nFuture writeFile(String data) async {\n final directory = await getApplicationDocumentsDirectory();\n final file = File('${directory.path}/data.txt');\n return file.writeAsString(data);\n}\n\n\n**Hive (NoSQL):**\n• Fast key-value database\n• Type-safe\n• No native dependencies
Question:
Explain Flutter testing strategies.
Answer:
Flutter testing strategies:\n\n**Test types:**\n• Unit tests - Test individual functions/classes\n• Widget tests - Test widget behavior\n• Integration tests - Test complete app flow\n\n**Unit testing:**\n\nimport 'package:flutter_test/flutter_test.dart';\n\nvoid main() {\n group('Calculator', () {\n test('should add two numbers', () {\n final calculator = Calculator();\n expect(calculator.add(2, 3), equals(5));\n });\n });\n}\n\n\n**Widget testing:**\n\nvoid main() {\n testWidgets('Counter increments smoke test', (WidgetTester tester) async {\n await tester.pumpWidget(MyApp());\n \n expect(find.text('0'), findsOneWidget);\n expect(find.text('1'), findsNothing);\n \n await tester.tap(find.byIcon(Icons.add));\n await tester.pump();\n \n expect(find.text('0'), findsNothing);\n expect(find.text('1'), findsOneWidget);\n });\n}\n\n\n**Integration testing:**\n\nvoid main() {\n group('App', () {\n testWidgets('full app test', (tester) async {\n app.main();\n await tester.pumpAndSettle();\n \n // Test complete user flow\n await tester.tap(find.byKey(Key('login_button')));\n await tester.pumpAndSettle();\n \n expect(find.text('Welcome'), findsOneWidget);\n });\n });\n}\n\n\n**Mocking:**\n• Use mockito package\n• Mock HTTP requests\n• Mock platform channels
Question:
How to optimize Flutter app performance?
Answer:
Flutter performance optimization:\n\n**Widget optimization:**\n• Use const constructors\n• Avoid rebuilding expensive widgets\n• Use RepaintBoundary for complex widgets\n• Implement shouldRebuild in custom widgets\n\n**List optimization:**\n\n// Use ListView.builder for large lists\nListView.builder(\n itemCount: items.length,\n itemBuilder: (context, index) {\n return ListTile(title: Text(items[index]));\n }\n)\n\n// Use ListView.separated for dividers\nListView.separated(\n itemBuilder: (context, index) => ItemWidget(items[index]),\n separatorBuilder: (context, index) => Divider(),\n itemCount: items.length\n)\n\n\n**Image optimization:**\n• Use appropriate image formats\n• Implement image caching\n• Use Image.network with cacheWidth/cacheHeight\n• Compress images\n\n**Memory management:**\n• Dispose controllers and streams\n• Use weak references\n• Avoid memory leaks in listeners\n\n**Build optimization:**\n• Use --release mode for production\n• Enable code splitting\n• Tree shaking for smaller bundles\n• Profile app with Flutter Inspector\n\n**Animation optimization:**\n• Use Transform instead of changing layout\n• Prefer Opacity over rebuilding\n• Use RepaintBoundary for animations
Question:
What are Flutter design patterns?
Answer:
Flutter design patterns:\n\n**BLoC Pattern:**\n\nclass CounterBloc {\n final _counterController = StreamController();\n final _actionController = StreamController();\n \n Stream get counter => _counterController.stream;\n Sink get action => _actionController.sink;\n \n CounterBloc() {\n _actionController.stream.listen(_handleAction);\n }\n \n void _handleAction(CounterAction action) {\n if (action == CounterAction.increment) {\n _counterController.add(_currentCount + 1);\n }\n }\n}\n\n\n**Provider Pattern:**\n\nclass UserProvider extends ChangeNotifier {\n User? _user;\n User? get user => _user;\n \n void setUser(User user) {\n _user = user;\n notifyListeners();\n }\n}\n\n\n**Repository Pattern:**\n\nabstract class UserRepository {\n Future getUser(String id);\n Future saveUser(User user);\n}\n\nclass ApiUserRepository implements UserRepository {\n @override\n Future getUser(String id) async {\n // API implementation\n }\n}\n\n\n**Singleton Pattern:**\n\nclass ApiService {\n static final ApiService _instance = ApiService._internal();\n factory ApiService() => _instance;\n ApiService._internal();\n}\n\n\n**Factory Pattern:**\n• Create objects without specifying exact class\n• Useful for creating different widget types\n• Platform-specific implementations
Question:
Explain Flutter isolates and concurrent programming.
Answer:
Flutter isolates and concurrency:\n\n**Isolate Concepts:**\n• Independent memory heaps\n• No shared memory between isolates\n• Communication via message passing\n• Each isolate has own event loop\n\n**Creating Isolates:**\n\nimport 'dart:isolate';\n\n// Heavy computation function\nvoid heavyComputation(SendPort sendPort) {\n // Perform heavy task\n int result = 0;\n for (int i = 0; i < 1000000; i++) {\n result += i;\n }\n sendPort.send(result);\n}\n\n// Main isolate\nFuture runHeavyTask() async {\n final receivePort = ReceivePort();\n await Isolate.spawn(heavyComputation, receivePort.sendPort);\n return await receivePort.first;\n}\n\n\n**Using compute() Function:**\n\nint heavyTask(int number) {\n // Heavy computation\n return number * number;\n}\n\nFuture performTask() async {\n final result = await compute(heavyTask, 1000);\n print('Result: $result');\n}\n\n\n**Communication Patterns:**\n• **One-way** - Send data, no response\n• **Request-Response** - Send data, wait for response\n• **Bidirectional** - Continuous communication\n\n**Use Cases:**\n• Image processing\n• JSON parsing\n• Cryptographic operations\n• File I/O operations\n• Network requests\n\n**Best Practices:**\n• Use compute() for simple tasks\n• Create custom isolates for complex scenarios\n• Minimize data transfer between isolates\n• Handle isolate lifecycle properly
Question:
Explain Flutter rendering pipeline and optimization.
Answer:
Flutter rendering pipeline:\n\n**Rendering Pipeline Stages:**\n1. **Build** - Widget tree construction\n2. **Layout** - Size and position calculation\n3. **Paint** - Drawing operations\n4. **Composite** - Layer composition\n\n**Optimization Strategies:**\n• **Const constructors** - Avoid unnecessary rebuilds\n• **RepaintBoundary** - Isolate expensive widgets\n• **ListView.builder** - Lazy loading for lists\n• **Image caching** - Reduce memory usage\n• **Tree shaking** - Remove unused code\n\n**Performance Tools:**\n• Flutter Inspector - Widget tree analysis\n• Performance Overlay - FPS monitoring\n• Dart DevTools - Memory profiling\n• Timeline view - Frame analysis\n\n**Best Practices:**\n• Minimize widget rebuilds\n• Use appropriate list widgets\n• Optimize image loading\n• Profile before optimizing\n• Use release builds for testing
Question:
How to implement custom Flutter plugins?
Answer:
Custom Flutter plugin implementation:\n\n**Plugin Structure:**\n\nmy_plugin/\n lib/\n my_plugin.dart # Dart API\n android/\n src/main/kotlin/ # Android code\n ios/\n Classes/ # iOS code\n example/ # Example app\n\n\n**Dart Interface:**\n\nclass MyPlugin {\n static const MethodChannel _channel = MethodChannel('my_plugin');\n \n static Future getPlatformVersion() async {\n return await _channel.invokeMethod('getPlatformVersion');\n }\n \n static Future showToast(String message) async {\n await _channel.invokeMethod('showToast', {'message': message});\n }\n}\n\n\n**Android Implementation:**\nkotlin\nclass MyPlugin: FlutterPlugin, MethodCallHandler {\n override fun onMethodCall(call: MethodCall, result: Result) {\n when (call.method) {\n \"getPlatformVersion\" -> {\n result.success(\"Android ${Build.VERSION.RELEASE}\")\n }\n \"showToast\" -> {\n val message = call.argument(\"message\")\n Toast.makeText(context, message, Toast.LENGTH_SHORT).show()\n result.success(null)\n }\n }\n }\n}\n\n\n**iOS Implementation:**\nswift\npublic class SwiftMyPlugin: NSObject, FlutterPlugin {\n public static func register(with registrar: FlutterPluginRegistrar) {\n let channel = FlutterMethodChannel(name: \"my_plugin\", binaryMessenger: registrar.messenger())\n let instance = SwiftMyPlugin()\n registrar.addMethodCallDelegate(instance, channel: channel)\n }\n \n public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {\n switch call.method {\n case \"getPlatformVersion\":\n result(\"iOS \" + UIDevice.current.systemVersion)\n default:\n result(FlutterMethodNotImplemented)\n }\n }\n}\n
Question:
Explain Flutter architecture and its components.
Answer:
Flutter architecture layers:\n\n**Framework Layer (Dart):**\n• Material/Cupertino - Design systems\n• Widgets - UI components\n• Rendering - Layout and painting\n• Animation & Gestures - User interactions\n\n**Engine Layer (C++):**\n• Skia - 2D graphics rendering\n• Dart Runtime - VM and isolates\n• Text - Text layout and rendering\n• Platform Channels - Native communication\n\n**Embedder Layer:**\n• Platform-specific code\n• Android (Java/Kotlin)\n• iOS (Objective-C/Swift)\n• Desktop (C++)\n• Web (JavaScript)\n\n**Key Components:**\n• **Widget Tree** - Immutable UI description\n• **Element Tree** - Widget instances\n• **RenderObject Tree** - Layout and painting\n• **Layer Tree** - Compositing\n\n**Benefits:**\n• Consistent UI across platforms\n• High performance rendering\n• Hot reload for fast development\n• Single codebase maintenance
Question:
How to implement advanced animations in Flutter?
Answer:
Advanced Flutter animations:\n\n**Animation Controllers:**\n\nclass _AnimatedWidgetState extends State \n with TickerProviderStateMixin {\n late AnimationController _controller;\n late Animation _animation;\n \n @override\n void initState() {\n super.initState();\n _controller = AnimationController(\n duration: Duration(seconds: 2),\n vsync: this\n );\n \n _animation = Tween(\n begin: 0.0,\n end: 1.0\n ).animate(CurvedAnimation(\n parent: _controller,\n curve: Curves.easeInOut\n ));\n }\n}\n\n\n**Custom Transitions:**\n\nclass SlideRoute extends PageRouteBuilder {\n final Widget page;\n \n SlideRoute({required this.page})\n : super(\n pageBuilder: (context, animation, secondaryAnimation) => page,\n transitionsBuilder: (context, animation, secondaryAnimation, child) {\n return SlideTransition(\n position: Tween(\n begin: Offset(1.0, 0.0),\n end: Offset.zero\n ).animate(animation),\n child: child\n );\n }\n );\n}\n\n\n**Staggered Animations:**\n\nclass StaggeredAnimation {\n final AnimationController controller;\n final Animation opacity;\n final Animation width;\n final Animation padding;\n \n StaggeredAnimation(this.controller)\n : opacity = Tween(begin: 0.0, end: 1.0).animate(\n CurvedAnimation(parent: controller, curve: Interval(0.0, 0.100))\n ),\n width = Tween(begin: 50.0, end: 150.0).animate(\n CurvedAnimation(parent: controller, curve: Interval(0.125, 0.250))\n ),\n padding = Tween(\n begin: EdgeInsets.only(left: 0.0),\n end: EdgeInsets.only(left: 100.0)\n ).animate(\n CurvedAnimation(parent: controller, curve: Interval(0.250, 0.375))\n );\n}\n\n\n**Physics-based Animations:**\n• SpringSimulation for natural motion\n• GravitySimulation for falling effects\n• FrictionSimulation for deceleration
Question:
Explain Flutter state management with BLoC pattern.
Answer:
BLoC (Business Logic Component) pattern:\n\n**Core Concepts:**\n• **Events** - User actions or system events\n• **States** - UI states based on business logic\n• **BLoC** - Processes events and emits states\n• **Streams** - Reactive data flow\n\n**Implementation:**\n\n// Events\nabstract class CounterEvent {}\nclass Increment extends CounterEvent {}\nclass Decrement extends CounterEvent {}\n\n// States\nabstract class CounterState {\n final int count;\n CounterState(this.count);\n}\nclass CounterInitial extends CounterState {\n CounterInitial() : super(0);\n}\nclass CounterUpdated extends CounterState {\n CounterUpdated(int count) : super(count);\n}\n\n// BLoC\nclass CounterBloc extends Bloc {\n CounterBloc() : super(CounterInitial()) {\n on((event, emit) {\n emit(CounterUpdated(state.count + 1));\n });\n \n on((event, emit) {\n emit(CounterUpdated(state.count - 1));\n });\n }\n}\n\n\n**UI Integration:**\n\nclass CounterPage extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return BlocProvider(\n create: (context) => CounterBloc(),\n child: BlocBuilder(\n builder: (context, state) {\n return Scaffold(\n body: Center(\n child: Text('${state.count}')\n ),\n floatingActionButton: FloatingActionButton(\n onPressed: () => context.read().add(Increment()),\n child: Icon(Icons.add)\n )\n );\n }\n )\n );\n }\n}\n\n\n**Benefits:**\n• Separation of concerns\n• Testable business logic\n• Reactive programming\n• Predictable state changes
Question:
How to implement custom painting in Flutter?
Answer:
Custom painting in Flutter:\n\n**CustomPainter Class:**\n\nclass MyPainter extends CustomPainter {\n @override\n void paint(Canvas canvas, Size size) {\n final paint = Paint()\n ..color = Colors.blue\n ..strokeWidth = 2.0\n ..style = PaintingStyle.stroke;\n \n // Draw circle\n canvas.drawCircle(\n Offset(size.width / 2, size.height / 2),\n 50.0,\n paint\n );\n \n // Draw path\n final path = Path()\n ..moveTo(0, size.height / 2)\n ..quadraticBezierTo(\n size.width / 2, 0,\n size.width, size.height / 2\n );\n canvas.drawPath(path, paint);\n }\n \n @override\n bool shouldRepaint(CustomPainter oldDelegate) => false;\n}\n\n\n**Usage:**\n\nCustomPaint(\n size: Size(200, 200),\n painter: MyPainter()\n)\n\n\n**Advanced Techniques:**\n• Clipping with clipPath()\n• Gradients and shaders\n• Image drawing\n• Text rendering\n• Transformations (rotate, scale, translate)\n\n**Performance Tips:**\n• Use shouldRepaint() wisely\n• Cache expensive calculations\n• Use RepaintBoundary for isolation\n• Minimize paint operations