Top 100 Flutter Interview Questions And Answers 2026
Here, we discuss questions covering all important aspects of Flutter and Dart that are most likely to be asked in interviews.
In this article, we will discuss all major Flutter and Dart interview questions, including the latest features and trends in 2025–2026, that are most likely to be asked by interviewers.
Flutter is a powerful open-source software development kit developed by Google. It allows developers to build beautiful, high-performance apps for mobile, web, and desktop using a single codebase.
Below, you will find important Flutter developer interview questions that will help you understand this framework better. This article also covers new features like Impeller, WebAssembly for Flutter Web, and updated state management techniques, along with tips to ace your Flutter interview.
1. What is Flutter?
Flutter is an open-source UI framework developed by Google that allows developers to build mobile, web, and desktop applications using a single codebase. Instead of relying on native UI components provided by Android or iOS, Flutter draws everything on the screen by itself using its own rendering engine. This approach gives developers full control over the UI and ensures that the app behaves the same way across all platforms.
In simple words, Flutter does not wrap native views — it creates its own UI. This is why Flutter apps feel fast, smooth, and visually consistent. Because everything is written in Dart and rendered directly, developers can design highly customized interfaces without fighting platform limitations.
“Flutter is not just a framework, it’s a complete UI toolkit.”
void main() {
runApp(const MyApp());
}2. Why should we choose Flutter for app development?
Flutter is chosen because it solves multiple problems at once. Traditionally, developers had to write separate codebases for Android, iOS, web, and desktop. Flutter removes this complexity by allowing one shared codebase. This significantly reduces development time, maintenance effort, and overall cost.
Another major reason is developer experience. Features like Hot Reload allow developers to see UI changes instantly without restarting the app. Flutter also provides a rich widget library that makes building complex UIs much easier. For startups, Flutter speeds up delivery. For large teams, it ensures consistency.
“Flutter lets teams move fast without breaking performance.”
3. What is Dart and why does Flutter use it?
Dart is the programming language used by Flutter. It was chosen because it supports both Just-In-Time (JIT) compilation for fast development and Ahead-Of-Time (AOT) compilation for high-performance production builds. This combination allows Flutter apps to be fast during development and efficient in release mode.
Dart is easy to learn, especially for developers coming from Java, Kotlin, or JavaScript. It has strong typing, null safety, and modern features like async/await, which makes writing asynchronous code much cleaner.
“Dart is designed to be boring in syntax but powerful in performance.”
4. What are widgets in Flutter?
In Flutter, everything is a widget. Buttons, text, images, padding, margins, layouts — all of them are widgets. Widgets describe how the UI should look at a given moment. They are immutable, meaning once created, they cannot be changed. If something changes, Flutter creates a new widget instead.
This design makes UI predictable and easy to reason about. Rather than modifying UI elements directly, Flutter rebuilds widgets based on the current state.
“In Flutter, UI is just a function of state.”
Text("Hello Flutter");5. What is the difference between StatelessWidget and StatefulWidget?
A StatelessWidget is used when the UI does not change after it is built. It depends only on the configuration passed to it. A StatefulWidget, on the other hand, is used when the UI can change dynamically due to user interaction, API responses, or internal logic.
The key idea is not about “screen size” or “complexity”, but about whether the UI can change over time. Beginners often misuse StatefulWidget, but knowing when to use which one is essential.
“If the UI can change, it needs state.”
class MyText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Text("Static UI");
}
}6. What is the Flutter widget lifecycle?
The widget lifecycle describes how a widget is created, updated, and destroyed. For StatefulWidget, this lifecycle includes methods like initState, build, didUpdateWidget, and dispose. These methods allow developers to control initialization, UI updates, and cleanup.
Understanding the widget lifecycle helps prevent common issues like memory leaks, unnecessary rebuilds, and crashes caused by accessing disposed objects.
“Most Flutter bugs come from misunderstanding the widget lifecycle.”
@override
void initState() {
super.initState();
}7. What is the Flutter application lifecycle?
The application lifecycle refers to how the entire app behaves when it moves between foreground, background, or inactive states. Flutter provides hooks to listen to these changes using WidgetsBindingObserver. This is important for handling things like pausing animations, saving data, or stopping network calls when the app is backgrounded.
Unlike widget lifecycle, this lifecycle is about the app as a whole, not individual UI components.
“Apps should respect the user’s device and system resources.”
8. What is BuildContext in Flutter?
BuildContext represents the location of a widget in the widget tree. It allows a widget to access information from its ancestors, such as themes, media queries, and inherited data. Many Flutter APIs depend on BuildContext, which is why using the correct context is very important.
Beginners often face errors because they try to use BuildContext before the widget is fully built or use the wrong context from a different widget tree.
“Context is not global — it belongs to a position in the tree.”
Theme.of(context);9. What is Hot Reload and why is it important?
Hot Reload allows developers to apply code changes instantly while keeping the current app state. This makes UI development extremely fast and encourages experimentation. Instead of restarting the app for every small change, developers can iterate quickly and visually.
Hot Reload is one of the biggest reasons Flutter is loved by developers.
“Hot Reload turns UI development into a conversation, not a waiting game.”
10. What is pubspec.yaml and why is it important?
The pubspec.yaml file is the configuration file of a Flutter project. It defines project metadata, dependencies, assets, fonts, and environment settings. Flutter relies heavily on this file to manage packages and resources.
A small mistake in pubspec.yaml can cause build failures, missing assets, or runtime errors, so understanding it is essential even for beginners.
dependencies:
flutter:
sdk: flutterQuestion 11: What is the difference between var, final, and const in Dart?
var is used for variables that can change values, final is used for variables that can be assigned only once at runtime, and const is used for compile-time constants whose values never change. Choosing the right type improves code safety, readability, and performance, especially in Flutter apps where immutability and widget rebuilding are critical.
“Use
constfor fixed values,finalfor runtime constants, andvarwhen the value may change."
var count = 5;
count = 10; // ✅ allowed
final name = "Flutter";
// name = "Dart"; // ❌ not allowed
const pi = 3.14;
// pi = 3.141; // ❌ not allowedQuestion 12: What is Null Safety in Dart?
Null safety in Dart ensures variables cannot contain null unless explicitly declared nullable. This prevents runtime null errors, making your Flutter apps more stable. Use ? for nullable types, ! to assert non-null, and ?? to provide default values.
“Null safety moves null errors from runtime to compile time, making code safer.”
String? title; // nullable
print(title ?? "Default Title");
String name = "Flutter";
// name = null; // ❌ not allowedQuestion 13: What is the difference between List, Set, and Map in Dart?
List stores ordered elements and allows duplicates, Set stores unique elements without guaranteed order, and Map stores key-value pairs for fast lookups. Choosing the right collection improves code clarity and performance.
“Use List for order, Set for uniqueness, and Map for key-based access.”
List<int> nums = [1, 2, 2, 3];
Set<int> uniqueNums = {1, 2, 2, 3};
Map<String, String> user = {"name": "Shirsh", "role": "Flutter Dev"};Question 14: What is the difference between async/await and Future in Dart?
Future represents a value available later, often from async operations like API calls. async and await let you write asynchronous code in a readable, synchronous style, avoiding nested .then() callbacks.
“Future is a promise; async/await is how you wait for it clearly.”
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return "Data loaded";
}
void main() async {
print(await fetchData());
}Question 15: What are Streams and when to use them in Dart?
Streams are sequences of asynchronous events. Use them for multiple values over time, like live data updates, chats, or sensors. They differ from Future, which gives only one value.
“Use Streams when data arrives in chunks over time.”
Stream<int> counter() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() {
counter().listen((val) => print(val));
}Question 16: What is the difference between extends, implements, and with in Dart?
extends is used for inheritance, implements for interfaces, and with for mixins. Using them properly allows code reuse and clean OOP design in Flutter.
“Extends for is-a, implements for interface contract, with for reusable behavior.”
class Animal { void eat() => print("Eating"); }
class Dog extends Animal { void bark() => print("Barking"); }
class Flyer { void fly() => print("Flying"); }
class Bird extends Animal with Flyer {}
void main() {
Bird b = Bird();
b.eat();
b.fly();
}Question 17: What is Memory Management in Dart?
Dart uses garbage collection to automatically clean up objects that are no longer referenced. In Flutter, failing to dispose of controllers, streams, or other resources can cause memory leaks, so always clean up resources in dispose().
“Dispose what you own, and Dart will handle the rest.”
class MyWidget extends StatefulWidget {
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final controller = TextEditingController();
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
}Question 18: What is the difference between == and identical() in Dart?
== checks value equality, while identical() checks if two references point to the exact same object. Understanding this prevents bugs in comparisons, especially with lists or custom objects.
“Use == for content comparison, identical() for reference check.”
var a = [1, 2];
var b = [1, 2];
print(a == b); // true (values are equal)
print(identical(a, b)); // false (different objects)Question 19: What are Generics in Dart?
Generics allow you to write reusable and type-safe code. You can create classes or functions that work with any type while maintaining type safety, which is essential for scalable Flutter apps.
“Generics prevent runtime type errors and improve code reusability.”
class Box<T> {
T content;
Box(this.content);
}
void main() {
var intBox = Box<int>(123);
var stringBox = Box<String>("Hello Flutter");
}Question 20: What are Extension Methods in Dart?
Extension methods let you add new methods to existing classes without modifying them. They are useful in Flutter for utilities like formatting, string manipulation, or custom helper functions.
“Extension methods make your code cleaner and reusable without changing existing classes.”
extension StringExtensions on String {
String capitalize() => this[0].toUpperCase() + substring(1);
}
void main() {
print("flutter".capitalize()); // Flutter
}Question 21: What is the difference between StatelessWidget and StatefulWidget in Flutter?
A StatelessWidget is immutable and does not store any state; it only builds UI based on the input parameters. A StatefulWidget can maintain state across rebuilds, which is useful for dynamic UI changes like user interactions or animations.
“Use StatelessWidget for static UI and StatefulWidget when the UI changes dynamically.”
// StatelessWidget
class MyStateless extends StatelessWidget {
final String title;
MyStateless(this.title);
@override
Widget build(BuildContext context) {
return Text(title);
}
}
// StatefulWidget
class MyStateful extends StatefulWidget {
@override
State<MyStateful> createState() => _MyStatefulState();
}
class _MyStatefulState extends State<MyStateful> {
int counter = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Counter: $counter'),
ElevatedButton(
onPressed: () => setState(() => counter++),
child: Text('Increment'),
),
],
);
}
}Question 22: What is the Widget Lifecycle in Flutter?
Flutter widgets, especially StatefulWidgets, have a lifecycle that defines when they are initialized, updated, or disposed. Key methods include initState(), didChangeDependencies(), build(), didUpdateWidget(), and dispose().
“Understanding the widget lifecycle prevents bugs and resource leaks.”
class MyWidget extends StatefulWidget {
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
@override
void initState() {
super.initState();
print("Widget initialized");
}
@override
void dispose() {
print("Widget disposed");
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text("Hello Flutter");
}
}Question 23: What is BuildContext in Flutter?
BuildContext represents the location of a widget in the widget tree. It allows widgets to access inherited data such as themes, media queries, or provider state. Using the correct context is crucial to avoid runtime errors.
“Context is not global — it belongs to a widget’s position in the tree.”
Widget build(BuildContext context) {
return Text(
"Hello Flutter",
style: Theme.of(context).textTheme.headline6,
);
}Question 24: What is the Rendering Pipeline in Flutter?
The rendering pipeline is how Flutter draws widgets to the screen. It consists of widgets → elements → render objects, followed by layout, painting, and compositing. Understanding this helps optimize performance and debug UI issues.
“Knowing the pipeline helps you reduce rebuilds and improve app efficiency.”
// Simplified concept
Widget build(BuildContext context) {
return Container(
child: Text("Flutter renders widgets in a tree"),
);
}Question 25: What is the difference between Hot Reload and Hot Restart in Flutter?
Hot Reload updates the UI without losing the app state, making it fast for UI changes. Hot Restart rebuilds the app from main() and resets the state, useful when global variables or initialization changes.
“Hot reload for UI tweaks, hot restart for code structure changes.”
// Example usage is IDE-specific; no code needed
// Hot Reload updates current UI instantly
// Hot Restart restarts app and resets all statesQuestion 26: What is the difference between Container and SizedBox in Flutter?
Container is a versatile widget that can add padding, margin, decoration, and constraints. SizedBox is simpler and is used mainly to give fixed width and height or add spacing between widgets. Use SizedBox when you only need spacing to improve performance slightly.
“Use Container for styling and SizedBox for spacing or fixed size.”
// Container example
Container(
width: 100,
height: 100,
color: Colors.blue,
padding: EdgeInsets.all(10),
child: Text("Hello"),
);
// SizedBox example
SizedBox(
width: 20,
height: 20,
);Question 27: What is SafeArea in Flutter?
SafeArea automatically pads your widgets to avoid notches, status bars, and system UI overlays. It ensures that the UI is visible and accessible on all devices.
“SafeArea keeps your content safe from device intrusions.”
SafeArea(
child: Text("This text won't overlap status bar or notch"),
);Question 28:What is mean by responsive and adaptive apps?
Responsive:- responsive app has had its layout tuned for the available screen size. Often this means (for example), re-laying out the UI if the user resizes the window, or changes the device’s orientation. This is especially necessary when the same app can run on a variety of devices, from a watch, phone, or tablet, to a laptop or desktop computer.
Adaptive:- Adapting the app to run on different device types, such as mobile and desktop, requires dealing with mouse and keyboard input, as well as touch input. It also means there are different expectations about the app’s visual density, how component selection works (cascading menus vs bottom sheets, for example), using platform-specific features (such as top-level windows), and more.
Question 29: Difference between ListView and ListView.builder in Flutter
ListView is good for small, static lists, while ListView.builder is optimized for large or dynamic lists because it creates widgets lazily, improving performance.
“Use ListView.builder for large lists to reduce memory usage.”
// Static ListView
ListView(
children: [Text("Item 1"), Text("Item 2")],
);
// Dynamic ListView.builder
ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => Text("Item $index"),
);Question 30: What is CustomPainter in Flutter?
CustomPainter allows you to draw shapes, paths, and custom graphics on a canvas. It is useful for charts, custom UI, and animations that need low-level drawing control.
“Use CustomPainter for custom graphics and animations.”
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.blue
..strokeWidth = 4;
canvas.drawLine(Offset(0, 0), Offset(100, 100), paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}Question 31: How to implement Form Validation in Flutter?
Flutter provides Form and TextFormField widgets with validators to validate user input. It ensures that users enter correct data before submission.
“Always validate user input to prevent invalid data in your app.”
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter text';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print("Form is valid");
}
},
child: Text("Submit"),
)
],
),
);Question 32: Difference between Visibility and Opacity in Flutter
Visibility hides or shows a widget completely, optionally removing it from the layout. Opacity makes a widget transparent but still takes space. Use Visibility for conditional UI and Opacity for visual effects.
“Visibility affects layout, Opacity only affects appearance.”
// Visibility example
Visibility(
visible: false,
child: Text("Hidden"),
);
// Opacity example
Opacity(
opacity: 0.0,
child: Text("Invisible but occupies space"),
);Question 33: When to use setState() in Flutter?
setState() is used in StatefulWidgets to update the UI when the widget’s state changes. It triggers a rebuild of the widget tree for that widget. Use it for simple local state changes only; for complex or app-wide state, consider state management solutions like Provider or Riverpod.
“setState() is simple, but don’t overuse it for large or shared states.”
class CounterWidget extends StatefulWidget {
@override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int count = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: () => setState(() => count++),
child: Text('Increment'),
),
],
);
}
}Question 34: What is InheritedWidget in Flutter?
InheritedWidget allows data to be shared efficiently down the widget tree. Child widgets can access this data without passing it manually through constructors. It is the base of many state management solutions like Provider.
“InheritedWidget makes data available to all descendants in a performance-friendly way.”
class MyData extends InheritedWidget {
final int counter;
MyData({required this.counter, required Widget child}) : super(child: child);
static MyData of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<MyData>()!;
@override
bool updateShouldNotify(MyData oldWidget) => counter != oldWidget.counter;
}Question 35: What is Lifting State Up in Flutter?
Lifting state up means moving state from a child widget to a common ancestor so that multiple widgets can access or modify it. This prevents duplicated states and ensures synchronized UI updates.
“Lift state up to share it between widgets efficiently.”
class ParentWidget extends StatefulWidget {
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
int counter = 0;
void increment() => setState(() => counter++);
@override
Widget build(BuildContext context) {
return Column(
children: [
ChildWidget(counter: counter, onPressed: increment),
Text('Parent counter: $counter'),
],
);
}
}
class ChildWidget extends StatelessWidget {
final int counter;
final VoidCallback onPressed;
ChildWidget({required this.counter, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text('Child counter: $counter'),
);
}
}Question 36: What is Provider Basics in Flutter?
Provider is a lightweight state management solution that simplifies sharing data across widgets. It uses ChangeNotifier for state changes and Consumer or context.watch() to rebuild widgets efficiently.
“Provider makes state management simpler and less error-prone compared to manual lifting.”
class Counter with ChangeNotifier {
int value = 0;
void increment() {
value++;
notifyListeners();
}
}
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => Counter(),
child: MyApp(),
),
);
}Question 37: What is the difference between Provider, Riverpod, and BLoC in Flutter?
- Provider: Simple and easy, good for small to medium apps.
- Riverpod: Safer, testable, and independent of BuildContext. Supports global state and advanced features.
- BLoC: Event-driven, ideal for complex apps requiring separation of UI and business logic.
“Choose the right state management based on app complexity and team familiarity.”
// Provider example
Consumer<Counter>(
builder: (context, counter, child) => Text('Value: ${counter.value}'),
);Question 38: Explain Solid Principle.
The SOLID principles are a set of guidelines that can help developers design software that is easy to maintain, extend, and scale. These principles were first introduced by Robert C. Martin in his book “Agile Software Development, Principles, Patterns, and Practices,” and they have since become an important part of the software development community.
The SOLID principles are:
- Single Responsibility Principle (SRP): A class should have only one reason to change.
- Open-Closed Principle (OCP): Software entities (classes, modules, etc.) should be open for extension but closed for modification.
- Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types.
- Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use.
- Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.
Flutter is a framework for building cross-platform mobile applications, and these principles can be applied when designing and building apps with Flutter. Adhering to these principles can help you create a more maintainable, scalable, and flexible app.
Question 39: What is Riverpod deep dive in Flutter?
Riverpod is a modern state management solution that is safe, testable, and decoupled from BuildContext. It supports global providers, computed providers, and async providers for complex apps. Riverpod reduces boilerplate compared to Provider.
“Riverpod is the next-generation Provider — safer, more scalable, and testable.”
final counterProvider = StateProvider<int>((ref) => 0);Consumer(
builder: (context, ref, child) {
final count = ref.watch(counterProvider);
return Text('Value: $count');
},
);Question 40: What is BLoC pattern in Flutter?
BLoC (Business Logic Component) separates UI from business logic using Streams. Events are added, state is emitted, and the UI rebuilds based on state changes. Ideal for large, complex applications requiring testable code.
“BLoC enforces a clear separation of concerns and predictable state flow.”
// Simple BLoC example
class CounterBloc {
final _controller = StreamController<int>();
int _count = 0;Stream<int> get stream => _controller.stream;
void increment() {
_count++;
_controller.sink.add(_count);
} void dispose() => _controller.close();
}
Question 41: What are InheritedWidget internals in Flutter?
InheritedWidget is the foundation of Flutter’s state propagation. It stores data and notifies descendant widgets when the data changes. Widgets access it via BuildContext. All higher-level solutions like Provider are built on top of it.
“InheritedWidget allows data to flow efficiently through the widget tree.”
class MyData extends InheritedWidget {
final int counter;
MyData({required this.counter, required Widget child}) : super(child: child);
static MyData of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<MyData>()!;
@override
bool updateShouldNotify(MyData oldWidget) => counter != oldWidget.counter;
}Question 42: What is Typedef in Dart?
A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.
typedef ManyOperation(int firstNo , int secondNo);
//function signature
Add(int firstNo,int second){
print("Add result is ${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is ${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is ${firstNo/second}");
}
Calculator(int a, int b, ManyOperation oper){
print("Inside calculator");
oper(a,b);
} void main(){
ManyOperation oper = Add;
oper(10,20);
oper = Subtract;
oper(30,20);
oper = Divide;
oper(50,5);
}
---Question 43: How to use Sealed Classes for State Management?
Sealed classes define a limited set of subclasses, often used to represent states in Flutter. This allows exhaustive switch statements, improving readability and avoiding unhandled states.
“Sealed classes make state handling predictable and compile-time safe.”
sealed class LoginState {}
class LoggedOut extends LoginState {}
class Loading extends LoginState {}
class LoggedIn extends LoginState {}
void handleState(LoginState state) {
switch (state.runtimeType) {
case LoggedOut:
print("User logged out");
break;
case Loading:
print("Loading...");
break;
case LoggedIn:
print("User logged in");
break;
}
}Question 44: What is Dependency Injection in Flutter?
Dependency Injection (DI) is a pattern where objects receive their dependencies instead of creating them. DI improves testability, modularity, and reduces tight coupling. Provider or Riverpod are commonly used for DI in Flutter.
“Inject dependencies instead of creating them inside classes for cleaner and testable code.”
class ApiService {
void fetchData() => print("Fetching data...");
}
class Repository {
final ApiService api;
Repository(this.api);
}
void main() {
final apiService = ApiService();
final repo = Repository(apiService);
repo.api.fetchData();
}Question 45: What are Mixins in Flutter?
Mixins allow reusing a class’s code in multiple class hierarchies without inheritance. They are useful for adding common behaviors like logging, validation, or animations.
“Mixins are reusable behavior modules that avoid deep inheritance chains.”
mixin Logger {
void log(String msg) => print("Log: $msg");
}
class Service with Logger {
void fetch() => log("Fetching data...");
}
void main() {
Service().fetch(); // Log: Fetching data...
}Question 46: What is WidgetsBindingObserver in Flutter?
WidgetsBindingObserver allows a widget to listen to app lifecycle events, such as when the app is paused, resumed, or inactive. It’s useful for pausing animations, saving state, or releasing resources when the app goes to the background.
“Use WidgetsBindingObserver to respond to lifecycle changes efficiently.”
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print('App state changed to: $state');
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}Question 47: What is Tree Shaking in Flutter?
Tree shaking is a compiler optimization that removes unused code from your Flutter app, reducing app size and improving performance. It’s automatically applied in release builds.
“Tree shaking ensures your app only includes what’s actually used.”
// No code needed — just release build
// flutter build apk --releaseQuestion 48: Question: What are some famous apps built using Flutter?
Flutter is used by many big companies to build beautiful, high-performance apps across platforms. Here are the top 10:
- Google Ads — Manage and track advertising campaigns
- SBI YONO — State Bank of India’s mobile banking app
- Alibaba — E-commerce and shopping apps
- Reflectly — Journaling and mindfulness app
- Realtor.com — Real estate listings and property search
- Grab — Ride-hailing and delivery services app
- eBay Motors — Car buying and selling platform
- Tencent — Various apps including social and gaming apps
- Philips Hue — Smart lighting control app
- BMW App — Vehicle management and services
Question 49: What is Global Error Handling in Flutter?
Global error handling allows you to catch uncaught exceptions at the app level, both in Flutter widgets and Dart async code. It ensures that your app can log, report, or gracefully recover from unexpected errors instead of crashing.
“Global error handling is essential to maintain app stability and improve user experience.”
void main() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.dumpErrorToConsole(details);
};
runZonedGuarded(() {
runApp(MyApp());
}, (error, stackTrace) {
print('Caught by zone: $error');
});
}Question 50: What are vsync and TickerProvider in Flutter?
vsync and TickerProvider are used to control animations efficiently. vsync prevents animations from consuming resources when the widget is off-screen. Any StatefulWidget implementing TickerProviderStateMixin can provide vsync to animation controllers.
“Always provide vsync to animations to save battery and improve performance.”
class MyAnimatedWidget extends StatefulWidget {
@override
State<MyAnimatedWidget> createState() => _MyAnimatedWidgetState();
}
class _MyAnimatedWidgetState extends State<MyAnimatedWidget>
with TickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
)..repeat(reverse: true);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _controller,
child: FlutterLogo(size: 100),
);
}
}Question 51: Difference between Implicit and Explicit Animations in Flutter
- Implicit animations: Automatically animate changes in properties (e.g.,
AnimatedContainer,AnimatedOpacity). Easier to use for simple animations. - Explicit animations: Require an
AnimationControllerandAnimationobject, giving full control over animation behavior, timing, and sequences.
“Use implicit animations for simplicity, explicit animations for precision and complex effects.”
// Implicit animation example
AnimatedContainer(
duration: Duration(seconds: 1),
width: 100,
height: 100,
color: Colors.blue,
);
// Explicit animation example uses AnimationController (see previous question)Question 52: What are Staggered Animations in Flutter?
Get Shirsh Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
Staggered animations are animations where multiple properties or widgets animate with different start times or durations. They create smooth, sequential effects for complex UI interactions.
“Staggered animations make your UI feel more natural and lively.”
class StaggeredDemo extends StatefulWidget {
@override
State<StaggeredDemo> createState() => _StaggeredDemoState();
}
class _StaggeredDemoState extends State<StaggeredDemo>
with TickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _sizeAnimation;
late Animation<Color?> _colorAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
)..forward();
_sizeAnimation = Tween<double>(begin: 50, end: 150).animate(
CurvedAnimation(parent: _controller, curve: Interval(0.0, 0.5)),
);
_colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate(
CurvedAnimation(parent: _controller, curve: Interval(0.5, 1.0)),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
width: _sizeAnimation.value,
height: _sizeAnimation.value,
color: _colorAnimation.value,
);
},
);
}
}Question 53: How to Secure your Flutter Application?
For securing flutter application, you can follow these steps,
- Code obfuscation
- Manage background snapshots
- Stay up-to-date with your Flutter version
- Use Flushing in-memory cache
- Use local authentication
- Use Secure Storage
- Restrict network traffic
- Use jail-breaking protection
Question 54: What is Certificate Pinning in Flutter?
Certificate pinning ensures your app trusts only specific SSL certificates, preventing man-in-the-middle attacks. It is essential for apps dealing with sensitive data.
“Certificate pinning increases app security for production APIs.”
// Using Dio with certificate pinning
// Detailed implementation requires platform-specific setupQuestion 55: What is Secure Storage in Flutter?
Secure storage is used to store sensitive data like tokens or passwords securely. Packages like flutter_secure_storage encrypt data at the OS level.
“Never store sensitive info in plain SharedPreferences; use secure storage.”
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
final storage = FlutterSecureStorage();
await storage.write(key: 'token', value: 'abcd1234');
String? token = await storage.read(key: 'token');Question 56: What is Retry Logic with Exponential Backoff in Flutter?
Retry logic with exponential backoff retries failed network requests with increasing intervals. This reduces server load and improves reliability when network connectivity is unstable.
“Exponential backoff prevents hammering the server with repeated requests.”
Future<void> fetchWithRetry() async {
int retry = 0;
while (retry < 5) {
try {
await Dio().get('https://example.com/data');
break;
} catch (e) {
retry++;
await Future.delayed(Duration(seconds: 2 * retry));
}
}
}Question 57: What are the Three Trees (Widget / Element / RenderObject) in Flutter?
Flutter’s UI architecture uses three trees:
- Widget Tree: Immutable descriptions of the UI
- Element Tree: Holds the widget instances and manages their lifecycle
- RenderObject Tree: Handles layout, painting, and hit testing
“Understanding the three trees helps optimize Flutter rendering and debug UI issues.”
// Conceptual understanding — no direct code neededQuestion 58: What is the Impeller Rendering Engine in Flutter?
Impeller is Flutter’s next-generation rendering engine replacing Skia for better performance, smoother graphics, and predictable frame rendering, especially on mobile devices. It improves GPU efficiency and reduces jank.
“Impeller is designed for faster, smoother, and more consistent UI rendering.”
// Impeller is enabled in Flutter 3.13+ via project settings
// flutter build apk --releaseQuestion 59: Difference between AOT and JIT Compilation in Flutter
- AOT (Ahead-of-Time): Compiles Dart code into native machine code before running, used in release builds for performance.
- JIT (Just-in-Time): Compiles code at runtime, used in debug mode for features like hot reload.
“JIT for development speed, AOT for runtime performance.”
// Conceptual — controlled by Flutter build commands
// Debug: JIT | Release: AOTQuestion 60: What is Code Obfuscation in Flutter?
Code obfuscation makes your Flutter app’s Dart code harder to reverse-engineer. It renames classes, methods, and fields to reduce code readability, increasing security for production apps.
“Obfuscate release builds to protect your intellectual property.”
flutter build apk --release --obfuscate --split-debug-info=/<project>/debug-infoQuestion 61: What are Platform Channels in Flutter?
Platform Channels allow Flutter apps to communicate with native code (Android/iOS). You can execute platform-specific functionality such as accessing sensors, storage, or other APIs not available in Flutter.
“Platform channels bridge Flutter and native code for full device capabilities.”
// Dart side
static const platform = MethodChannel('samples.flutter.dev/battery');
Future<void> getBatteryLevel() async {
try {
final int level = await platform.invokeMethod('getBatteryLevel');
print('Battery level: $level%');
} on PlatformException catch (e) {
print("Failed to get battery level: '${e.message}'.");
}
}Question 62: What is FFI (Foreign Function Interface) in Flutter?
FFI allows Dart code to call C/C++ native libraries directly. It’s useful for high-performance operations, such as audio/video processing or heavy computation.
“FFI lets you reuse native code without writing platform-specific channels.”
import 'dart:ffi';
import 'dart:io';
final dylib = DynamicLibrary.open(Platform.isAndroid ? "libnative.so" : "native.dylib");Question 63: How to implement Deep Linking with go_router in Flutter?
Deep linking opens a specific screen in your app via a URL. go_router simplifies routing and supports nested routes, query parameters, and deep linking.
“Deep linking improves user navigation and allows external links to open specific pages.”
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => HomeScreen(),
),
GoRoute(
path: '/profile/:id',
builder: (context, state) {
final id = state.params['id'];
return ProfileScreen(userId: id!);
},
),
],
);Question 64: What is App Startup Optimization in Flutter?
App startup optimization focuses on reducing launch time by minimizing unnecessary work in main(), using deferred components, split AOT, and optimizing initial widget tree.
“Faster app startup improves user experience and retention.”
void main() {
WidgetsFlutterBinding.ensureInitialized();
// Initialize only essential services here
runApp(MyApp());
}Question 65: What types of tests can you perform?
There are three main kinds of tests: unit tests, widget tests, and integration tests.
Unit tests are all about checking the validity of your business logic.
Widget tests are for making sure UI widgets have the components that you expect them.
Integration tests check that your app is working as a whole.
For more information click here.
Question 66: How to Mock Dependencies in Flutter?
Mocking helps in unit testing by replacing real dependencies with fake implementations. Packages like mockito are used for creating mocks of APIs, services, or repositories.
“Mocking ensures tests are isolated and repeatable.”
class MockApiService extends Mock implements ApiService {}
void main() {
final mockApi = MockApiService();
when(mockApi.fetchData()).thenAnswer((_) async => 'Mock data');
}Question 67: What are Integration Tests in Flutter?
Integration tests test the app as a whole, including UI interactions, APIs, and platform integration. They ensure features work correctly across widgets and services.
“Integration tests catch issues that unit tests cannot, simulating real user interactions.”
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Counter increments test', (tester) async {
await tester.pumpWidget(MyApp());
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});
}Question 68: What is Golden Testing in Flutter?
Golden tests compare the rendered UI of widgets with a reference image to ensure visual consistency. It’s especially useful for complex UIs, themes, or animations.
“Golden tests prevent accidental UI regressions during development.”
testWidgets('MyWidget golden test', (tester) async {
await tester.pumpWidget(MyWidget());
await expectLater(
find.byType(MyWidget),
matchesGoldenFile('goldens/my_widget.png'),
);
});Question 69: How to Detect Memory Leaks in Flutter?
Memory leaks occur when objects are retained unnecessarily, leading to increased memory usage. You can detect leaks using DevTools, Flutter Observatory, and monitoring heap snapshots. Always dispose controllers, streams, and listeners.
“Proper resource cleanup prevents memory leaks and improves app performance.”
// Example: Dispose controllers to avoid leaks
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final controller = TextEditingController();
@override
void dispose() {
controller.dispose(); // Important!
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
}Question 70: What are Custom RenderObjects in Flutter?
Custom RenderObjects give low-level control over layout, painting, and hit testing. Use them for performance-critical widgets where default widgets are insufficient.
“Custom RenderObjects allow precise rendering while improving efficiency.”
class MyRenderBox extends RenderBox {
@override
void performLayout() {
size = constraints.biggest;
}
@override
void paint(PaintingContext context, Offset offset) {
final paint = Paint()..color = Colors.blue;
context.canvas.drawRect(offset & size, paint);
}
}Question 71: How to Implement Efficient Pagination in Flutter?
For large data sets, use lazy loading with ListView.builder and scroll listeners. Fetch data in chunks to avoid memory overload and ensure smooth scrolling.
“Efficient pagination keeps the UI responsive and improves memory usage.”
ListView.builder(
itemCount: items.length + 1,
itemBuilder: (context, index) {
if (index == items.length) {
fetchMoreData(); // Fetch next page
return CircularProgressIndicator();
}
return ListTile(title: Text(items[index]));
},
);Question 72: How to Cache API Responses in Flutter?
Caching reduces network calls and improves performance. Use packages like dio_cache_interceptor or implement local caching with shared_preferences or Hive for offline support.
“Caching improves app speed and reduces server load.”
// Simple shared_preferences cache example
final prefs = await SharedPreferences.getInstance();
prefs.setString('userData', jsonEncode(userData));
final cachedData = jsonDecode(prefs.getString('userData') ?? '{}');Question 73: How to Handle Runtime Permissions in Flutter?
Permissions like camera, location, or storage require runtime checks. Use the permission_handler package to request and check permissions safely.
“Always check and request permissions at runtime to prevent app crashes.”
import 'package:permission_handler/permission_handler.dart';
Future<void> checkCameraPermission() async {
if (await Permission.camera.request().isGranted) {
print("Camera permission granted");
} else {
print("Camera permission denied");
}
}Question 74: How to Use Background Tasks with WorkManager in Flutter?
WorkManager runs periodic or one-time background tasks on Android and iOS. It’s useful for syncing data, notifications, or heavy computations in the background.
“Background tasks keep your app functional even when not active.”
Workmanager().registerOneOffTask("1", "simpleTask");
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) {
print("Background task running: $task");
return Future.value(true);
});
}Question 75: How to Implement Push Notifications in Flutter?
Use Firebase Cloud Messaging (FCM) to send push notifications. Handle messages when the app is foreground, background, or terminated.
“Push notifications keep users engaged and informed.”
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Received message: ${message.notification?.title}');
});Question 76: How to Handle In-App Purchases in Flutter?
Use packages like in_app_purchase to manage product listing, purchases, and subscriptions. Validate receipts to ensure security.
“In-app purchases should be handled securely with proper validation.”
final _iap = InAppPurchase.instance;Question 77: How to Implement Analytics & Crash Reporting in Flutter?
Use Firebase Analytics to track user behavior and Firebase Crashlytics to monitor crashes. These tools help improve app quality.
“Analytics and crash reporting help make data-driven improvements.”
FirebaseCrashlytics.instance.log("User clicked button");
FirebaseAnalytics.instance.logEvent(name: "button_click");Question 78: How to Measure Code Coverage in Flutter?
Use flutter test --coverage to generate code coverage reports. This ensures critical parts of your app are tested and reduces bugs in production.
“High code coverage improves app reliability and maintainability.”
flutter test --coverage
genhtml coverage/lcov.info -o coverage/htmlQuestion 79: What are Feature Flags & A/B Testing in Flutter?
Feature flags allow developers to enable or disable features without redeploying the app. A/B testing helps experiment with UI/UX changes to see which version performs better.
“Feature flags and A/B testing help release features safely and optimize user experience.”
bool isNewFeatureEnabled = FeatureFlags.isEnabled('new_dashboard');
if (isNewFeatureEnabled) {
showNewDashboard();
} else {
showOldDashboard();
}Question 80: How to Implement a Design System in Flutter?
A design system ensures consistent UI components across the app. Define colors, typography, spacing, and reusable widgets to improve maintainability.
“A design system keeps your app visually consistent and scalable.”
class AppTheme {
static final lightTheme = ThemeData(
primaryColor: Colors.blue,
textTheme: TextTheme(bodyText1: TextStyle(fontSize: 16)),
);
}Question 81: How to Set Up CI/CD Pipeline for Flutter?
CI/CD automates building, testing, and deploying Flutter apps. Tools like GitHub Actions, Codemagic, and Bitrise are commonly used.
“CI/CD ensures faster releases and fewer manual errors.”
# GitHub Actions sample snippet
name: Flutter CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@v2
- run: flutter pub get
- run: flutter testQuestion 82: What is Modular Architecture in Flutter?
Modular architecture divides the app into self-contained modules, each with its own UI, state, and business logic. It improves scalability, maintainability, and testability.
“Modular architecture helps large apps stay organized and easy to maintain.”
lib/
└── features/
├── auth/
├── dashboard/
└── profile/Question 83: How to Handle App Update Management in Flutter?
App update management ensures users install the latest version. Use in-app update packages or store APIs to notify and enforce updates.
“Prompting users to update ensures they get bug fixes and new features.”
// Example: in_app_update package
final status = await InAppUpdate.checkForUpdate();
if (status.updateAvailable) InAppUpdate.performImmediateUpdate();Question 84: How to Implement Localization (i18n) in Flutter?
Localization allows apps to support multiple languages. Use arb files and flutter_localizations to manage translations.
“Localization improves app reach and user experience across regions.”
MaterialApp(
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: [Locale('en'), Locale('es')],
);Question 85: When should you use mainAxisAlignment and crossAxisAlignment?
We can use the crossAxisAlignment and mainAxisAlignment to control how row and column widgets align their children based on our choice.
The row’s cross-axis will run vertically, and the main axis will run horizontally. See the below visual representation to understand it more clearly.

The column’s cross-axis will run horizontally, and the main axis will run vertically. The below visual representation explains it more clearly.

Question 86: How to Design Large-Scale App Architecture in Flutter?
Large-scale apps require modular, scalable, and maintainable architecture. Use feature-based modules, clean architecture, and state management like Riverpod or BLoC. Proper separation of UI, business logic, and data layers is key.
“A well-structured architecture ensures app stability as it grows.”
lib/
└── features/
├── auth/
│ ├── data/
│ ├── domain/
│ └── presentation/
├── dashboard/
└── shared/Question 87: How to Implement Offline-First Architecture in Flutter?
Offline-first apps work without an internet connection, syncing data when available. Use local storage (Hive, SQLite) and background sync with retry logic.
“Offline-first improves user experience in poor network conditions.”
// Example: saving API response locally
final box = await Hive.openBox('cache');
box.put('user_data', apiData);Question 88: How to Implement Real-Time with WebSockets in Flutter?
WebSockets allow two-way communication for real-time updates like chat apps. Use packages like web_socket_channel to handle live data streams.
“WebSockets enable real-time features without constant polling.”
import 'package:web_socket_channel/web_socket_channel.dart';final channel = WebSocketChannel.connect(Uri.parse('wss://echo.websocket.org'));
channel.stream.listen((message) => print('Received: $message'));
channel.sink.add('Hello WebSocket');Question 89: What are the keys in Flutter and when to use it?
In Flutter, a Key is a unique identifier for a widget that allows Flutter to identify a widget from its previous state. Keys are used to identify widgets when the widget tree changes, so that Flutter can preserve state for those widgets.
There are several types of keys in Flutter, including:
GlobalKey: A global key is unique across the entire app, and is useful when you need to identify a widget from a different part of the app.UniqueKey: A unique key is unique within a widget's parent widget, and is useful when you need to identify a widget within a list of widgets.ValueKey: A value key is based on a value, such as a string or an integer, and is useful when you need to identify a widget within a list of widgets based on its value.
You should use keys in Flutter whenever you need to identify a widget and preserve its state. This is typically necessary when you are working with lists of widgets, or when you are building widgets that need to be able to update their state based on user interactions.
For example, if you have a list of items that can be reordered by the user, you can use keys to identify each item and preserve its state when it is reordered. Similarly, if you have a form with multiple input fields, you can use keys to identify each field and preserve its state as the user fills out the form.
It’s important to note that keys should only be used when necessary, as they can have a performance impact on your app. You should only use keys when you need to identify a widget and preserve its state, and you should choose the appropriate type of key based on your needs.
Question 90: What are Testing Strategies for Expert Flutter Apps?
Testing strategies include unit tests, widget tests, integration tests, and golden tests. Maintain a test pyramid, focusing more on unit and widget tests, and automating integration tests.
“A strong testing strategy ensures reliability and reduces production bugs.”
// Widget test example
testWidgets('Counter increments', (tester) async {
await tester.pumpWidget(MyApp());
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});Question 91: How to Monitor Performance in Flutter Apps?
Use Flutter DevTools, profiling tools, and Firebase Performance Monitoring to track CPU, memory, frame rates, and network calls. Identify and fix performance bottlenecks proactively.
“Monitoring performance helps deliver smooth, responsive apps.”
// Enable performance overlay
MaterialApp(
showPerformanceOverlay: true,
);Question 92: How to Sync State Across Devices in Flutter?
Syncing state across devices requires cloud storage, real-time databases (Firebase, Supabase), and conflict resolution. Keep local caching for offline access and synchronization logic for consistency.
“State sync ensures seamless user experience across multiple devices.”
// Firebase Realtime Database example
FirebaseDatabase.instance.ref('user_data').onValue.listen((event) {
final data = event.snapshot.value;
print('Synced data: $data');
});Question 93: What is the Impeller rendering engine and how does it improve Flutter performance?
Impeller is Flutter’s new GPU rendering engine, designed to replace Skia for smoother animations and fewer jank issues. It precompiles shaders, reduces frame drops, and ensures consistent 60–120fps performance across mobile and desktop platforms.
“Impeller makes Flutter animations buttery smooth and predictable.”
// Impeller usage is mostly internal; developers benefit automatically
// Ensure your Flutter version uses Impeller (Flutter 3.13+)
MaterialApp(
home: Scaffold(
body: Center(child: Text('Impeller rendering!')),
),
);Question 94: How does Flutter support WebAssembly (WASM) and why is it important for Flutter Web performance?
Flutter Web now supports WASM to execute Dart code faster than JavaScript. WASM reduces parsing time, improves CPU-intensive computations, and provides near-native performance for web apps.
“WebAssembly brings high performance to Flutter Web, especially for complex apps.”
// No direct code; ensure Flutter Web build targets WASM in future versions.Question 95: Explain tree-shaking and how Flutter removes unused code in release builds.
Tree-shaking removes unused functions, classes, and packages from release builds. This reduces app size and ensures faster startup, especially on Web.
“Remove what you don’t use to keep your app lean.”
flutter build apk --release
# Flutter automatically performs tree-shakingHere’s a simplified and clear version of Question 96 with explanation and example:
Question 96: What is a Stream in Flutter?
A Stream is a sequence of asynchronous events or data that you can listen to over time. Think of it like a pipe: when you put a value in one end, all listeners on the other end can receive it. Multiple listeners can receive the same data from the same stream.
“Streams help handle data that arrives over time, like user input, network responses, or sensor updates.”
// Example: simple stream
Stream<int> numberStream() async* {
for (int i = 1; i <= 3; i++) {
await Future.delayed(Duration(seconds: 1));
yield i; // send value to listeners
}
}
void main() {
numberStream().listen((value) {
print('Received: $value');
});
}
Output:
Received: 1
Received: 2
Received: 3Question 97: How do you create private variables in Dart?
In Dart, you use an underscore _ before a variable name to make it private. Unlike some other languages, Dart’s private variables are accessible anywhere within the same file, but cannot be accessed from other files.
“In Dart, private means file-level access, not just class-level.”
// File: example.dart
class Person {
String _name = "Shirsh"; // private variable
}
void main() {
var person = Person();
// print(person._name); // ❌ Error if accessed from another file
}Question 98: What is the event loop, and how is it related to isolates in Flutter?
The event loop is a core part of Flutter that manages the flow of events and updates the app’s state. It continuously listens for events (like user taps, network responses, or timers) and executes the corresponding code.
An isolate is a separate thread in Dart that runs independently of the main thread. Isolates are useful for heavy computations or tasks that would otherwise block the UI.
The event loop communicates with isolates by sending messages between them. This allows Flutter to run code concurrently without freezing the UI.
“The event loop keeps the app responsive, while isolates handle heavy tasks safely in the background.”
import 'dart:isolate';
void heavyTask(SendPort sendPort) {
int sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += i;
}
sendPort.send(sum);
}
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(heavyTask, receivePort.sendPort);
receivePort.listen((message) {
print('Result from isolate: $message');
});
}
Output:
Result from isolate: 499999500000Question 99: How to create Responsive Layouts in Flutter?
Responsive layouts adapt to different screen sizes and orientations. You can use MediaQuery, LayoutBuilder, and Flexible widgets to adjust the UI dynamically.
“Always make layouts adaptive for all screen sizes to improve user experience.”
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return width > 600
? Row(children: [Text("Wide screen")])
: Column(children: [Text("Narrow screen")]);
}Question 100: What is a Factory Constructor in Dart and how is it different from a Normal Constructor?
A factory constructor can control object creation. It can reuse an existing object instead of always creating a new one. This is useful for Singletons.
A normal constructor always creates a new object every time.
// Normal constructor - always creates new object
class CarNormal {
String make;
CarNormal(this.make);
}
// Factory constructor - can reuse object (Singleton)
class CarFactory {
static final CarFactory _instance = CarFactory._internal();
String make;
CarFactory._internal() : make = "Ford";
factory CarFactory() => _instance; // always returns same object
}
void main() {
var car1 = CarNormal("Toyota");
var car2 = CarNormal("Toyota");
print(identical(car1, car2)); // false
var car3 = CarFactory();
var car4 = CarFactory();
print(identical(car3, car4)); // true
}Key Difference:
- Normal constructor: always creates new objects
- Factory constructor: can reuse existing objects
In this article, we have covered all major Flutter and Dart interview questions, from beginner to advanced level, including the latest features and updates in Flutter 2025–2026. These questions are designed to help you understand the framework deeply and prepare effectively for your interviews.
Flutter is a powerful and versatile SDK, and knowing these concepts will not only help you in interviews but also make you a better Flutter developer.
We hope this guide helps you boost your confidence and crack your Flutter/Dart interviews!
Your Feedback Matters:
You can comment below and share which questions you would like us to add or if you have better or simpler explanations for any question. We love updating this guide to make it more helpful and easy to understand for everyone.
Have a nice day!🙂
No comments:
Post a Comment
Note: only a member of this blog may post a comment.