0% found this document useful (0 votes)
21 views21 pages

Flutter Basic Questions

The document provides a comprehensive overview of Flutter, an open-source UI toolkit by Google for building natively compiled applications across platforms using Dart. It covers fundamental concepts such as widgets, state management, rendering engine, and performance optimization, along with advanced topics like BLoC pattern, testing, and networking. Additionally, it outlines frequently asked interview questions and a roadmap for Flutter interview preparation.

Uploaded by

harram shamaim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views21 pages

Flutter Basic Questions

The document provides a comprehensive overview of Flutter, an open-source UI toolkit by Google for building natively compiled applications across platforms using Dart. It covers fundamental concepts such as widgets, state management, rendering engine, and performance optimization, along with advanced topics like BLoC pattern, testing, and networking. Additionally, it outlines frequently asked interview questions and a roadmap for Flutter interview preparation.

Uploaded by

harram shamaim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Basic Questions/Answers

🔹 1. What is Flutter?

Answer:
Flutter is an open-source UI toolkit created by Google for building natively compiled
applications for mobile, web, and desktop from a single codebase.

🔹 2. What is Dart?

Answer:
Dart is the programming language used by Flutter. It is optimized for building fast and reactive
user interfaces and compiles to native code.

🔹 3. What is a Widget in Flutter?

Answer:
In Flutter, everything is a widget. Widgets are the building blocks of a Flutter app’s UI, such as
text, buttons, images, and layouts.

🔹 4. Difference between StatelessWidget and StatefulWidget?

Answer:

 StatelessWidget: Immutable; once built, it cannot change.


 StatefulWidget: Mutable; it can change over time and update the UI with setState().

🔹 5. What is the build() method?

Answer:
The build() method describes how to display the widget in the UI. It’s called whenever the
widget needs to be rendered or updated.

🔹 6. What is setState() in Flutter?


Answer:
setState() is used to notify the Flutter framework that the internal state of a widget has
changed, prompting it to rebuild the UI.

🔹 7. What is the pubspec.yaml file?

Answer:
It's the configuration file used to manage a Flutter project’s assets, dependencies, and metadata
(like app name and version).

🔹 8. How does Flutter achieve native performance?

Answer:
Flutter uses the Dart language, which compiles to native ARM code, and its own rendering
engine to achieve high performance.

🔹 9. What is hot reload in Flutter?

Answer:
Hot reload allows developers to inject updated source code files into the running Dart VM,
preserving the app state and speeding up development.

🔹 10. What is the difference between main() and runApp() in Flutter?

Answer:

 main() is the entry point of a Dart application.


 runApp() inflates the given widget and attaches it to the screen.
Advanced Questions/Answers

🔸 1. How does Flutter’s rendering engine work?

Answer:
Flutter uses the Skia rendering engine. It redraws the entire UI every frame, making the UI
smooth and consistent. The framework uses a layered architecture:

 Widget layer
 Element layer
 RenderObject layer This gives fine control over every pixel on the screen.

🔸 2. What is an InheritedWidget and how is it used?

Answer:
InheritedWidget allows data to be efficiently propagated down the widget tree. It’s commonly
used for managing app-wide states like themes or user sessions.
Example: Theme.of(context) uses InheritedWidget under the hood.

🔸 3. Explain the difference between keys: GlobalKey vs LocalKey vs ValueKey.

Answer:

 LocalKey: Basic key used to differentiate widgets.


 GlobalKey: Uniquely identifies a widget across the whole app. Used for accessing
widget states.
 ValueKey: Used when rebuilding lists with values to maintain state.

🔸 4. What is the difference between Navigator.push and


Navigator.pushReplacement?

Answer:

 push: Adds a new route on top of the stack.


 pushReplacement: Replaces the current route with a new one, removing the previous
one from the stack.
🔸 5. What is the role of FutureBuilder and StreamBuilder in Flutter?

Answer:

 FutureBuilder: Used to build UI based on the result of a Future.


 StreamBuilder: Builds UI based on a Stream of data (e.g., real-time updates).

🔸 6. Explain Flutter’s widget lifecycle.

Answer: For StatefulWidget, key lifecycle methods include:

 initState()
 didChangeDependencies()
 build()
 setState()
 deactivate()
 dispose()

🔸 7. How would you optimize a Flutter app for performance?

Answer:

 Use const constructors where possible.


 Avoid rebuilding large widget trees unnecessarily.
 Use RepaintBoundary to isolate redrawing.
 Use ListView.builder for large lists.
 Minimize usage of setState.

🔸 8. What are Isolates in Dart and how do they relate to Flutter?

Answer:
Isolates are independent threads of execution in Dart. They are used to perform heavy
computations off the main thread without blocking the UI.

🔸 9. What is the BLoC pattern in Flutter?


Answer:
BLoC (Business Logic Component) separates UI from business logic using Streams and Sinks.
It helps in building scalable, testable apps with reactive programming.

🔸 10. How does Flutter handle state management?

Answer: Flutter provides various approaches:

 setState() – simple, local state


 Provider – recommended by Flutter team
 Riverpod – an improvement over Provider
 Bloc / Cubit – reactive state using Streams
 GetX, MobX, etc. – other popular third-party options

✅ Top Frequently Asked Flutter Interview Questions & Answers


🔹 1. What is Flutter and why is it used?

Answer:
Flutter is an open-source UI toolkit by Google for building natively compiled applications for
mobile, web, and desktop from a single codebase. It is known for its hot reload, fast
performance, and customizable UI widgets.

🔹 2. What are widgets in Flutter?

Answer:
Widgets are the basic building blocks of a Flutter app. Everything in Flutter is a widget —
whether it’s layout, text, padding, or an image.

🔹 3. What’s the difference between StatelessWidget and StatefulWidget?

Answer:

 StatelessWidget: UI that doesn’t change.


 StatefulWidget: UI that can update dynamically based on state changes.

🔹 4. What is hot reload and hot restart?

Answer:

 Hot reload: Updates code and UI without losing the app state.
 Hot restart: Restarts the app and clears the state.

🔹 5. How do you manage state in Flutter?

Answer:

 For simple state: setState()


 For scalable apps: Provider, Riverpod, BLoC, GetX, MobX, etc.
🔹 6. What is the pubspec.yaml file?

Answer:
It’s the configuration file for managing dependencies, assets, fonts, and more in a Flutter project.

🔹 7. What is Navigator in Flutter?

Answer:
Navigator manages a stack of routes (pages). You can use it to navigate between screens using
Navigator.push() and Navigator.pop().

🔹 8. What is a Future and how is it used?

Answer:
A Future in Dart represents a value that will be available in the future, often used for async
tasks like fetching data from an API.

🔹 9. Difference between FutureBuilder and StreamBuilder?

Answer:

 FutureBuilder: Used for one-time async operations.


 StreamBuilder: Used for continuous data flow (e.g., Firebase real-time updates).

🔹 10. What are keys in Flutter?

Answer: Keys are used to preserve state of widgets when the widget tree rebuilds.
Types: Key, ValueKey, ObjectKey, GlobalKey.

🔹 11. How does Flutter achieve high performance?

Answer:
Flutter uses its own rendering engine (Skia), compiles to native ARM code, and doesn't rely on
native UI components — leading to smooth performance.
🔹 12. What is the use of initState() in StatefulWidget?

Answer:
initState() is the first method called when a StatefulWidget is created. It’s used to initialize
data, start animations, or fetch data once.

🔹 13. What is the difference between Column and ListView?

Answer:

 Column: Displays widgets vertically without scrolling.


 ListView: Same as Column but scrollable and efficient for large lists.

🔹 14. How do you optimize a Flutter app?

Answer:

 Use const widgets.


 Use lazy widgets like ListView.builder.
 Avoid unnecessary rebuilds.
 Use RepaintBoundary for complex UIs.

🔹 15. What is a BuildContext?

Answer:
BuildContext provides the location of a widget in the widget tree and is used to access theme,
media query, or navigate.

2:28 What is Flutter?

Answer:
Flutter is an open-source UI toolkit developed by Google for building natively compiled
applications for mobile, web, and desktop from a single codebase. It uses the Dart
programming language and has its own rendering engine called Skia, enabling beautiful and
high-performance apps.

3:02 What is the concept of class in Flutter?

Answer:
In Flutter (and Dart), a class is a blueprint for creating objects. Everything in Flutter is built
using classes — whether it's a StatelessWidget, a layout, a custom model, or even business
logic. It encapsulates data and behavior (methods) and helps in object-oriented
programming.

3:40 What is the difference between Stateless Widgets and Stateful Widgets?

Answer:

 StatelessWidget: UI components that don’t change over time or after user interaction.
 StatefulWidget: UI components that can change dynamically based on events, user
input, or internal logic using setState().

Use Stateless when the UI doesn't depend on dynamic data and Stateful when the UI reacts to
internal or external changes.

4:24 What is the difference between GetX, BLoC and Provider? Which one you
prefer and why?

Answer:

 Provider: Officially recommended by Flutter; simple, good for small-to-medium apps.


 BLoC (Business Logic Component): Uses Streams and events; ideal for complex
enterprise-level apps.
 GetX: Lightweight and reactive with minimal boilerplate; great for quick development
and state management, routing, and dependency injection.

Preferred: It depends. For simple apps, Provider is sufficient. For complex apps, I prefer GetX
due to its simplicity, speed, and multiple built-in utilities.

6:40 What is the difference between unit, widget and integration tests in Flutter?
Answer:

 Unit Test: Tests a single function, method, or class in isolation.


 Widget Test: Tests a widget’s UI and interaction behavior.
 Integration Test: Tests a complete app or a large part of it, simulating real user
interactions.

8:32 How would you monitor errors in a Flutter application?

Answer:

 Use FlutterError.onError for catching framework-level errors.


 Use runZonedGuarded() for uncaught asynchronous errors.
 Use monitoring tools like Firebase Crashlytics, Sentry, or BugSnag to track and report
runtime issues and crashes in production.

9:52 What do you understand about the material and cupertino aspects of
Flutter design?

Answer:

 Material: Google's design system for Android. Use widgets like Scaffold, AppBar,
MaterialButton.
 Cupertino: Apple’s design language for iOS. Use widgets like
CupertinoPageScaffold, CupertinoNavigationBar.

Flutter allows platform-specific UI using Theme.of(context).platform or conditionally


rendering widgets using Platform.isIOS.

11:00 Before releasing an app to production, what steps do you consider to make
sure functionalities are working fine and also if it is optimized?

Answer:

 Conduct unit, widget, and integration testing.


 Perform UI/UX testing across different screen sizes and OS versions.
 Use Flutter DevTools to analyze performance.
 Optimize assets, use const constructors.
 Run flutter build apk --release and test the release build.
 Integrate Crashlytics or Sentry for post-release monitoring.
 Use code obfuscation and app signing.
 Check for permissions, battery usage, and startup time.

12:40 What is Dart and why does Flutter use it?

Answer:
Dart is an object-oriented, class-based language developed by Google. Flutter uses Dart because:

 It compiles to native code (JIT & AOT).


 It supports hot reload via JIT.
 It has a rich set of features like async/await, streams, and null safety.
 It was designed for UI development.

14:20 What is the difference between hot restart and hot reload?

Answer:

 Hot Reload: Injects updated source code files into the running Dart VM. Preserves the
app state.
 Hot Restart: Restarts the app from the beginning. State is lost but everything is rebuilt
cleanly.

15:52 Differentiate required and optional parameters in Dart.

Answer:

 Required: Must be passed when calling a function.

dart
CopyEdit
void greet({required String name}) { ... }

 Optional: Can be omitted. They can be:


o Named optional with default values:

dart
CopyEdit
void greet({String name = 'Guest'}) { ... }

o Positional optional:
dart
CopyEdit
void greet([String name = 'Guest']) { ... }

17:05 What are streams? What different types of streams does Flutter support?

Answer: Streams provide asynchronous data sequences. Flutter supports:

 Single-subscription streams (most common): one listener at a time.


 Broadcast streams: multiple listeners allowed.

Used in real-time data (e.g., Firebase, network data, sensors).

18:24 What is the purpose of a single subscription stream?

Answer: A single subscription stream is used when only one listener can listen to the stream
at a time. It's ideal for data that’s meant to be consumed once, like API responses or user input.

19:05 What are null-aware operations?

Answer: Null-aware operators help handle nullable values safely:

 ?? → if null, use default


 ?. → safe access
 ??= → assign only if null
 ! → assert non-null

Example:

dart
CopyEdit
String? name;
print(name ?? 'Guest'); // Output: Guest

21:08 Why do we pass functions to a widget?

Answer: To allow child widgets to communicate back with parents. It helps in handling events
like button clicks, state changes, or callbacks from UI interactions.
21:50 What is a Future in Flutter?

Answer: A Future represents a potential value or error that will be available asynchronously.
It's commonly used for:

 Network calls
 File I/O
 Delayed tasks

Example:

dart
CopyEdit
Future<String> fetchData() async {
return await http.get(url);
}

✅ Complete Flutter Interview Preparation Roadmap (with Topics)

🚀 1. Flutter Basics
 What is Flutter?
 Why use Flutter?
 Flutter architecture overview
 Widgets: What they are and types (stateless vs stateful)
 Widget tree and how build method works
 Flutter rendering engine (Skia)
 Hot reload vs hot restart
 Flutter CLI commands (flutter doctor, flutter run, etc.)
 pubspec.yaml (dependencies, assets, fonts)

🐦 2. Dart Language Fundamentals

 Variables, data types


 Functions (named, anonymous, arrow)
 Required vs optional parameters
 Loops & control statements
 Collections (List, Set, Map)
 Null safety and null-aware operators
 Futures and async-await
 Streams and their types (single/broadcast)
 Exception handling

🧱 3. Object-Oriented Programming (OOP) in Dart

 Classes and Objects


 Inheritance and mixins
 Abstraction and encapsulation
 Interfaces & abstract classes
 Constructors (named, factory)
 Polymorphism
 this, super, static, final, const

🎨 4. Widgets & Layouts

 StatelessWidget vs StatefulWidget
 Common widgets: Container, Row, Column, Stack, Expanded, Padding
 Custom widgets
 ListView, GridView, CustomScrollView
 Forms and form validation
 Navigation and routes (Navigator, named routes)
🌐 5. State Management

 setState() and lifting state up


 Provider (basic to advanced)
 Riverpod (if preferred)
 GetX (state, routing, DI)
 BLoC (Streams, Cubit, HydratedBloc)
 Which one to use and when?

🧪 6. Testing in Flutter

 Unit Testing
 Widget Testing
 Integration Testing
 Mocking and using mockito
 Flutter test best practices

🔌 7. Networking & APIs

 HTTP package usage


 REST API integration (GET, POST, PUT, DELETE)
 Error handling in API calls
 JSON serialization (manual & using json_serializable)

🖼️8. UI/UX & Animations

 Theme and custom themes


 Material vs Cupertino widgets
 Hero animations
 AnimatedContainer, AnimatedBuilder
 Lottie animations
 CustomPaint and Canvas

📂 9. Local & Persistent Storage

 SharedPreferences
 Local database: sqflite
 Local file I/O
 Hive or ObjectBox for NoSQL storage

🔐 10. Authentication

 Firebase Auth
 Manual JWT token-based login
 Social login (Google, Facebook)
 Token storage and security

☁️11. Firebase & Backend Integration

 Firebase Firestore (real-time updates)


 Firebase Storage
 Firebase Messaging (Push Notifications)
 Firebase Crashlytics
 Firebase Analytics

🧭 12. Navigation & Routing

 Simple routing
 Named routes
 Route generator
 Nested navigation (e.g., in bottom nav bars)
 GetX/Riverpod routing

🧰 13. Deployment & Optimization

 Preparing app for production


 APK vs AAB build
 Obfuscation & minification
 App signing
 Reducing app size
 Performance monitoring
 CI/CD basics
💻 14. Advanced Topics

 Custom RenderBox and Slivers


 Platform channels (native Android/iOS integration)
 Isolates and background tasks
 WebSockets (real-time apps)
 Microtask vs Event Queue

🔎 15. Common Interview Questions & Patterns

 Differences: FutureBuilder vs StreamBuilder


 Why Flutter over React Native?
 How to debug and profile Flutter apps?
 Explain your project architecture.
 OOP design principles (SOLID)
 Factory vs Constructor
 Lazy loading and pagination

✅ Flutter Interview Topics Explained

🚀 1. Flutter Basics

 What is Flutter?
Flutter is an open-source UI SDK by Google for building natively compiled applications for
mobile, web, desktop, and embedded devices from a single codebase.
 Widgets in Flutter:
Everything in Flutter is a widget (buttons, padding, layout). Widgets describe what their view
should look like and are immutable.
 Stateless vs Stateful Widgets:
o StatelessWidget – doesn’t hold any state (e.g., Text, Icon).
o StatefulWidget – has a mutable state that can change (e.g., forms, animations).
 Widget Tree:
It's the structure of how widgets are nested. Flutter rebuilds widgets efficiently when state
changes.
 Flutter Rendering Engine (Skia):
Skia renders pixels directly to the screen, allowing high-performance rendering without relying
on native UI components.
🐦 2. Dart Language Fundamentals

 Dart is the language used in Flutter. It supports both OOP and functional-style programming.
 Variables & Types:
var, final, const, int, double, String, bool, List, Map, Set.
 Functions:
Supports positional and named parameters, with required, optional, and default values.
 Null Safety:
Prevents null-related runtime errors using ?, !, and late.
 Async-Await & Futures:
Used for asynchronous programming, such as API calls or delays.
 Streams:
Handle real-time data flow; used with StreamBuilder.

🧱 3. OOP in Dart

 Classes & Objects:


Core building blocks of Dart.
 Inheritance & Mixins:
Inherit behavior from a parent class. Mixins allow code reuse without inheritance.
 Abstract Classes & Interfaces:
Abstract class can’t be instantiated directly and is used for base definitions. Dart doesn’t have
interfaces explicitly—every class is an interface.
 Constructors:
Normal, named, factory constructors help in different object creation scenarios.
 Encapsulation & Polymorphism:
Use private variables (_) and method overriding for flexible architecture.

🎨 4. Widgets & Layouts

 Core Widgets:
Container, Row, Column, Stack, SizedBox, Text, Image.
 Custom Widgets:
Helps split UI into reusable components.
 Layouts:
Use Flexible, Expanded, MediaQuery, AspectRatio for responsive design.
 Forms:
Flutter provides form widgets and validation methods using Form, TextFormField, and
GlobalKey<FormState>.
🌐 5. State Management

 setState():
Basic method to update UI state in a StatefulWidget.
 Provider:
Officially recommended for app-wide state sharing.
 GetX:
Lightweight and simple for routing, state management, and dependency injection.
 BLoC (Business Logic Component):
Uses Streams and Sinks to separate business logic and UI.
 Riverpod:
An improvement over Provider, more flexible and testable.

🧪 6. Testing

 Unit Testing:
Tests logic in isolation (e.g., functions, models).
 Widget Testing:
Tests a widget’s UI and interactions (e.g., tapping a button).
 Integration Testing:
Simulates real user interactions across multiple screens and components.

🔌 7. Networking & API Calls

 Using HTTP package:


http.get(), http.post() to fetch data from REST APIs.
 JSON Serialization:
Convert response JSON into Dart models using jsonDecode, or packages like
json_serializable.
 Error Handling:
Use try-catch, timeout handling, and response code checks.

🖼️8. UI/UX & Animations

 Themes:
Light/Dark modes, global text styles, button styles via ThemeData.
 Material vs Cupertino:
o Material = Android-style design.
o Cupertino = iOS-style design.
 Animations:
o Basic: AnimatedContainer, AnimatedOpacity.
o Advanced: Hero, Tween, AnimationController.

📂 9. Local & Persistent Storage

 SharedPreferences:
Store small key-value data like login state.
 sqflite:
SQLite-based local database for structured data.
 Hive:
Lightweight NoSQL alternative to store Dart objects.

🔐 10. Authentication

 Firebase Authentication:
Simplifies login (email/password, Google, etc.).
 Manual Auth:
Use JWT tokens and secure APIs for custom login.
 Token Storage:
Use SharedPreferences, flutter_secure_storage for storing tokens securely.

☁️11. Firebase & Backend Integration

 Firestore:
Real-time NoSQL database.
 Firebase Storage:
Upload and retrieve files (images, docs).
 Firebase Messaging:
Push notifications.
 Firebase Crashlytics:
Monitor crashes and issues in production.

🧭 12. Navigation & Routing

 Navigator:
Navigator.push() and Navigator.pop() for navigation.
 Named Routes:
Register routes in MaterialApp.
 Route Generator:
Dynamically generate screens based on routes.
 Nested Navigation:
Handle navigation inside tabs or bottom navigation bars.

🧰 13. Deployment & Optimization

 Build APK/AAB:
flutter build apk or flutter build appbundle.
 Performance Optimization:
Use flutter analyze, reduce widget rebuilds, lazy loading, image caching.
 App Size:
Reduce using tree-shaking, code splitting, image compression.
 CI/CD:
Use GitHub Actions, Codemagic, or Bitrise for automation.

💻 14. Advanced Topics

 Platform Channels:
Communicate with native Android/iOS code.
 Isolates:
Run heavy tasks in parallel without blocking UI.
 WebSockets:
For real-time features like chats and games.
 CustomPaint:
Draw custom shapes and visuals.

🔎 15. Common Interview Questions & Patterns

 Future vs Stream
Future gives a single value, Stream gives multiple over time.
 Why Flutter?
Fast development, single codebase, expressive UI.
 Project Architecture
MVVM or Clean Architecture using repositories, services, models, and views.
 SOLID Principles
Improve maintainability and testability.

You might also like