Flutter-Dart
FLUTTER - INTERVIEW
QUESTIONS
1.
In the below code snippet, convert
makeMangoShake() to a getter called mangoshake using the shorthand
"arrow" syntax.
class
Recipe {
int mango;
int milk;
int sugar;
Recipe(this.mango, this.milk,
this.sugar);
int makeMangoShake() {
return mango+milk+sugar;
} }
Answer:
methodName(parameters) => statement;
int get mangoshake => mango + milk + sugar;
2. 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 the 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.
We
can process a stream by using the await for or listen() from the Stream API. It
has a way to respond to errors. We can create streams in many ways, but they
can be used in the same way. See the below example:
Future<int> sumStream(Stream<int> stream) async {
var sum = 0;
await for (var value in stream) {
sum = sum + value;
}
return sum;
}
Dart APIs: Stream and Future. Where a Future represents the result of a single
computation, a stream is a sequence of
results.
3.
Explain Hot Reload in
Flutter?
The hot reload feature allows you to
quickly and easily perform an experiment in the project. It helps to build UI,
add new features, fix bugs, and make app development fast. To perform hot
reloading of a Flutter app, do the following steps:
- Run the app
in a supported Flutter editor or terminal window.
- Modify any
of the Dart files in the project.
- If you use
an IDE that supports Flutter, then select Save All or click the Hot Reload
button on the toolbar. Immediately, you can see the result in your
emulator or real device.
4.
What is the difference
between Hot Restart and Hot Reload?
·
The
following are the essential differences between Hot Restart and Hot Reload:
Hot Reload |
Hot Restart |
·
It
works with a small r key on the terminal or commands prompt. |
·
It
mainly works with States value. |
·
The
hot reload feature allows us to quickly compile the newly added code in the file and sent them to Dart Virtual Machine (DVM). After DVM completes the updation, it immediately updates the UI of the app. |
·
It
allows developers to get a fully compiled application
becauseit destroys the preserves State values
and sets themto their defaults. On every Hot Restart,
our app widget tree is completely rebuilt with the new
typed code. |
·
It
helps to build UI, add new features, fix bugs, and
make app development
fast. |
·
It
takes more time than Hot Reload to compile and update the app. |
5.
What is the difference
between required and optional parameters in Dart?
Required parameters |
optional parameters |
·
Optional
parameters are parameters which don't have to be specified when calling given
function. |
·
In Dart,
there are two ways to specify optional parameters: they can be either
positional or named. ·
Optional
parameters are parameters which don't have to be specified when calling given
function. |
·
Optional
parameters must be declared after required
parameters. |
·
Optional
parameters must be declared after required
parameters. |
Required
parameter is a well know old style parameter which we all familiar with it example:
output:
|
optional
parameter will be disclosed with square bracket [ ] &
square bracketed parameter are optional. example:
output:
|
Required
Parameter Required
parameter is a well know old style parameter which we all familiar with it example:
output:
|
·
The
current syntax for optional positional parameters is: foo([bool
optional = false]) ·
The
current syntax for required named parameters is: foo({@required
bool optional = false}) Both
syntaxes are not used in any other mainstream language that I know of and are
unnecessary verbose compared to possible alternatives. |
6. complete this function:
convertToTitleString({String? name)
{
return name;
}
main() { |
|
var city = "new
york"; |
|
print(titleCase(city)); |
|
} |
|
/// Inefficient way of
capitalizing each word in a string. |
|
String titleCase(String text)
{ |
|
if (text.length <= 1) return text.toUpperCase(); |
|
var words = text.split(' '); |
|
var capitalized = words.map((word) { |
|
var first = word.substring(0, 1).toUpperCase(); |
|
var rest = word.substring(1); |
|
return '$first$rest'; |
|
}); |
|
return capitalized.join(' '); |
|
} |
main() {
String spanish = "esto es una prueba con varias palabras";
/// First option.
print(titleCase(spanish));
/// Second option.
String titleCaseVar = spanish
.split(' ')
.map((word) => word[0].toUpperCase() + word.substring(1))
.join(' ');
print(titleCaseVar);
}
/// My way of capitalizing each word in a string.
String titleCase(String text) {
if (text == null) throw ArgumentError("string: $text");
if (text.isEmpty) return text;
/// If you are careful you could use only this part of the code as shown in the second option.
return text
.split(' ')
.map((word) => word[0].toUpperCase() + word.substring(1))
.join(' ');
}
7. What is State and how can we manage it?
State: state is
information that can be read when the widget is built and might change or
modified over a lifetime of the app. If you want to change
your widget, you need to update the state object, which can be done by using
the setState() function available for Stateful widgets. The setState() function
allows us to set the properties of the state object that
triggers a redraw of the UI.
Managing
state in an application is one of the most important and necessary process in
the life cycle of an application.
Let us
consider a simple shopping cart application.
·
User will login using their credentials into the application.
·
Once user is logged in, the application should persist the logged
in user detail in all the screen.
·
Again, when the user selects a product and saved into a cart, the
cart information should persist between the pages until the user checked out
the cart.
·
User and their cart information at any instance is called the
state of the application at that instance.
A state
management can be divided into two categories based on the duration the
particular state lasts in an application.
·
Ephemeral −
Last for a few seconds like the current state of an animation or a single page
like current rating of a product. Flutter supports
its through StatefulWidget.
·
app state −
Last for entire application like logged in user details, cart information,
etc., Flutter supports
its through scoped_model.
Flutter State Management
In
this section, we are going to discuss state management and how we can handle it
in the Flutter. We know that in Flutter, everything is a widget. The widget can
be classified into two categories, one is a Stateless
widget, and another is a Stateful
widget. The Stateless widget does not have any internal
state. It means once it is built, we cannot change or modify it until they are
initialized again. On the other hand, a Stateful widget is dynamic and has a
state. It means we can modify it easily throughout its lifecycle without
reinitialized it again.
In Flutter, the state management categorizes into two
conceptual types, which are given below:
1. Ephemeral State
2. App State
Ephemeral State
This state is
also known as UI State or local state. It is a type of state which is related
to the specific widget, or you can say that it is a
state that contains in a single widget. In this kind of state, you do not need
to use state management techniques. The common example of this state is Text Field.
class MyHomepage extends StatefulWidget {
@override
MyHomepageState createState() => MyHomepageState();
}
class MyHomepageState extends State<MyHomepage> {
String _name = "Peter";
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text(_name),
onPressed: () {
setState(() {
_name = _name == "Peter" ? "John" : "Peter";
});
},
);
}
}
In the above example,
the _name is an ephemeral state. Here, only the
setState() function inside the StatefulWidget's class can access the _name. The
build method calls a setState() function, which does the modification in the
state variables. When this method is executed, the widget object is replaced
with the new one, which gives the modified variable value.
App State
It is different
from the ephemeral state. It is a type of state that we want to share across various parts of our app
and want to keep between user sessions. Thus, this type of state can be used
globally. Sometimes it is also known as application state or shared state. Some
of the examples of this state are User preferences, Login info, notifications
in a social networking app, the shopping cart in an e-commerce app, read/unread
state of articles in a news app, etc.
The following
diagram explains the difference between the ephemeral state and the app state
more appropriately.
The simplest
example of app state management can be learned by using the provider package. The state management with the
provider is easy to understand and requires less coding. A provider is a third-party library. Here, we need to
understand three main concepts to use this library.
1. ChangeNotifier
2. ChangeNotifierProvider
3. Consume
ChangeNotifier
ChangeNotifier is
a simple class, which provides change notification to its listeners. It is easy
to understand, implement, and optimized for a small number of listeners. It is
used for the listener to observe a model for changes. In this, we only use
the notifyListener() method to inform the listeners.
For example, let
us define a model based on ChangeNotifier. In this model, the Counter is extended with ChangeNotifier,
which is used to notify its listeners when we call notifyListeners(). It is the
only method that needs to implement in a ChangeNotifier model. In this example,
we declared two functions the increment and decrement, which are used to increase and
decrease the value. We can call notifyListeners() method any time the model
changes in a way that might change your app's UI.
8. What is Scaffold?
Scaffold is
a class in flutter which provides many widgets
or we can say APIs like Drawer, SnackBar,
BottomNavigationBar, FloatingActionButton, AppBar etc. Scaffold will expand or occupy the whole device
screen. It will occupy the available space. Scaffold will provide a framework to implement the basic
material design layout of the application.
Properties of Scaffold Class:
· AppBar: It displays a horizontal bar which mainly placed at
the top of the Scaffold. appBar uses the
widget AppBar which has its own
properties like elevation, title, brightness, etc.
· body: It will display the main or primary content in the
Scaffold. It is below the appBar and
under the floatingActionButton. The
widgets inside the body are at the left-corner by default.
· floatingActionButton: FloatingActionButton is a
button that is placed at the right bottom corner by default. FloatingActionButton is an
icon button that floats over the content of the screen at a fixed place. If we scroll
the page its position won’t change, it will be fixed.
·
drawer: drawer is
a slider menu or a panel which is displayed at the side of the Scaffold. The
user has to swipe left to right or right to left according to the action
defined to access the drawer menu. In the Appbar, an appropriate icon for the
drawer is set automatically at a particular position. The gesture to open the
drawer is also set automatically. It is handled by the Scaffold.
·
bottomNavigationBar: bottomNavigationBar is like
a menu at the bottom of the Scaffold. We have seen this navigationbar in most
of the applications. We can add multiple icons or texts or both in the bar as
items.
BottomNavigationBar widget to display the bar. For the
color of active icon we use the fixedColor property.
To add items in the bar we use BottomNavigationBarItems widget,
inside which we give text and icon. For the action performed on the tapping on
the items, we have onTap(int
indexOfItem) function which works according to the index position
of the item.
· backgroundColor: used to set the color of the whole Scaffold widget.
· floatingActionButtonAnimator: used to provide
animation to move floatingActionButton.
· primary: to tell whether the Scaffold will
be displayed or not.
· drawerScrimColor: used to define the color for the primary content
while a drawer is open.
· bottomSheet: This property takes in a widget (final) as the
object to display it at the bottom of the screen.
· drawerDragStartBehaviour: This property
holds DragStartBehavior enum as the object to determine
the drag behaviour of the drawer.
· drawerEdgeDragWidth: This determines the area under which a swipe or a drag
will result in the opening of the drawer. And it takes in a double as the object.
· drawerEnableOpenGesture: This property holds in
a boolean value as the object to determine the drag
gesture will open the drawer or not, by default it is set to true.
· endDrawer: The endDrawer property
takes in a widget as the parameter. It is similar to the Drawer, except the
fact it opens in the opposite direction.
· endDrawerEnableOpenGesture: Again this property
takes in a boolen value as the object to
determine whether the drag gesture will open the endDrawer or not.
· extendBody: The extendBody property takes in a boolean as the object. By default, this property
is always false but it must not be null. If it is set to true in the presence
of a bottomNavigationBar or persistentFooterButtons, then the height of these is
added to the body and they are shifted beneath the body.
· extendBodyBehindAppBar: This property
also takes in a boolean as the object. By
default, this property is always false but it must not be null. If it is set to
true the appBar instead of being on the body is extended above
it and its height is added to the body. This property is used when the color of
the appBar is not fully opaque.
· floatingActionButtonLocation: This property is
responsible for the location of the floatingActionBotton.
· persistentFooterButton: This property takes in
a list of widgets. Which are usually buttons that are displayed underneath
the scaffold.
· resizeToAvoidBottomInsets: This property takes in
a boolean value as the object. If set to true then
the floating widgets on the scaffold resize
themselves to avoid getting in the way of the on-screen keyboard.
9.
Differences Between Stateless and
Stateful Widget?
Stateless Widget:
|
Stateful Widget:
|
||
·
Stateless Widgets are static widgets. |
·
Stateful Widgets are dynamic widgets. |
||
·
They do not depend on any data change or any behavior
change. |
·
They can be updated during runtime based on user action
or data change.. |
||
·
Stateless Widgets do not have a state, they will be
rendered once and will not update themselves, but will only be updated when
external data changes. |
·
Stateful Widgets have an internal state and can
re-render if the input data changes or if Widget’s state changes. |
||
·
For
Example: Text, Icon, RaisedButton are Stateless Widgets. |
·
For Example: Checkbox, Radio Button, Slider are
Stateful Widgets |
||
·
Stateless
widgets are the widgets that don’t change i.e. they are immutable. ·
Its
appearance and properties remain
unchanged throughout the lifetime of the widget. |
·
Stateful
Widgets are the ones that change its properties during run-time. they are mutable and can be drawn multiple
times within its lifetime. |
||
·
Stateless
widgets cannot change their state during the runtime of the app, which means
the widgets cannot be redrawn while the app is in action. |
·
Stateful
widgets can change its appearance in response to events triggered by user
interactions or when it receives data. |
||
·
we
have to override the build() method as implemented in the
code below. |
·
we
have to override the createState() method, which returns the state of the
widget. |
||
10.
Explain the difference
between "??" and "?" Operators.
? operator |
? Operator |
The "??" operator is used
to evaluate and returns the value between two expressions. It can be used as
below: |
The "?" operator is used
to evaluate and returns the value between two expressions based on the given
condition. It can be used as below: |
11.
What is the difference
between WidgetsApp and MaterialApp?
WidgetsApp |
MaterialApp |
WidgetsApp is used for basic
navigation. It includes many foundational widgets together with the widgets
library that Flutter uses to create the UI of our app. |
MaterialApp, along with the material
library, is a layer that is built on the top of WidgetsApp and its library.
It implements Material Design that provides a unified look and feels to our
app on any platform. |
WidgetsApp class is the base class
for MaterialApp class. |
It offers many interesting tools
such as Navigator or Theme for developing the application. |
It wraps several widgets that are
required for building the application. |
It wraps several widgets that are
required for building material design applications. |
12.
What are Null-aware operators?
Dart provides
some useful information to handle the null values.
1.
The "??=" assignment operator that assigns a value to a variable only
when that variable is null.
int a; // Initial value of a is null.
a ??= 5;
print(a); // It will print 5.
2.
The "??" null-aware operator that is used to evaluate and returns the
value between two expression. It first checks the expression 1 and if it is
non-null, returns its value; otherwise, it will evaluate and returns the value
of expression 2:
print(3 ?? 5); // It will print 3.
print(null ?? 5); // It will print 5.
13.
What is Flutter?
Flutter is a UI toolkit for
creating fast, beautiful, natively compiled mobile applications with one
programming language and a single codebase. It is an open-source development
framework developed by Google. Generally, Flutter is not a language; it is an
SDK. Flutter apps use Dart programming language for creating an app. The first
alpha version of Flutter was released in May 2017.
Flutter is mainly optimized for 2D
mobile apps that can run on both Android and iOS platforms. We can also use it
to build full-featured apps, including camera, storage, geolocation, network,
third-party SDKs, and more.
14.
What is Dart?
Dart is a general-purpose,
object-oriented programming language with C-style syntax. It is open-source and
developed by Google in 2011. The purpose of Dart programming is to create a
frontend user interfaces for the web and mobile apps. It is an important
language for creating Flutter apps. The Dart language can be compiled both AOT
(Ahead-of-Time) and JIT (Just-in-Time).
15.
What are the Flutter
widgets?
A Flutter app is always considered
as a tree of widgets. Whenever you are going to code for building anything in
Flutter, it will be inside a widget. Widgets describe how your app view should
look like with their current configuration and state. When you made any
alteration in the code, the widget rebuilt its description by calculating the
difference of previous and current widget to determine the minimal changes for
rendering in the app's UI.
Widgets are nested with each other
to build the app. It means your app's root is itself a widget, and all the way
down is a widget also. For example, a widget can display something, can define
design, can handle interaction, etc.
16.
What are the best editors
for Flutter development?
The Flutter
development tools allow to make Flutter development faster and thus boosting
the developer's workflow. Flutter IDE and tools need some plugins to develop
mobile applications. The plugins help us to dart compiling, code analysis, and
Flutter development. The popular IDE for Flutter developments are as follows:
- Android
Studio
- Visual
Studio
- IntelliJ
IDEA
- Xcode
17.
What is pubspec.yaml file?
It is the
project's configuration file that will use a lot during working with the
Flutter project. It allows you how your application works. It also allows us to
set the constraints for the app. This file contains:
- Project
general settings such as name, description, and version of the project.
- Project
dependencies.
- Project
assets (e.g., images, audio, etc.).
18.
What are packages and
plugins in Flutter?
A package is a group of similar types of classes,
interfaces, and sub-packages. The packages and plugins help us to build the app
without having to develop everything from packages. In Flutter, it allows you
to import new widgets or functionality into the app. The packages and plugins
have a very small distinction. Generally, packages are the new components or
the code written in dart languages, whereas plugins allow more functionality on
the device by using the native code. In the DartPub, packages and plugins are
both referred to as packages.
19.
What are the advantages of
Flutter?
The popular
advantages of the Flutter framework are as follows:
·
Cross-platform Development: This feature allows Flutter to
write the code once, maintain, and can run on different platforms. It saves the
time, effort, and money of the developers.
·
Faster Development: The performance of the Flutter
application is fast. Flutter compiles the application by using the arm C/C++
library that makes it closer to machine code and gives the app a better native
performance.
·
Good Community: Flutter has good community
support where the developers can ask the issues and get the result quickly.
·
Live and Hot Reloading: It makes the app development
process extremely fast. This feature allows us to change or update the code are
reflected as soon as the alterations are made.
·
Minimal code: Flutter app is developed by Dart
programming language, which uses JIT and AOT compilation to improve the overall
start-up time, functioning and accelerates the performance. JIT enhances the
development system and refreshes the UI without putting extra effort into
building a new one.
·
UI Focused: It has an excellent user interface
because it uses a design-centric widget, high-development tools, advanced APIs,
and many more features.
·
Documentation: Flutter has very good
documentation support. It is organized and more informative. We can get
everything that we want to be written in one place.
20.
Which one is better between
Flutter and React Native?
·
Flutter and React Native are both used to develop the native
hybrid app from a single codebase. These apps can run on iOS and Android
platforms.
·
React Native develop by Facebook, whereas the Flutter framework
was first introduced by Google. So, both framework has a very good feature and
community.
·
Flutter uses Dart language to create applications, whereas React
Native uses JavaScript to build the applications.
·
From the developer's point of view, it is very difficult to choose amongst
them. Thus, it is very challenging to choose a winner between Flutter and React
Native.
21.
What is Tween Animation?
It is the short form of
in-betweening. In a tween animation, it is required to define the start and
endpoint of animation. It means the animation begins with the start value, then
goes through a series of intermediate values and finally reached the end value.
It also provides the timeline and curve, which defines the time and speed of the
transition. The widget framework provides a calculation of how to transition
from the start and endpoint.
22.
Name some popular apps that
use Flutter?
Today, many
organizations use Flutter for building the app. Some of the most popular app
built on Flutter are as follows:
- Google Ads
- Reflectly
- Alibaba
- Birch
Finance
- Coach
Yourself
- Tencent
- Watermaniac
23.
Name the popular database
package used in the Flutter?
The most used and
popular database packages used in the Flutter are as follows:
·
sqflite database: It allows to access and
manipulate SQLite database.
·
Firebase database: It will enable you to access and
manipulate the cloud database.
24.
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.
25.
When should you use
mainAxisAlignment and crossAxisAlignment?
We can use the crossAxisAlignment
and mainAxisAlignment to control how a row and column widgets align its
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. |
26.
What is the difference
between SizedBox VS Container?
Container |
SizedBox |
·
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. |
·
The SizedBox widget in Flutter is a box that comes with a specified size. Unlike
Container, it does not allows us to set color or decoration for the widget. |
·
If we have a widget
that needs some background styling may be a color, shape, or size
constraints, we may wrap it in a container 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. |
27.
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 the 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.
We can process a
stream by using the await for or listen() from the Stream API. It has a way to
respond to errors. We can create streams in many ways, but they can be used in
the same way. See the below example:
Future<int> sumStream(Stream<int> stream) async {
var sum = 0;
await for (var value in stream) {
sum = sum + value;
}
return sum;
}
27) Explain the different
types of Streams?
Streams can be of
two types, which are:
Single
subscription streams
It is the most
common type of stream that contains a sequence of events, which is the parts of
a larger whole. It will deliver the events in the correct order and without
missing any of them. If any of the events are missing, then the rest of the
stream makes no sense. This stream is mainly used to read a file or receive a
web request. It will listen once, and if it is listening again, it means
missing an initial event. When it starts listening, the data will be fetched
and provided in chunks.
Broadcast
streams
It is a type of
stream used for individual messages that can be handled one at a time without
the knowledge of the previous events. It can have multiple listeners to listen
simultaneously, and we can listen again after canceling the previous
subscription. This mouse events in a browser is a kind of this stream.
28.
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 course of 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.
29.
What are the different build
modes in Flutter?
The Flutter
tooling supports three modes while compiling the application. These compilation
modes can be chosen by depending on where we are in the development cycle. The
name of the modes are:
- Debug
- Profile
- Release
30.
What is the difference
between WidgetsApp and MaterialApp?
38) What is BuildContext?
BuildContext
in Flutter is the part of the widgets in the Element tree so that each widget
has its own BuildContext. We mainly use it to get a reference to another
widget or theme. For example, if we want to use a material design element, it
is required to reference it to the scaffold. We can get it using the
Scaffold.of(context) method. 39) What types of tests can
you perform in Flutter?
Testing
is an activity used to verify and validate the application, which is bug-free
and meets the user requirements. Generally, we can use these three types of
tests in Flutter: Unit
Tests: It tests a single function, method, or class. Its goal is
to ensure the correctness of code under a variety of conditions. This testing
is used for checking the validity of our business logic. Widget
Tests: It tests a single widget. Its goal is to ensure that the
widget's UI looks and interacts with other widgets as expected. Integration
Tests: It validates a complete app or a large part of the app.
Its goal is to ensure that all the widgets and services work together as
expected. Flutter
also provides one additional testing known as a golden test. Its goal is to
ensure that you have an image of a widget or screen and check to see whether
the actual widget matches it or not.
To read more information, click
here. |