Top 100 Flutter Interview Questions

In this article we will discuss about some all major Flutter and Dart Interview Question, that probably chanse to ask by interviewer.

Flutter is a great open-source software development kit, Flutter is developed by Google. Below are some Flutter developer interview questions that will help you better understand this framework. Besides providing you with an idea of the Flutter interview questions, we will also give you tips for ace the Flutter interview.
Flutter interview questions and answers will be of great help to you, whether you are a candidate looking for interview questions or a recruiter who is looking to find talented Flutter developers.

So let’s start with some simple questions and then we will discuss some deep inside things,

1)What is Flutter?
Flutter is an open-source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase.
Flutter is not a language; it is an SDK. Flutter apps use the Dart programming language for creating an app. The first alpha version of Flutter was released in May 2017.

2) What is Dart?
It is open-source and developed by Google in 2011. The purpose of Dart programming is to create frontend user interfaces for the web and mobile apps.
Dart is a client-optimized language for developing fast apps on any platform. Its goal is to offer the most productive programming language for multi-platform development.

3)What are the Flutter widgets?
Flutter widgets are built using a modern framework that takes inspiration from React. The central idea is that you build your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against the previous description to determine the minimal changes needed in the underlying render tree to transition from one state to the next.

4) What is the Difference Between Stateless and Stateful Widget in Flutter?

A stateless widget is useful when the part of the user interface you are describing does not depend on anything other than the configuration information and the BuildContext whereas a Stateful widget is useful when the part of the user interface you are describing can change dynamically.

A Stateful Widget is a mutable widget that is the reason it can be drawn multiple times within its lifetime.
It is referred to as dynamic because it can change the inner data during the widget's lifetime. A widget that allows us to refresh the screen is called a Stateful widget. This widget does not have a build() method. It has the createState() method, which returns a class that extends the Flutters State Class. The examples of the Stateful widget are Checkbox, Radio, Slider, InkWell, Form, and TextField.

A Stateless widget will never rebuild by itself but can from external events.
The Stateless widget does not have any state information. It remains static throughout its lifecycle. Examples of the Stateless widget are Text, Row, Column, Container, etc. If the screen or widget contains static content, it should be a Stateless widget, but if you want to change the content, it needs to be a Stateful widget.

5) What is StatefulWidget LifeCycle?

The lifecycle has the following simplified steps:

  • createState(): When we build a new StatefulWidget, this one calls createState() right away and this override method must exist.
  • initState(): It is the first method called after the Widget is created.This is our equivalent to onCreate() and viewDidLoad()
  • didChangeDependencies() : This method is called immediately after initState() on the first time the widget is built.
  • build() : This is called right after didChangeDependencies(). All the GUI is rendered here and will be called every single time the UI needs to be rendered.
  • didUpdateWidget(): It’ll be called once the parent Widget did a change and needs to redraw the UI.
  • deactivate(): Framework calls this method whenever it removes this State object from the tree
  • dispose(): It is called when this object and its State are removed from the tree permanently and will never build again.

For more detail click here.

6) What is AppLifecycleState?

AppLifecycleState is as follows:

  • inactive — The application is in an inactive state and is not receiving user input. (iOS only).
  • paused — The application is not currently visible to the user, not responding to user input, and running in the background.
  • resumed — The application is visible and responding to user input.
  • suspending — The application will be suspended momentarily. (Android only).

For more detail click here.

7) What is pubspec.yaml file?
It is responsible for handling importing images/fonts/third-party packages which you want to include in your project.
The pubspec. yaml file is used to define the dependencies of your Flutter project. This metadata information is written in the YAML language. This file can have the following fields name, version, description, homepage, repository, documentation, dependencies, environment, and more about the pubspec.yaml file.

8) what is the difference between a flutter package and the flutter plugin.
A “package” contains only Dart code.
A “plugin” contains both Dart and Native code (kotlin/js/swift/…)

Flutter plugins: (Native-related developments).
Flutter plugin is the wrapper of the native code like android( Kotlin or java) and iOS(swift or objective c)
Flutter can do anything that a native application can through the use of Platform Channels and Message Passing. Flutter instructs the native iOS/Android code to act and returns the result to Dart.

Flutter packages or modules: (Make the development faster by using code from util libraries).
Flutter supports using shared packages contributed by other developers to the Flutter and Dart ecosystems. This allows for quickly building an app without having to develop everything from scratch.

A package can use plugins if it wants to. It will still qualify as a package.

9) What is the difference between WidgetsApp and MaterialApp?

WidgetsApp:- A convenience class that wraps several widgets that are commonly required for an application.
One of the primary roles that WidgetsApp provides is binding the system back button to pop the Navigator or quitting the application.

MaterialApp:- A convenience widget that wraps several widgets that are commonly required for material design applications.
It builds upon a WidgetsApp by adding material-design specific functionality, such as AnimatedTheme and GridPaper.

10) What’s the difference between hot reload and hot restart?

In simple words,
Hot Reload is just updating the changes in your program.
But Hot Restart will again remove your previous state and run the complete program.

Hot Reload

  • Flutter hot reload features works with a combination of the Small r key on the command prompt or Terminal.
  • The hot reload feature quickly compile the newly added code in our file and sent the code to Dart Virtual Machine. After done updating the Code Dart Virtual Machine update the app UI with widgets.
  • Hot Reload takes less time than Hot restart.
  • There is also a drawback in Hot Reload, If you are using States in your application then Hot Reload preservers the States so they will not update on Hot Reload our set to their default values.

Hot Restart

  • A hot restart is much different from a hot reload.
  • In Hot restart, it destroys the preserved State value and set them to their default. So if you are using state value in your application then after every hot restart the developer gets a fully compiled application and all the states will be set to their defaults.
  • The app widget tree is completely rebuilt with a new type of code.
  • Hot Restart takes much higher time than Hot reload.

11) Can you nest a Scaffold? Why or why not?

Yes, you can nest a Scaffold. That’s the beauty of Flutter. You control the entire UI.
Scaffold is just a widget, so you can put it anywhere a widget might go. By nesting a, you can layer drawers, snack bars, and bottom sheets.

12) Describe Some of the major features of Flutter.

Some of the major features of using Flutter are,

Fast Development — With the use of a rich set of fully customizable widgets, you can build native interfaces in minutes with Flutter.

Expressive and Flexible UI — The layered architecture present with the Flutter enables you to fully customize your UI. This results in fast rendering and expressive designs.

Native Performance — The widgets present in the Flutter incorporate all the critical platform differences such as scrolling, navigation, icons, and more. It gives a full native performance on all platforms

13) How do you reduce widget rebuild?
You rebuild widgets when the state changes. This is normal and desirable because it allows the user to see the state changes reflected in the UI. However, rebuilding parts of the UI that don’t need to change is wasteful.

There are several things you can do to reduce unnecessary widget rebuilding.

  • The first is to refactor a large widget tree into smaller individual widgets, each with its build method.
  • Whenever possible, use the const constructor, because this will tell Flutter that it doesn't need to rebuild the widget.
  • Keep the subtree of a stateful widget as small as possible. If a stateful widget needs to have a widget subtree under it, create a custom widget for the stateful widget and give it a child parameter.

14) What is BuildContext and how is it useful?
BuildContext is the widget's element in the Element tree — so every widget has its own BuildContext.

You usually use BuildContext to get a reference to the theme or another widget. For example, if you want to show a material dialog, you need a reference to the scaffold. You can get it with Scaffold.of(context), where context is the build context. of() searches up the tree until it finds the nearest scaffold.

15) How do you talk to native code from within a Flutter app?
Normally you don’t need to talk to native code because the Flutter framework or third-party plugins handle it. However, if you do find yourself needing to get special access to the underlying platform, you can use platform channels.

One type of platform channel is a method channel. Data is serialized on the Dart side and then sent to the native side. You can write native code to interact with the platform before sending a serialized message back. That message might be written in Java or Kotlin on Android or Objective-C or Swift on iOS.

You don’t use platform channels on the web, however, because they’re an unnecessary step.

The second type of platform channel is the event channel, which you use to send a stream of data from the native platform back to Flutter. This is useful for monitoring sensor data.

16) 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.

17) What are the pros and cons of different state management solutions?
While there are countless varieties, some of the more popular state management solutions include BLoC, ChangeNotifier with Provider, Redux, MobX, and RxDart. These are all appropriate for medium- to large-scale apps, if you’re only making a quick demo app, then a stateful widget is often enough.

Instead of listing the pros and cons of each state management option, it’s more useful to look at the situations where a certain class of solutions is a better fit. For example, for someone who’s overwhelmed with the sheer number of options, it’s important to choose a solution that’s easy to grasp, mentally. ChangeNotifier with Provider or MobX would be a good choice because it makes sense to directly call methods on the state class in response to events.

If you’re heavily reliant on streams, such as with a Firebase API, then it’s natural to choose a stream-based solution like BLoC or RxDart.

And if you need undo/redo functionality, then you’d want a solution like BLoC or Redux that handles immutable states well.

18) What is Stream in Flutter?
A stream is a sequence of asynchronous events. It provides an asynchronous sequence of data. It is the same as a pipe where we put some value on one end, and if we have a listener on the other end, it will receive that value. We can keep multiple listeners in a stream, and all of those will receive the same value when put in the pipeline.

19) How to create private variables in Dart?
In dart '_' is used before the variable name to declare it as private. Unlike other programming languages, here private doesn't mean it is available only to the class it is in, private means it is accessible in the file it is in and not accessible to other files.

20) What is the event loop, and what is its relationship to isolates?
The Event Loop has one simple job to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
Dart code runs on a single thread called an isolate. Individual isolates don’t hang out together. An isolate is what all Dart code runs in. It’s like a little space on the machine with its own, private chunk of memory and a single thread running an event loop.
An isolate has its memory and a single thread of execution that runs an event loop.

21) What is the tree shaking in Flutter?
Tree shaking
is an optimization technique to remove the unused module in the bundle during the build process. It is a dead code elimination technique used to optimize the code.

22) What are DevTools in Flutter?
DevTools in Flutter
are a set of tools used for performance management and debugging. With these tools, you can inspect the UI layout, diagnose the UI performance issues, perform source-level debugging, view general log & diagnostics information, and more. This tool is still in preview release but you can test the alpha version of this tool by clicking the “beaker” icon in the upper-right corner of DevTools.

23) What is The Flex widget in Flutter?
The Flex widget allows you to control the axis along which the children are placed (horizontal or vertical). This is referred to as the main axis. If you know the main axis in advance, then consider using a Row (if it’s horizontal) or Column (if it’s vertical) instead, because that will be less verbose.

24) What are the differences between expanded and flexible widgets?
You may use Flexible to resize the widgets in rows and columns. It’s mainly used to adjust the space of the different child widgets while keeping the relationship with their parent widgets. Meanwhile, Expanded changes the constraints sent to the children of rows and columns; it helps to fill the available spaces there.

25) Material Vs Cupertino Widget?
Cupertino
widgets are used to build an iOS-like app and MaterialApp is used to build an Android (Material) app.
Material widgets implement the Material design language for iOS, Android, web, and desktop.
Cupertino widgets implement the current iOS design language based on Apple’s Human Interface Guidelines.
The Material Design language was created for any platform, not just Android. When you write a Material app in Flutter, it has the Material look and feels on all devices, even iOS. If you want your app to look like a standard iOS-styled app.
you would use the Cupertino library You can technically run a Cupertino app on either Android or iOS, but (due to licensing issues) Cupertino won’t have the correct fonts on Android. For this reason, use an iOS-specific device when writing a Cupertino app.

26) What is a Null Aware Operator?
Null-aware operators
in dart allow you to make computations based on whether or not a value is null. It’s shorthand for longer expressions. A null-aware operator is a nice tool for making nullable types usable in Dart instead of throwing an error.
The most common use of the Null aware operator is when a developer wants to parse JSON data from the server and after parsing JSON, the user can check whether the JSON is empty or not using the IF-Else condition.

27) What is Form, textfield and textFormField?
If you making a Form where you require to save, reset, or validate operations- use TextFormField. Else For Simple user input capture TextField is sufficient. TextFormField, which integrates with the Form widget.
This is a convenience widget that wraps a TextField widget in a FormField. A Form ancestor is not required. The Form simply makes it easier to save, reset, or validate multiple fields at once. To use without a Form, pass a GlobalKey to the constructor and use GlobalKey.currentState to save or reset the form field.

28) Difference between StreamBuilder and FutureBuilder?
FutureBuilder is used for one-time response, like taking an image from the Camera, getting data once from the native platform (like fetching device battery), getting file reference, making an HTTP request, etc.

On the other hand, StreamBuilder is used for fetching some data more than once, like listening for a location update, playing music, stopwatch, etc.

Both StreamBuilder and FutureBuilder have the same behavior: They listen to changes on their respective object. And trigger a new build when they are notified of a new value.
Future is like Promise in JS or Task in c#. They are the representation of an asynchronous request. Futures have one and only one response. A common usage of Future is to handle HTTP calls. What you can listen to on a Future is its state. Whether it’s done, finished with success, or had an error. But that’s it.
Stream on the other hand is like an async Iterator in JS. This can be assimilated into a value that can change over time. It usually is the representation of web sockets or events (such as clicks). By listening to a Stream you’ll get each new value and also if the Stream had an error or completed A Future can’t listen to a variable change. It’s a one-time response. Instead, you’ll need to use a Stream.

29) What is the Future?
A Future is used to represent a potential value, or error, that will be available at some time in the future. Receivers of a Future can register callbacks that handle the value or error once it is available.
To perform asynchronous operations in Dart, you can use the Future class and the async and await keywords. A future (lower case “f”) is an instance of the Future (capitalized “F”) class.
A future represents the result of an asynchronous operation and can have two states: uncompleted or completed.

30)What is the Difference between synchronous operation and synchronous function also Difference between asynchronous operation and asynchronous function?

synchronous operatil̥on: A synchronous operation blocks other operations from executing until it completes.
synchronous function: A synchronous function only performs synchronous operations.
asynchronous operation: Once initiated, an asynchronous operation allows other operations to execute before it completes.
asynchronous function: An asynchronous function performs at least one asynchronous operation and can also perform synchronous operations.

31) What is the difference between Method and function?

A simple way to remember:

  • Function → Free (Free means it can be anywhere, no need to be in an object or class)
  • Method → Member (A member of an object or class)

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class — the class is the definition, and the object is an instance of that data).

(this is a simplified explanation, ignoring issues of scope, etc.)

32) 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.

33) What is LayoutBuilder?
LayoutBuilder Widget is similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget’s constraints. This is useful when the parent constrains the child’s size and doesn’t depend on the child’s intrinsic size.

34) Difference between MediaQuery and LayoutBuilder?
the MediaQueryData.size property contains the width and height of the current window. You can use MediaQuery to retrieve the size (width/height) and orientation (portrait/landscape) of the screen.
The main difference between MediaQuery and LayoutBuilder is that MediaQuery uses the complete context of the screen rather than just the size of your particular widget, whereas LayoutBuilder can determine the maximum width and height of a particular widget.

35) Difference between Double.infinity vs MediaQuery?
The difference can be summarized into:

  • I want to be as big as my parent allows (double.infinity)
  • I want it to be as big as the screen (MediaQuery).

Usually, you’ll want to use it double.infinity, but it's not always possible.
Some Widgets allow their children to be as big as they want to be (Column, ListView, OverflowBox...).

In that situation using double.infinity creates a paradox:

  • The parent allows any size
  • The child wants the biggest size allowed by the parent

Using MediaQuery in these situations is bad though. You will rarely want to do that unless you're creating a widget similar to Scaffold.

36) What is the use of AspectRatio?
You can use the widget to size the child to a specific aspect ratio. This widget first tries the largest width permitted by the layout constraints and then decides the height by applying the given aspect ratio to the width.

37) What are dynamic, var, and final?
dynamic:
can change the TYPE of the variable, & can change the VALUE of the variable later in code.
var: can’t change TYPE of the variable, but can change VALUE of the variable later in code.
final: can’t change TYPE of the variable, & can’t change VALUE of the variable later in code.

38) Difference between Final vs const vs Static?
static” means a member is available in the class itself instead of on instances of the class. That’s all it means, and it isn’t used for anything else. static modifies *members*. A static variable retains its values till the program finishes execution. Static members are referenced by the class name.

final” means single-assignment: a final variable or field *must* have an initializer. Once assigned a value, a final variable’s value cannot be changed. final modifies *variables*.

The const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile time, and the object with this state will be considered frozen and completely immutable.

39) What are Getter and setter methods?
Getter and setter
methods are the class methods used to manipulate the data of the class fields. The getter is used to read or get the data of the class field whereas the setter is used to set the data of the class field to some variable.

40) What is Factory constructors?
Factory constructors are not actual constructors. They are functions hidden behind a fake constructor. They are used to replace static methods that you’d use in other languages So a factory constructor can be used — to create instances of subclasses (for example depending on the passed parameter — to return a cached instance instead of a new one — to prepare calculated values to forward them as parameters to a normal constructor so that final fields can be initialized with them. This is often used to work around limitations of what can be done in an initializer list of a normal constructor (like error handling).

41) What is State?
The state is information that,
we can be read synchronously when the widget is built and we might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using State.setState.

42) Difference between Ephemeral state vs App state?
Ephemeral State
-when your state variables are inside of the Stateful widget, it is known as an ephemeral state.

App State — When your state variables are outside of the Stateful widget, it's known as App state. (because that state is used by many widgets)
For managing the app state, you have to use a state management solution (inherited widget or third-party library).

43) Difference between dependencies vs dev_dependencies packages?
dependencies:
here we add a list of plugins that we have to include while deploying your App after the completion of your development stage.

dev_dependencies: here we add a list of plugins that you want to try out at the development stage to test the apps at the development stage.
For example: In the development stage, we use Mockito and test plugins and SDK to write the test cases and to test the complete behavior of the app. These kinds of plugins and SDKs we include in So in the release apps, there is no need of adding these plugins or SDK support.

44) What technology is Flutter built with?
Flutter is built with C, C++, Dart, and Skia (a 2D rendering engine). See this architecture diagram for a better picture of the main components. For a more detailed description of the layered architecture of Flutter, read the architectural overview.

45) Difference between deactivate and dispose?
Deactivte
: Called when this object is removed from the tree. deactivate is called when a widget may be dispose. But that is not guaranteed.
Dispose: Called when this object is removed from the tree permanently. By understanding both sentences, you’ll see that deactivate will be called for widgets that are removed from the tree, temporarily or permanently, whereas dispose will only be called for widgets being removed permanently.

46) Difference Between MVC, MVP, and MVVM Architecture Pattern?

The Model—View—Controller(MVC) Pattern
The MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:

  • Model: This component stores the application data. It does not know the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.
  • View: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.
  • Controller: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user’s response and updates the Model as per the need.

The Model—View—Presenter(MVP) Pattern
MVP pattern overcomes the challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:

  • Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.
  • View: UI(User Interface) layer. It provides the visualization of the data and keeps a track of the user’s action to notify the Presenter.
  • Presenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user’s input notification from the View.

The Model — View — ViewModel (MVVM) Pattern
MVVM pattern has some similarities with the MVP(Model — View — Presenter) design pattern as the Presenter role is played by the ViewModel. However, the drawbacks of the MVP pattern have been solved by MVVM. It suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are:

  • Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.
  • View: The purpose of this layer is to inform the ViewModel about the user’s action. This layer observes the ViewModel and does not contain any kind of application logic.
  • ViewModel: It exposes those data streams which are relevant to the View. Moreover, it serves as a link between the Model and the View.

47) What is the difference between debug mode and profile mode?
in Simple words, we Use debug mode during development, when you want to use hot reload. and we Use profile mode when you want to analyze performance.
Debug includes debugging information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled. As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

48) What is the difference between these operators ?? and ?.

Conditional Operators ( ? : )
The conditional operator is considered shorthand for the if-else statement. The conditional operator is also called a Ternary Operator.
var s = country1 != null ? "India" : "US";

a null-aware operator (??)
which returns the expression on its left unless that expression’s value is null, in which case it evaluates and returns the expression on its right:

print(1 ?? 3); // <-- Prints 1.
print(null ?? 12); // <-- Prints 12.

49) Differentiate between required vs optional vs named parameters in Dart.

Required Parameter

The required parameter is a well know old-style parameter which we are all familiar with it
example:

findVolume(int length, int breath, int height) {
print('length = $length, breath = $breath, height = $height');
}
findVolume(10,20,30);

output:

length = 10, breath = 20, height = 30

Optional Positional Parameter

the parameter will be disclosed with the square bracket [ ] & square bracketed parameters are optional.

example:

findVolume(int length, int breath, [int height]) {
print('length = $length, breath = $breath, height = $height');
}
findVolume(10,20,30);//valid
findVolume(10,20);//also valid

output:

length = 10, breath = 20, height = 30
length = 10, breath = 20, height = null // no value passed so height is null

Named Parameters:

These are parameters that can be passed in any order by passing the name of the parameter followed by the passed value. For example:

void sum({int num1, int num2});

This function is called this:

sum(num1: 12, num2: 24);

Also, named parameters can also have default values.

50) Explain the different types of Streams?
There are two kinds of streams.

1. Single subscription streams:-
The most common kind of stream. — It contains a sequence of events that are parts of a larger whole. Events need to be delivered in the correct order and without missing any of them. — This is the kind of stream you get when you read a file or receive a web request. — Such a stream can only be listened to once. Listening again later could mean missing out on initial events, and then the rest of the stream makes no sense. — When you start listening, the data will be fetched and provided in chunks.

2. Broadcast streams:-

  • It is intended for individual messages that can be handled one at a time. This kind of stream can be used for mouse events in a browser, for example.
  • You can start listening to such a stream at any time, and you get the events that are fired while you listen.
  • More than one listener can listen at the same time, and you can listen again later after canceling a previous subscription.

51) What are the keys in Flutter and when to use it?
A Key is an identifier for Widgets, Elements and SemanticsNodes.

  • A new widget will only be used to update an existing element if its key is the same as the key of the current widget associated with the element.
  • Keys must be unique amongst the Elements with the same parent.
  • Subclasses Key should either subclass LocalKey or GlobalKey.
  • Keys are useful when manipulating collections of widgets of the same type.
  • If you find yourself adding, removing, or reordering a collection of widgets of the same type that hold some state, then, you should use a key.

52) Explain async, await in Flutter?
An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.

Example:-
Future<void> test2() async {
var a = await fetchData();
}

53) How does Dart AOT work?
The AOT-compiled code runs inside an efficient Dart runtime that enforces the sound Dart type system and manages memory using fast object allocation and a generational garbage collector.

54) What are the similarities and differences between Future and Stream in Flutter?
Both futures and streams are parts of Dart. The main similarity between them is that they are both used for asynchronous programming.

also One of the main similarities is that both will return in the future(asynchronous). One difference is that Future only returns once. The stream will return again and again.

The main difference between them is:

  • a future is used for a value that may be not available right now, may become available at some later moment, and then will not change. We want to react when the value becomes available (and e.g. display it)
  • a stream is used when some value changes over time and we want to react to the changes (e.g. by displaying the current value)

55) What’s the difference between async and async* in Dart?
Marking a function as async or async* allows it to use the async/await for a Future.

The difference between both is that async* will always return a Stream and offer some syntactical sugar to emit a value through the yield keyword.

We can therefore do the following:

Stream<int> foo() async* {
for (int i = 0; i < 42; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}

This function emits a value every second, which increments every time.

56) Why does the first Flutter app build take so long?

When you build the Flutter app the first time, it will take a longer time. It is because Flutter built the device-specific APK or IPA file. Thus, the Gradle and Xcode are used to build the file, taking a long time.

57) What is the difference between “main()” and “runApp()” functions in Flutter?

We can differentiate the main and runApp functions in Flutter as below:

  • The main() function is responsible for starting the program. Without the main() function, we cannot write any program on Flutter.
  • The runApp() function is responsible for returning the widgets that are attached to the screen as a root of the widget tree and will be rendered on the screen.

58) 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.

59) What is the difference between SizedBox VS Container?

The Container in Flutter is a parent widget that can contain multiple child widgets and manage them efficiently through width, height, padding, background color, etc. If we have a widget that needs some background styling may be a color, shape, or size constraint, we may wrap it in a container widget.

The SizedBox widget in Flutter is a box that comes in a specified size. Unlike Container, it does not allows us to set the color or decoration for the widget. We can only use it for sizing the widget passed as a child. It means it forces its child widget to have a specific width or height.

60) Why is the build() method on State and not StatefulWidgets?
The main reason behind this is that the StatefulWidget uses a separate State class without building a method inside its body. It means all fields inside a Widget are immutable and includes all its sub-classes.

On the other hand, the StatelessWidget has its build and associated methods inside its body. It is due to the nature of StatelessWidget, which is rendered completely on the screen using the provided info. It also doesn’t allow any future changes in its State information.

The StatefulWidget allows us to change the State information during the app. Therefore, it is not suitable for storage in a build method to satisfy Widget class conditions where all fields are immutable. This is the main reason to introduce the State class. Here, we only need to override the createState() function to attach the defined State with the StatefulWidget, and then all expected changes happen in a separate class.

61) Why do we need mixins?
Dart does not support multiple inheritances. Thus to implement the multiple inheritances in Flutter/Dart, we need mixins. Mixins provide a way to write the reusable class’s code in multiple class hierarchies.

62) Why do we use a Ticker in Flutter?
Ticker in Flutter is a refresh rate of our animation. It is a class that sends a signal at a regular interval, i.e., around 60 times per second. We can understand it with our watch, which tics at regular intervals. At each tick, Ticker provides a callback method with the duration since the first ticks at each second, after it was started. Even if the tickers started at different times, they always synchronized automatically.

63) When to use mixins and when to use interfaces in Dart?
The difference lies in the concept. If you understand this, you will use it in the right way.

In OOP, an interface is something that enforces the deriving class to implement a set list of public fields and methods.

But unlike other traditional programming languages like C# and JAVA, Dart does not have explicit interface types. Each class, by default, defines its interface composed of public fields and methods. So, every class can act as an interface in Dart.

implements keyword is to implement an interface. Also, a class can implement multiple interfaces.

  1. In OOP, inheritance implies sharing of behavior between classes. We can not share features with an interface. So, when we implement a class, we can not share its behavior.

If you want to share the behavior across these two classes, you should use the extends keyword.

  1. In OOP, a mixin is a class that contains methods for use by other classes. Unlike the interface and inheritance approach, a mixin doesn’t have to be the parent class of those other classes.

So a mixin neither imposes usage restriction nor forces type restriction.

You will usually put common functions inside a mixin. Make use of the mixin by using the “with” keyword.

64) What is the Container class in flutter?
The Container class provides the ability to create a widget with certain properties like padding, borders, heighContainert, width, border, etc.

65) Can a container have more than one child?
A container is a Single-child layout widget. But it can have multiple children by using a Multi-child layout widget as its child.

66) What are the extension methods in Dart? Why use it?
Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.

67) In how many ways you can pass the parameters in Dart?
Mainly on the three ways, you can pass parameters:
default, optional, and named.
also, Dart functions allow positional parameters, named parameters, and optional positional and named parameters, or a combination of all of them. Positional parameters are the basic parameters, and they’re required.

68) How to access property or method conditionally in Dart?
?. is known as a Conditional Property access operator used to guard access to a property or method of an object that might be null, we put a question mark ( ? ) before the dot ( . ): This operator is widely used to prevent the access of the null object.

69) Explain the Spread operator.
In Dart, Spread Operator (…) and Null-aware Spread Operator (…?) are used for inserting multiple elements in a collection like Lists, Maps, etc.

Syntaxes:

  • Spread operator
...Data_structureExample:-
var a = [0,1,2,3,4];
var b = [6,7,8,9];
var c = [...a,5,...b];

print(c); // prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Null-aware Spread operator
...?Data_structureExmaple :-List<int> l1 = [1, 2, 3];List<int> nullList = null;List<int> result = [...l1, ...?nullList];print(result); // prints:   [1, 2, 3] 

70) Explain Provider Pub/Library in Flutter.
Provider is a wrapper around InheritedWidget to make them easier to use and more reusable. this is probably the approach you should start with. The provider package is easy to understand and it doesn’t use much code. It also uses concepts that are applicable in every other approach. By using provider instead of manually writing InheritedWidget, you get: — state management pattern and separate business logic from UI — simplified allocation/disposal of resources — lazy-loading — a largely reduced boilerplate over making a new class every time devtools friendly — a common way to consume these InheritedWidgets increased scalability for classes with a listening mechanism that grows exponentially in complexity (such as ChangeNotifier, which is O(N²) for dispatching notifications).

71) When to use Provider. of<X> vs. Consumer<X> in Flutter.
Provider.of is the only way to obtain and listen to an object. Consumer, Selector, and all the *ProxyProvider calls Provider.of to work.

Provider.of vs Consumer is a matter of personal preference. But there are a few arguments for both

Provider.of

  • can be called in all the widgets lifecycle, including click handlers and didChangeDependencies
  • doesn’t increase the indentation

Consumer

  • allows more granular widgets rebuilds
  • solves most BuildContext misuse

72) Why can’t I use context.read in build(), but I can use Provider.of with listen: false?
context.read is not allowed inside build because it is very dangerous to use there, and there are much better solutions available.

  • Provider.of is allowed in build for backward-compatibility.

Overall, the reasoning behind why context.read is not allowed inside build is explained in its documentation.

73) How to use multiple Consumers for a single widget in flutter Provider.
Yes you can add up to 6 consumers and will be as follows
Consumer2<AuthProvider, StorageProvider>(
builder: (context, authProvider, storageProvider, child) { }
)

There are some other Consumer widgets. Consumer2, Consumer3, Consumer4 till Consumer6. If you want to listen to 4 ChangeNotifier you can use Consumer4

Consumer4(
builder: (context, changeNotifier1, changeNotifier2, changeNotifier3, changeNotifier4, child) {
// your widget
}
)

74) What is the difference between Provider vs. InheritedWidget?
Yes. The provider is indeed mostly features based on Inheritedwidgets.

If you want to make your own, then that’s fine. But you’ll quickly realize that, without a provider, you’ll have hundreds of useless repetitive lines.

The provider takes the logic of InheritedWidgets but reduces the boilerplate to the strict minimum.

Provider is not a must, but should.

First of all, it’s promoted by Flutter Team and flexible enough to handle almost any state-management solution.

It might not be fair to say that InheritedWidget with dispose because Provider has too many different use cases and inherits some optimizations probably you won't find anywhere else.

If you use InheritedWidget it in a large application, build methods always rebuild the whole build method. But with Provider you have Consumer widget which is can be very specific to control specific blocks of build the method, so you have more efficiency. Also listeners have less complexity than InheritedWidgets'(O(N) vs O(N²)).

The problem is since Flutter was intended to be a UI framework at first, the default state management solutions are also UI-oriented.

Lastly, since you’ll need different state-management patterns for different projects, one package-for-all scenario is invaluable IMO.

75) Differentiate ChangeNotifierProvider vs ListenableProvider vs Provider?

Provider: The most basic form of provider. It takes a value and exposes it, whatever the value is.

ListenableProvider: A specific provider for Listenable object. ListenableProvider will listen to the object and ask widgets which depend on it to rebuild whenever the listener is called.

ChangeNotifierProvider: A specification of ListenableProvider for ChangeNotifier. It will automatically call ChangeNotifier.dispose when needed.

So, ChangeNotifierProvider is a specific type of Provider which will listen to the object and rebuild its dependent widgets when this object has been updated. Also, it will automatically call the dispose method when needed.

The Provideris the generic provider, without any more complex features, being very much like an optimized Inherited Widget.

76) Define some famous companies who using Flutter?

Some companies that use Flutter are

  • realtor.com,
  • Tencent,
  • the new york times,
  • square,
  • google,
  • eBay,
  • Sonos,
  • BMW,
  • Emaar

77) How would you execute code only in debug mode?

First to import this,

import 'package:flutter/foundation.dart' as Foundation;

then you can use kReleaseMode like

if(Foundation.kReleaseMode){ // is Release Mode ??
print('release mode');
} else {
print('debug mode');
}

So, by this condition you can execute code only in debug mode.

78) What is Iterable collections in Dart?
An Iterable is a collection of elements that can be accessed sequentially. In Dart, an Iterable is an abstract class, meaning that you can’t instantiate it directly. However, you can create a new Iterable by creating a new List or Set .

79) What is Concurrency in Dart?
Concurrency is the execution of several instruction sequences at the same time. It involves performing more than one task simultaneously. Dart uses Isolates as a tool for doing work in parallel.

80) 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);
}

81) What is Generics in Dart?
Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language. By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types.

void main() { 
List <String> logTypes = new List <String>();
logTypes.add("WARNING");
logTypes.add("ERROR");
logTypes.add("INFO");

// iterating across list
for (String type in logTypes) {
print(type);
}
}

82) What is Runes in Dart.
A rune can be defined as an integer used to represent any Unicode code point. As a Dart string is a simple sequence of UTF-16 code units, 32-bit Unicode values in a string are represented using a special syntax. The String class in the dart:core library gives ways to access runes.
Example:-

import 'dart:core';  
void main(){
f1();
}
f1() {
String x = 'Runes';
print(x.codeUnits); // [82, 117, 110, 101, 115]
}

83) What is HTML DOM in Dart?
Every webpage can be considered an object and it exists inside a browser window. We can access the webpage using the web browser and it needed to be connected to the internet. The DOM is the acronym for the Document object model. A Document object denotes the HTML document that is displayed in that window.

84) How many Data Types Support in Dart?
These are the type of values that can be represented and manipulated in a programming language.

The Dart language supports the following types−

  • Numbers
  • Strings
  • Booleans
  • Lists
  • Maps

85) What is Symbol in Dart?
Symbols in Dart are opaque, dynamic string names used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human-readable string and a string that is optimized to be used by computers.

Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime.

In Dart reflection, specific classes are available in the dart: mirrors package. This library works in both web applications and command-line applications.

import 'dart:mirrors'; 
void main(){
Symbol lib = new Symbol("foo_lib");
String name_of_lib = MirrorSystem.getName(lib);

print(lib); //Symbol("foo_lib")
print(name_of_lib); //foo_lib
}

86) What are Dart Constants?

Dart Constant is defined as an immutable object, which means it can’t be changed or modified during the execution of the program. Once we initialize the value to the constant variable, it cannot be reassigned later.

Defining/Initializing Constant in Dart

The Dart constant can be defined in the following two ways.

  • Using the final keyword
  • Using the const keyword

87) What are Dart Callable Classes?
Dart provides the facility to call class instances like a function. To make callable class, we need to implement a call() method in it. Let’s understand the following example -

class Addition {
int call(int a, int b) => a + b;
}
void main() {
Addition addition = Addition();
var result = addition(1, 5);
print(result); // 6
}

88) What is Super Constructor in Dart?
In dart, the subclass can inherit all the variables and methods of the parent class, with the use of extends keyword but it can’t inherit the constructor of the parent class. To do so we make use of the super constructor in the dart. There are two ways to call a super constructor:

  1. Implicitly
  2. Explicitly

Implicit super: In this case, the parent class is called implicitly, when there is object creation of child class. Here we don’t make use of the super constructor but when the child class constructor is invoked then it calls the default parent class constructor.

Explicit super: If the parent constructor is default then we call it as followed in implicit super, but if it takes parameters then the superclass is invoked as shown in the syntax mentioned above.

89) What is Anonymous Function in Dart?
An anonymous function in Dart is like a named function but they do not have names associated with it. An anonymous function can have zero or more parameters with optional type annotations. An anonymous function consists of self-contained blocks of code that can be passed around in our code as a function parameter.

  • In Dart, most of the functions are named functions we can also create a nameless function known as an anonymous function, lambda, or closure.
  • In Dart we can assign an anonymous function to constants or variables, later we can access or retrieve the value of closure based on our requirements:

90) What is Recursion in Dart?
Recursion is the process where a function calls itself its subroutine in order to solve a complex iterative task by dividing it into sub-tasks. Any function which calls itself recursively is called a recursive function, and the process of calling a function by itself is called recursion. Recursion leads to several iterative calls to the same function, however, it is important to have a base case to terminate the recursion.

91) Explain Threading in Dart?
Dart/Flutter is single-threaded and not possible to share global variables. As each isolate has its own memory, space, and everything.
To make it work like multi-threaded you have to use isolates and the communication will be used through ports by sending messages to one another. If you do not want to use Future you can use isolates. Flutter is written using Dart and Dart is a single-threaded language then Flutter apps are single-threaded. This means that a Flutter app can only do one thing at a time.

91) Difference between Equatable vs Freezed?
I mean the purpose of using it is the same Not at all. Equatable is “An abstract class that helps to implement equality without needing to explicitly override == and hashCode.”. Freezed is “Code generation for immutable classes that has a simple syntax/API without compromising on the features.”

Sure, they both override == and hashCode, but after that, they are very different. Equatable is a mixin to give a consistent, easy == and hashCode (although not necessarily the most efficient). Freezed is a build system that can use annotations to make immutable classes. Definitely different.

92) Explain FittedBox Widget?
FittedBox is a widget used to scale and position its child within the parent’s box according to specified fit type and alignment.

93) What is Lazy Loading?
Lazy loading
is a design pattern commonly used in computer programming and mostly in web design and development to defer the initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used.

94) How to check for types in Dart? Or What is sound typing in Dart?

Use .runtimeType to get the type:

void main() {var data_types = ["string", 123, 12.031, [], {} ];`

for(var i=0; i<data_types.length; i++){
print(data_types[i].runtimeType);if (data_types[i].runtimeType == String){
print("-it's a String");
}else if (data_types[i].runtimeType == int){
print("-it's a Int");

}else if (data_types[i].runtimeType == [].runtimeType){
print("-it's a List/Array");
}else if (data_types[i].runtimeType == {}.runtimeType){
print("-it's a Map/Object/Dict");
}else {
print("\n>> See this type is not their .\n");
}
}}

Soundness is about ensuring your program can’t get into certain invalid states. A sound type system means you can never get into a state where an expression evaluates to a value that doesn’t match the expression’s static type. For example, if an expression’s static type is String, at runtime, you are guaranteed to only get a string when you evaluate it.

95) What is BLOC Pattern?
It's a state management system for Flutter recommended by Google developers. It helps in managing state and make access to data from a central place in your project. MVP and MVVM are some good examples. Only the thing that will change is: that BLOC will be replaced with ViewModel in MVVM.

The best part about this pattern is that you won’t need to import any plugins or learn any custom syntax. Flutter already comes with everything you need.

“It's a state management system for Flutter recommended by Google developers. It helps in managing state and make access to data from a central place in your project. — BLOC will be replaced with ViewModel in MVVM 3. What is under the hood of BLOC ? or What is that core thing that manages the state in one place? STREAMS or REACTIVE approach. In general terms, data will be flowing from the BLOC to the UI or from UI to the BLOC in the form of streams. If you have never heard about streams. Read this Stack Overflow answer.”

96) Describe some Performance best practices in code.
- Avoid repetitive and costly work in build() methods since build() can be invoked frequently when ancestor Widgets rebuild. — Avoid overly large single Widgets with a large build() function.
Split them into different Widgets based on encapsulation but also on how they change: — When setState() is called on a State, all descendent widgets rebuild. Therefore, localize the setState() call to the part of the subtree whose UI actually needs to change.
Avoid calling setState() high up in the tree if the change is contained to a small part of the tree.
Avoid using the Opacity widget, and particularly avoid it in an animation. Use AnimatedOpacity or FadeInImage instead. For more information, see Performance considerations for opacity animation. When using an AnimatedBuilder, avoid putting a subtree in the builder function that builds widgets that don’t depend on the animation. This subtree is rebuilt for every tick of the animation. Instead, build that part of the subtree once and pass it as a child to the AnimatedBuilder. For more information, see Performance optimizations.
Avoid clipping in an animation. If possible, pre-clip the image before animating it.
Avoid using constructors with a concrete List of children (such as Column() or ListView()) if most of the children are not visible on screen to avoid the build cost.
Don’t split your widgets into methods Use const widgets where possible Avoid rebuilding all the widgets repetitively — (by change notifier) Use itemExtent in ListView for long Lists Avoid using the Opacity, particularly in an animation https://blog.codemagic.io/how-to-improve-the-performance-of-your-flutter-app./ https://flutter.dev/docs/perf/rendering/best-practices

97) How to hide Android StatusBar in Flutter?
You can use SystemChrome.setEnabledSystemUIOverlays([]) to hide and SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values) to bring it back again.

98) How do you detect the host platform from Dart code?

a simple way for web and app both, we can detect the host platform

import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
var platformName = '';
if (kIsWeb) {
platformName = "Web";
} else {
if (Platform.isAndroid) {
platformName = "Android";
} else if (Platform.isIOS) {
platformName = "IOS";
} else if (Platform.isFuchsia) {
platformName = "Fuchsia";
} else if (Platform.isLinux) {
platformName = "Linux";
} else if (Platform.isMacOS) {
platformName = "MacOS";
} else if (Platform.isWindows) {
platformName = "Windows";
}
}
print("platformName :- "+platformName.toString());

99) How to get .apk and .ipa files from flutter?
For apk (Android) you need to run the command :

flutter build apk --release

If you want to split the apks per abi (Split Apk) then run

flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi

For ipa (iOS) you need to run the command :

flutter build ios --release

From the console

P.S. --release is optional as it is by default if you need debug build, just replace --release with --debug

you can find the released APK or IPA files form

build/app/outputs/flutter-apk/app-release.apk

100) What does the ‘yield’ keyword do in flutter?
yield adds a value to the output stream of the surrounding async* function. It's like return, but doesn't terminate the function.

See https://dart.dev/guides/language/language-tour#generators

Stream asynchronousNaturalsTo(n) async* {
int k = 0;
while (k < n) yield k++;
}

When the yield statement executes, it adds the result of evaluating its expression to the stream. It doesn’t necessarily suspend (though in the current implementations it does).

So that’s all the questions that I think it’s enough for understanding flutter knowledge.because if you are able to get its core concept, you can answer similar types of questions as well.
I took it from many websites as some research if you find out any wrong info or miscorrected also if you think any major question that I missed to include in there, please write in the comment below.

if you got something wrong? Mention it in the comments. I would love to improve.
I am Shirsh Shukla. A creative Developer and a Technology lover. You can find me on LinkedIn or maybe follow me on Twitter or just walk over my portfolio for more details.

Have a nice day!🙂

--

--

Mobile Application Developer | GDG Speaker | Technical Blogger at medium | community member at StackOverflow | Organizer @FlutterIndore

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shirsh Shukla

Shirsh Shukla

703 Followers

Mobile Application Developer | GDG Speaker | Technical Blogger at medium | community member at StackOverflow | Organizer @FlutterIndore