Dart Interview Questions and Answers
What is Dart?
- Dart is a client-optimized, open-source programming language developed by Google. It is designed for building fast applications on any platform, including mobile, web, desktop, and server.
What are the key features of Dart?
- Client-optimized for UI.
- Fast on all platforms (compiles to native code, JavaScript).
- Productive development (hot-reload, rich libraries, strong tooling).
- Familiar syntax (similar to C#, Java, JavaScript).
- Strongly typed (with type inference).
- Null safety.
- Asynchronous programming support (Futures, Streams, async/await).
- Object-oriented.
Explain the different ways Dart code can be executed.
- Dart VM (Just-In-Time - JIT): Used for fast development cycles (hot-reload) during development. Executes code directly.
- Ahead-of-Time (AOT) Compilation: Compiles Dart code to native machine code for production deployments on mobile, desktop, and server, providing high performance and fast startup times.
- Compilation to JavaScript: Compiles Dart code to JavaScript for running on the web, ensuring compatibility with web browsers.
What is the difference between var
, final
, and const
?
var
: A general-purpose way to declare a variable. The type is inferred by the compiler. The variable can be reassigned.final
: A variable that can only be set once. Its value is determined at runtime. Cannot be reassigned after initialization.const
: A compile-time constant. Its value must be known at compile time. Cannot be reassigned. More restrictive thanfinal
.
Explain Null Safety in Dart.
- Null safety is a feature (introduced in Dart 2.12) that helps prevent null reference errors at runtime. By default, variables are non-nullable unless explicitly marked with
?
(e.g.,int?
). The compiler enforces that you handle potential null values.
What are the different data types in Dart?
- Numbers (
int
,double
). - Strings (
String
). - Booleans (
bool
). - Lists (
List
). - Sets (
Set
). - Maps (
Map
). - Runes.
- Symbols.
dynamic
.Object
.Null
.
What is the difference between List
and Set
?
List
: An ordered collection of elements. Can contain duplicate elements. Elements are accessed by index.Set
: An unordered collection of unique elements. Does not allow duplicate elements. Optimized for checking if an element is present.
What is a Map in Dart?
- A Map is a collection that stores key-value pairs. Keys must be unique. Values can be duplicated. Optimized for retrieving a value based on its key.
Explain the different types of parameters in Dart functions.
- Required Positional: Parameters that must be provided in the correct order.
- Optional Positional: Parameters enclosed in square brackets
[]
. They can be omitted, and if not provided, their value isnull
(or a specified default value). - Named Parameters: Parameters enclosed in curly braces
{}
. They are identified by their name when calling the function. They can be optional by default or required using therequired
keyword (Dart 2.12+).
What is an anonymous function (lambda) in Dart?
- An anonymous function is a function without a name. They are often used for short, inline functions, such as callbacks or when working with collection methods like
map()
orforEach()
.
What is the arrow syntax (=>
) used for?
- The arrow syntax (
=>
) is a shorthand for functions that contain only a single expression. The expression's value is implicitly returned.
Explain the concept of Everything is an Object in Dart.
- In Dart, everything, including numbers, booleans, functions, and even
null
, is an object. All objects inherit from theObject
class.
What is the purpose of the dynamic
keyword?
- The
dynamic
keyword allows you to declare a variable that can hold values of any type. Type checking is deferred to runtime. Use with caution as it sacrifices compile-time type safety.
What is the difference between is
and as
operators?
is
: Checks if an object is of a specific type and returns a boolean (true
orfalse
).as
: Performs a type cast. If the cast is successful, it returns the object as the specified type; otherwise, it throws a runtime error.
What is the cascade notation (..
)?
- The cascade notation allows you to perform a sequence of operations on the same object without repeating the object name. It returns the original object.
What is the null-aware operator (??
)?
- The null-aware operator (
??
) provides a default value if the expression on the left is null.expression1 ?? expression2
returnsexpression1
if it's not null; otherwise, it returnsexpression2
.
What is the null-aware assignment operator (??=
)?
- The null-aware assignment operator (
??=
) assigns a value to a variable only if the variable is currently null.variable ??= value
is equivalent toif (variable == null) variable = value;
.
What is the null-conditional operator (?.
)?
- The null-conditional operator (
?.
) provides a safe way to access a member or call a method on an object that might be null. If the object is null, the expression evaluates to null instead of throwing aNullReferenceError
.
What is a Class in Dart?
- A class is a blueprint for creating objects. It defines the properties (instance variables) and behaviors (methods) that objects of that class will have.
What is a Constructor in Dart?
- A constructor is a special method used to create and initialize objects of a class. It has the same name as the class and no return type.
Explain Named Constructors.
- Named constructors allow you to create multiple constructors for a class with different names, enabling more descriptive ways to create objects.
What is a Factory Constructor?
- A factory constructor is a constructor that doesn't always create a new instance of the class. It can return existing instances, instances of subclasses, or perform other logic before returning an instance. Used with the
factory
keyword.
What is a Const Constructor?
- A const constructor creates a compile-time constant instance of a class. All instance variables must be final. Used with the
const
keyword.
Explain Inheritance in Dart.
- Inheritance is a mechanism where a class (subclass/derived class) can inherit properties and methods from another class (superclass/base class) using the
extends
keyword. It promotes code reusability and establishes an "is-a" relationship.
What is Method Overriding?
- Method overriding is the process of providing a new implementation in a subclass for a method that is already defined in the superclass. The method signature must be the same.
What is the purpose of the super
keyword?
- The
super
keyword is used in a subclass to refer to the superclass's members (methods, properties, constructors).
What is an Abstract Class?
- An abstract class is a class that cannot be instantiated directly. It is designed to be a base class for other classes. Abstract classes can contain both abstract methods (without implementation) and concrete methods (with implementation). Defined using the
abstract
keyword.
What is an Abstract Method?
- An abstract method is a method declared in an abstract class or interface without an implementation. Subclasses must provide an implementation for abstract methods.
What are Implicit Interfaces in Dart?
- Every class in Dart implicitly defines an interface with all its instance members. Other classes can implement this interface using the
implements
keyword.
What is the difference between extends
and implements
?
extends
: Used for inheritance. A class inherits from a single superclass.implements
: Used to implement one or more interfaces. A class must provide an implementation for all members of the implemented interfaces.
What is a Mixin?
- A mixin is a way to reuse class code in multiple class hierarchies. It allows a class to inherit the members of one or more mixins using the
with
keyword, without being a direct subclass of those mixins.
What is the purpose of the static
keyword?
- The
static
keyword makes a member (variable or method) belong to the class itself rather than to a specific instance of the class. Static members are accessed using the class name.
What is the difference between an Instance Variable and a Static Variable?
- Instance Variable: Each object of the class has its own copy of the instance variable.
- Static Variable: There is only one copy of the static variable, shared among all instances of the class.
What is an Enum?
- An enum (enumeration) is a special kind of class used to represent a fixed set of named constant values.
Explain Futures and Asynchronous Programming in Dart.
- Futures represent the result of an asynchronous operation that may complete at some point in the future. Asynchronous programming in Dart uses
Future
,async
, andawait
to perform operations without blocking the main thread.
What is the purpose of the async
and await
keywords?
async
: Marks a function as asynchronous. An async function can containawait
expressions.await
: Used within anasync
function to pause execution until aFuture
completes. The thread is not blocked; other code can run.
What is a Stream?
- A Stream represents a sequence of asynchronous events or data. It can emit zero or more events over time. Used for handling continuous data flows, like user input, network data, or file reading.
What is the difference between a Future and a Stream?
Future
: Represents a single asynchronous result that will be available in the future.Stream
: Represents a sequence of asynchronous results (events) that can arrive over time.
How do you handle errors in asynchronous operations (Futures)?
- Using
.catchError()
with theFuture
. - Using a
try-catch
block within anasync
function around theawait
expression.
What is an Isolate?
- An Isolate is an independent worker in Dart that has its own memory space. Isolates communicate with each other by sending messages. They are used to achieve true parallelism and prevent blocking the main thread for CPU-intensive tasks.
How do Isolates communicate with each other?
- Isolates communicate by sending messages back and forth through Ports (
SendPort
andReceivePort
). Data sent between Isolates must be "sendable" (typically primitive types or types that can be serialized).
What is the Pub package manager?
- Pub is Dart's package manager. It is used to manage dependencies (libraries and tools) for Dart projects, download packages from the Pub.dev repository, and publish your own packages.
What is the purpose of the pubspec.yaml
file?
- The
pubspec.yaml
file is the manifest file for a Dart project. It contains information about the project, its dependencies (dependencies
anddev_dependencies
), and other configuration.
What is the difference between dependencies
and dev_dependencies
in pubspec.yaml
?
dependencies
: Packages that are required for the application to run in production.dev_dependencies
: Packages that are only needed during development (e.g., testing frameworks, code generators, linters).
What is Generics in Dart?
- Generics allow you to write type-safe and reusable code by defining classes, methods, and functions with placeholder types (type parameters) that are specified when the type or method is used.
What is the purpose of the typedef
keyword?
- The
typedef
keyword is used to create an alias (a new name) for a function type or (in Dart 2.13+) any type. This can make code more readable.
What is the difference between throw
and rethrow
?
throw
: Throws a new exception. The stack trace starts from the point wherethrow
is called.rethrow
: Rethrows the currently caught exception, preserving the original stack trace. This is generally preferred when you catch an exception but want to let it propagate further up the call stack after performing some action.
What is the purpose of the late
keyword? (Null Safety)
- The
late
keyword is used to declare a non-nullable variable that will be initialized later, but before it is first accessed. This is useful for variables that cannot be initialized immediately but are guaranteed to be non-null by the time they are used.
What is the purpose of the required
keyword for named parameters? (Null Safety)
- The
required
keyword (used within the curly braces{}
) indicates that a named parameter must be provided when calling the function. The compiler will enforce this.
Explain String Interpolation in Dart.
- String interpolation allows you to embed expressions inside a string literal using
$variableName
or${expression}
. The expression's value is converted to a string and inserted into the original string.
What is the purpose of the ?.
operator (Null-conditional member access)? (revisited)
- Provides safe access to a member or method on a potentially null object.
What is the purpose of the ..
operator (Cascade notation)? (revisited)
- Allows performing multiple operations on the same object without repeating the object name.
What is the purpose of the ...
operator (Spread operator)? (Dart 2.3+)
- The spread operator is used to insert all elements of a collection into another collection literal (List, Set, or Map).
What is the purpose of Collection If and For? (Dart 2.3+)
- Collection
if
allows you to conditionally include elements in a collection literal. - Collection
for
allows you to generate elements for a collection literal based on a loop.
What is the difference between final
and const
? (revisited)
final
: Runtime constant, initialized once.const
: Compile-time constant, value known at compile time.
What are Runes?
- Runes are the integer representation of Unicode code points. Dart uses runes to represent the characters of a string.
What are Symbols?
- A Symbol object represents an operator or identifier declared in a Dart program. They are used for reflection and by some APIs, but less commonly used in typical application code.
What is the main function (main()
)?
- The
main()
function is the entry point for every Dart program. Execution begins here.
How do you read input from the console in Dart?
- Using
stdin.readLineSync()
from thedart:io
library.
How do you write output to the console in Dart?
- Using the
print()
function.
What is the purpose of the assert
keyword?
- The
assert
keyword is used for debugging. It checks if a boolean condition is true. If the condition is false, anAssertionError
is thrown. Assertions are only active in debug mode.
What is the difference between an error and an exception?
- Error: Represents a program error that you should not try to catch (e.g., stack overflow, out of memory). Usually indicates a bug in the code.
- Exception: Represents a condition that can be handled (e.g., file not found, network error). You can use
try-catch
to handle exceptions.
What is the purpose of the covariant
keyword?
- The
covariant
keyword is used with parameter types in method overrides to allow a more specific type in the subclass method parameter than in the superclass method parameter.
What is the purpose of the typedef
keyword? (revisited)
- Creates an alias for a function type or any type.
What is the purpose of the show
and hide
keywords in imports?
show
: Specifies which members from a library should be imported.hide
: Specifies which members from a library should *not* be imported.
What is Deferred Loading (Lazy Loading) in Dart?
- Deferred loading allows you to load a library only when it's needed during runtime. This is useful for reducing the initial load time of an application, especially for parts of the app that are not immediately required. Used with
deferred as
.
What is the purpose of the part
and part of
keywords?
part
: Used in a library file to indicate that the implementation of a class or other members is in a separate file.part of
: Used in a separate file to indicate that it is part of a larger library. This allows splitting large libraries into multiple files while still being treated as a single unit.
What is the purpose of the external
keyword?
- The
external
keyword is used to declare a method or function that is implemented outside of the Dart code, typically in native code (using FFI) or JavaScript (for web).
What is Dart FFI (Foreign Function Interface)?
- Dart FFI allows Dart code to directly call functions and access data in native code libraries (like C libraries).
What is the purpose of the @override
annotation?
- The
@override
annotation is used to mark a method or getter/setter in a subclass that is intended to override a member from the superclass. It helps the compiler detect errors if the signature doesn't match.
What is the purpose of the @required
annotation? (Deprecated in favor of required
keyword)
- The
@required
annotation was used before Dart 2.12 (null safety) to indicate that a named parameter was mandatory. It is now superseded by therequired
keyword.
What is the purpose of the @immutable
annotation?
- The
@immutable
annotation is used to indicate that a class and its subclasses are immutable (their state cannot change after creation). This is a hint for analysis tools and doesn't enforce immutability at runtime.
What is the purpose of the @visibleForTesting
annotation?
- The
@visibleForTesting
annotation is used to mark private members (those starting with_
) that are intentionally made visible for testing purposes.
What is Dart DevTools?
- Dart DevTools is a suite of performance and debugging tools for Dart and Flutter applications. It includes inspectors for UI layout, performance monitoring, memory debugging, and more.
What is the Dart Analyzer?
- The Dart Analyzer is a static analysis tool that checks Dart code for errors, warnings, and style issues without running the code. It helps catch potential problems early in the development process.
What is the purpose of dart format
?
dart format
is a command-line tool that automatically formats Dart code according to the standard Dart style guide. This helps maintain consistent code style across a project.
What are Effective Dart guidelines?
- Effective Dart is a set of guidelines for writing idiomatic, readable, and maintainable Dart code. It covers style, documentation, usage, and design.
What is the difference between a mutable and immutable object?
- Mutable Object: An object whose state can be changed after it is created.
- Immutable Object: An object whose state cannot be changed after it is created. New objects are created for any modifications.
How do you create an immutable List in Dart?
- You can use
List.unmodifiable(anotherList)
or create a const list literal (const [1, 2, 3]
).
How do you create an immutable Map in Dart?
- You can use
Map.unmodifiable(anotherMap)
or create a const map literal (const {'a': 1, 'b': 2}
).
What is the difference between ==
and identical()
?
==
: By default, for objects, it checks if they are the same instance. Classes can override the==
operator to provide value-based equality.identical()
: Checks if two references point to the exact same object in memory.
What is the purpose of the hashCode
getter?
- The
hashCode
getter returns an integer hash code for an object. It is used by hash-based collections (likeSet
andMap
) for efficient lookup. If you override the==
operator for value-based equality, you must also overridehashCode
to ensure that equal objects have the same hash code.
What is the purpose of the covariant
keyword? (revisited)
- Allows a more specific type for a parameter in an overridden method.
What is the purpose of the sealed
keyword? (Dart 2.17+)
- The
sealed
keyword is used with classes or mixins. It prevents a class from being extended or implemented outside of its own library. This allows the compiler and analysis tools to know the complete set of possible subtypes within the library, enabling exhaustive checking in switch statements.
What is the purpose of the interface
keyword? (Dart 2.17+)
- While every class implicitly defines an interface, the explicit
interface
keyword can be used to declare an interface that cannot be extended, only implemented.
What is the purpose of the base
keyword? (Dart 2.17+)
- The
base
keyword is used with classes. Abase
class can only be extended, not implemented, outside of its own library.
What is the purpose of the final
keyword on classes? (Dart 3.0+)
- A
final
class can only be extended within the same library and cannot be implemented anywhere.
What is the purpose of the record
type? (Dart 3.0+)
- Records are lightweight, immutable, fixed-size, unnamed, aggregate types. They are useful for returning multiple values from a function or grouping related data.
What are Patterns in Dart? (Dart 3.0+)
- Patterns are a set of language features that allow you to match against the "shape" of data and deconstruct it. They are used in switch statements, if-case statements, variable declarations, and more.
What is a Switch Expression? (Dart 3.0+)
- A switch expression is a concise way to evaluate a series of patterns against an expression and return a value based on the first matching pattern.
What is an If-Case statement? (Dart 3.0+)
- An if-case statement allows you to match a single pattern against an expression and execute a block of code if the pattern matches.
What is List Pattern? (Dart 3.0+)
- A list pattern is used to match against lists and deconstruct their elements.
What is Map Pattern? (Dart 3.0+)
- A map pattern is used to match against maps and deconstruct their key-value entries.
What is Object Pattern? (Dart 3.0+)
- An object pattern is used to match against objects and deconstruct their properties.
What is the purpose of the _
(underscore) for variable names?
- When used as the first character of a variable, function, class, or library name, the underscore makes the member private to its library.
What is the purpose of the _
(underscore) as a wildcard pattern? (Dart 3.0+)
- In pattern matching, a single underscore
_
is a wildcard pattern that matches anything and discards the value.
What is the purpose of the _
(underscore) for unused variables?
- A single underscore
_
can be used as a variable name for an unused variable to indicate to the reader and the analyzer that the variable is intentionally not used.
What is the difference between dynamic
and Object?
?
dynamic
: Opts out of static type checking. Operations on adynamic
variable are checked at runtime.Object?
: A nullable variable that can hold any type of object, includingnull
. Static type checking is still performed, but you must handle the possibility ofnull
.
What is the purpose of the covariant
keyword? (revisited)
- Allows a more specific parameter type in an overridden method.
What is the purpose of the sealed
keyword? (revisited)
- Restricts subclassing/implementation to the same library, enabling exhaustive checking.
What is the purpose of the interface
keyword? (revisited)
- Explicitly declares an interface that can only be implemented.
What is the purpose of the base
keyword? (revisited)
- Requires subclasses to be in the same library.
What is the purpose of the final
keyword on classes? (revisited)
- Limits extension to the same library and prevents implementation.
What is the purpose of the record
type? (revisited)
- Lightweight, immutable aggregate type for grouping data.
What are Patterns in Dart? (revisited)
- Features for matching and deconstructing data structures.
What is a Switch Expression? (revisited)
- A concise way to return a value based on pattern matching.
What is an If-Case statement? (revisited)
- Matches a single pattern and executes a code block.
What is List Pattern? (revisited)
- Pattern for matching and deconstructing lists.
What is Map Pattern? (revisited)
- Pattern for matching and deconstructing maps.
What is Object Pattern? (revisited)
- Pattern for matching and deconstructing objects.
What is the purpose of the extension
keyword?
- The
extension
keyword allows you to add new functionality (methods, getters, setters, operators) to existing libraries or classes without modifying their source code.
What is the difference between a Callable Class and a function?
- A Callable Class is a class that can be called like a function by implementing the
call()
method. This is useful when you need an object that also behaves like a function, potentially with internal state.
What is the purpose of the typedef
keyword? (revisited)
- Creates an alias for a function type or any type.
What is the purpose of the @pragma
annotation?
- The
@pragma
annotation provides hints to the Dart compiler or other tools. For example,@pragma('vm:prefer-inline')
suggests that the VM should try to inline a method.
What is the purpose of the external
keyword? (revisited)
- Declares a member that is implemented outside of the Dart code.
What is the purpose of the library
keyword?
- The
library
keyword is used at the top of a file to declare the library name. This helps in organizing and importing code.
What is the purpose of the export
keyword?
- The
export
keyword is used in a library file to make members from another library directly available to users of the current library, without the user needing to import the other library explicitly.
What is the purpose of the part
and part of
keywords? (revisited)
- Used to split a large library into multiple files.
What is the purpose of the covariant
keyword? (revisited)
- Allows a more specific parameter type in an overridden method.
What is the purpose of the sealed
keyword? (revisited)
- Restricts subclassing/implementation to the same library, enabling exhaustive checking.
What is the purpose of the interface
keyword? (revisited)
- Explicitly declares an interface that can only be implemented.
What is the purpose of the base
keyword? (revisited)
- Requires subclasses to be in the same library.
What is the purpose of the final
keyword on classes? (revisited)
- Limits extension to the same library and prevents implementation.
What is the purpose of the record
type? (revisited)
- Lightweight, immutable aggregate type for grouping data.
What are Patterns in Dart? (revisited)
- Features for matching and deconstructing data structures.
What is a Switch Expression? (revisited)
- A concise way to return a value based on pattern matching.
What is an If-Case statement? (revisited)
- Matches a single pattern and executes a code block.
What is List Pattern? (revisited)
- Pattern for matching and deconstructing lists.
What is Map Pattern? (revisited)
- Pattern for matching and deconstructing maps.
What is Object Pattern? (revisited)
- Pattern for matching and deconstructing objects.
What is the purpose of the extension
keyword? (revisited)
- Adds functionality to existing types without modifying source.
What is the difference between a Callable Class and a function? (revisited)
- A class that can be called like a function via the
call()
method.
What is the purpose of the typedef
keyword? (revisited)
- Creates an alias for a function type or any type.
What is the purpose of the @pragma
annotation? (revisited)
- Provides hints to the compiler or tools.
What is the purpose of the external
keyword? (revisited)
- Declares a member implemented outside of Dart code.
What is the purpose of the library
keyword? (revisited)
- Declares the library name for a file.
What is the purpose of the export
keyword? (revisited)
- Makes members from another library available to the current library's users.
What is the purpose of the part
and part of
keywords? (revisited)
- Used to split a large library into multiple files.