# Interview Question With Answer

{% embed url="<https://dev.to/fullstackcafe/29-flutter-interview-questions-mobile-devs-need-to-know-1fon>" %}
Sumber
{% endembed %}

Flutter is booming in the mobile market as the next revolution. It has proven to hold the potential to win over every mobile technology and become the only choice for cross-platform app development in the future. Follow along and check the first most comprehensive list of Flutter Interview Questions and Answers that will trend on mobile developers interviews in 2020. Exclusive on FullStack.Cafe.

> Originally published on [FullStack.Cafe - Real Tech Interview Questions And Answers For Devs](https://www.fullstack.cafe/blog/flutter-interview-questions)

#### Q1: What is Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐

**Flutter** is an open-source UI toolkit from *Google* for crafting beautiful, natively compiled applications for desktop, web, and mobile from a single codebase. Flutter apps are built using the *Dart* programming language.

🔗 **Source:** [flutter.dev](https://flutter.dev/)

#### Q2: What is Dart and why does Flutter use it?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

**Dart** is an *object-oriented*, *garbage-collected* programming language that you use to develop Flutter apps.\
It was also created by Google, but is open-source, and has community inside and outside Google.\
Dart was chosen as the language of **Flutter** for the following reason:

* Dart is **AOT** (Ahead Of Time) compiled to fast, predictable, native code, which allows almost all of Flutter to be written in Dart. This not only makes Flutter fast, virtually everything (including all the widgets) can be customized.
* Dart can also be **JIT** (Just In Time) compiled for exceptionally fast development cycles and game-changing workflow (including Flutter’s popular sub-second stateful hot reload).
* Dart allows Flutter to avoid the need for a separate declarative layout language like *JSX* or *XML*, or separate visual interface builders, because Dart’s declarative, programmatic layout is easy to read and visualize. And with all the layout in one language and in one place, it is easy for Flutter to provide advanced tooling that makes layout a snap.

🔗 **Source:** [hackernoon.com](https://hackernoon.com/why-flutter-uses-dart-dd635a054ebf)

#### Q3: What is a "widget" and mention its importance in Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

* Widgets are basically the UI components in Flutter.
* It is a way to describe the configuration of an *Element*.
* They are inspired from components in **React**.

Widgets are important in Flutter because everything within a Flutter application is a **Widget** , from a simple “*Text”* to “*Buttons”* to “*Screen Layouts”*.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/50958238/what-is-a-widget-in-flutter)

#### Q4: How many types of widgets are there in Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

There are two types of widgets:

1. **StatelessWidget** : A widget that does not require mutable state.
2. **StatefulWidget**: A widget that has mutable state.

🔗 **Source:** [proandroiddev.com](https://proandroiddev.com/flutter-from-zero-to-comfortable-6b1d6b2d20e)

#### Q5: What is the difference between "main()" and "runApp()" functions in Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

* `main ()` function came from *Java*-like languages so it's where all program started, without it, you can't write any program on Flutter even without UI.
* `runApp()` function should return *Widget* that would be attached to the screen as a root of the *Widget Tree* that will be rendered.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/58883728/what-is-the-difference-between-main-function-and-the-runapp-function-in-flutte)

#### Q6: What is an App state?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

* State that is not *ephemeral*, that you want to share across many parts of your app, and that you want to keep between user sessions, is what we call **application state** (sometimes also called *shared state*).
* Examples of application state:
  * 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

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/development/data-and-backend/state-mgmt/ephemeral-vs-app)

#### Q7: What are the different build modes in Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐⭐

* The Flutter tooling supports three modes when compiling your app, and a headless mode for testing.
* You choose a compilation mode depending on where you are in the development cycle.
* The modes are:
  * Debug
  * Profile
  * Release

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/testing/build-modes)

#### Q8: Differentiate StatelessWidget and StatefulWidget?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

**Stateless** : Widget state creates ONLY ONCE, then **it can update values but not state** explicitly. That's why it has only one class which extends with `StatelessWidget`. They can never re-run `build()` method again.

**Stateful** : Widgets **can update their STATE (locally) & values multiple times upon event triggered**. That's the reason, the implementation is also different. In this, we have 2 classes, one is `StatefulWidget` & the other is it's State implementation handler i.e. `State<YourWidget>`. So if I say, they can re-run `build()` method again & again based on events triggered.

* A `StatelessWidget` will never *rebuild* by itself (but can from external events). A `StatefulWidget` can.
* A `StatelessWidget` is static wheres a `StatefulWidget` is dynamic.

See the diagram below:![](https://res.cloudinary.com/practicaldev/image/fetch/s--trCv4WkB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.stack.imgur.com/eQ688.png)

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/50958238/what-is-a-widget-in-flutter)

#### Q9: Why do we pass functions to widgets?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* Functions are first class objects in *Dart* and can be passed as parameters to other functions.
* We pass a function to a *widget* essentially saying, “invoke this function when something happens”.
* Callbacks using interfaces like *Android* (\<Java 8) have too much boilerplate code for a simple callback.

**Java Functions are first class objects in Dart and can be passed as parameters to other functions.callback:**<br>

```
button.setOnClickListener(new View.OnClickListener() {  
    @override  
    public void onClick(View view) {  
      // Do something here  
    }  
  }  
);
```

(Notice that this is only the code for setting up a listener. Defining a button requires separate *XML* code.)

**Dart equivalent:**<br>

```
FlatButton(  
  onPressed: () {  
    // Do something here  
  }  
)
```

(**Dart** does both declaration as well as setting up the callback.)\
This becomes much cleaner and organised and helps us avoid unnecessary complication.

🔗 **Source:** [medium.com](https://medium.com/@dev.n/answering-questions-on-flutter-app-development-6d50eb7223f3)

#### Q10: Differentiate between Hot Restart and Hot Reload?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

**Hot Reload**

* Flutter hot reload features works with combination of **Small r key** on command prompt or Terminal.
* 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 then Hot restart.
* There is also a draw back 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**

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

🔗 **Source:** [https://flutter-examples.com/difference-between-hot-reload-and-hot-restart-in-flutter-dart/](https://medium.com/@dev.n/answering-questions-on-flutter-app-development-6d50eb7223f3)

#### Q11: Differentiate between required and optional parameters in Dart?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

**Required Parameters**

Dart required parameters are the arguments that are passed to a function and the function or method required all those parameters to complete its code block.<br>

```
findVolume(int length, int breath, int height) {
 print('length = $length, breath = $breath, height = $height');
}

findVolume(10,20,30);
```

**Optional Parameters**

* Optional parameters are defined at the end of the parameter list, after any required parameters.
* In Flutter/Dart, there are 3 types of optional parameters:
  * Named
    * Parameters wrapped by `{ }`
    * eg. `getUrl(int color, [int favNum])`
  * Positional
    * Parameters wrapped by `[ ]`)
    * eg. `getUrl(int color, {int favNum})`
  * Default
    * Assigning a default value to a parameter.
    * eg. `getUrl(int color, [int favNum = 6])`

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/13264230/what-is-the-difference-between-named-and-positional-parameters-in-dart)

#### Q12: What is ScopedModel / BLoC Pattern?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

**ScopedModel** and **BLoC** (Business Logic Components) are common Flutter app architecture patterns to help separate business logic from UI code and using fewer *Stateful Widgets*.

* **Scoped Model** is a third-party package that is not included into Flutter framework. It's a set of utilities that allow you to easily pass a data Model from a parent Widget down to its descendants. In addition, it also rebuilds all of the children that use the model when the model is updated. This library was originally extracted from the Fuchsia codebase.
* **BLoC** stands for Business Logic Components. It helps in managing state and make access to data from a central place in your project. The gist of BLoC is that everything in the app should be represented as stream of events: widgets submit events; other widgets will respond. BLoC sits in the middle, managing the conversation.

🔗 **Source:** [technologymoon.com](https://technologymoon.com/community/mobile-comparison-f15/what-is-scopedmodel-bloc-pattern-t51952.html)

#### Q13: What is Streams in Flutter/Dart?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* Asynchronous programming in Dart is characterized by the `Future` and `Stream` classes.
* A **stream** is a sequence of *asynchronous* events. It is like an *asynchronous Iterable*—where, instead of getting the next event when you ask for it, the stream tells you that there is an event when it is ready.
* *Streams* can be created in many ways but they all are used in the same way; the *asynchronous for loop*( **await for**). E.g<br>

  ```
  Future<int> sumStream(Stream<int> stream) async {
    var sum = 0;
    await for (var value in stream) {
      sum += value;
    }
    return sum;
  }
  ```
* Streams provide an *asynchronous* sequence of data.
* Data sequences include user-generated events and data read from files.
* You can process a stream using either **await for** or `listen()` from the *Stream API*.
* Streams provide a way to respond to errors.
* There are two kinds of streams: **single subscription** or **broadcast**.

🔗 **Source:** [dart.dev](https://dart.dev/tutorials/language/streams)

#### Q14: Explain the different types of Streams?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

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.
   * **Broadcast streams**
   * It 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.

🔗 **Source:** [dart.dev](https://dart.dev/tutorials/language/streams)

#### Q15: What are packages and plugins in Flutter?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* Packages allow you to *import new widgets or functionality* into your app.
* There is a small distinction between packages and plugins.
* Packages are usually new components or code written purely in Dart whereas plugins work to allow more functionality on the device side using native code.
* Usually on **DartPub**, both packages and plugins are referred to as packages and only while creating a new package is the distinction clearly mentioned.

🔗 **Source:** [medium.com](https://medium.com/@dev.n/answering-questions-on-flutter-app-development-6d50eb7223f3)

#### Q16: What are keys in Flutter and when to use it?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* 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 of `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**.

🔗 **Source:** [api.flutter.dev](https://api.flutter.dev/flutter/foundation/Key-class.html)

#### Q17: What are Null-aware operators?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* Dart offers some handy operators for dealing with values that might be null.
* One is the **??=** assignment operator, which assigns a value to a variable only if that variable is currently null:<br>

  ```
  int a; // The initial value of a is null.
  a ??= 3;
  print(a); // <-- Prints 3.

  a ??= 5;
  print(a); // <-- Still prints 3.
  ```
* Another null-aware operator is ??, 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:<br>

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

🔗 **Source:** [dart.dev](https://dart.dev/codelabs/dart-cheatsheet)

#### Q18: What is profile mode and when do you use it?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* In **profile** mode, some *debugging* ability is maintained—enough to profile your app’s performance.
* Profile mode is used when you want to **analyze** performance.
* Profile mode is disabled on the *emulator* and *simulator*, because their behavior is not representative of real performance.
* On **mobile**, profile mode is similar to release mode, with the following differences:
  * Some service extensions, such as the one that enables the performance overlay, are enabled.
  * Tracing is enabled, and tools supporting source-level debugging (such as *DevTools*) can connect to the process.
* Profile mode for a **web** app means that:
  * The build is not minified but *tree shaking* has been performed.
  * The app is compiled with the *dart2js* compiler.
* The command `flutter run --profile` compiles to profile mode.

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/testing/build-modes)

#### Q19: What is release mode and when do you use it?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

* Use **release** mode for deploying the app, when you want **maximum** optimization and **minimal** footprint size.
* Use release mode when you are ready to release your app.
* For **mobile**, release mode (which is not supported on the simulator or emulator), means that:
  * Assertions are disabled.
  * Debugging information is stripped out.
  * Debugging is disabled.
  * Compilation is *optimized* for fast startup, fast execution, and small package sizes. Service extensions are disabled.
* Release mode for a **web app** means that:
  * The build is minified and *tree shaking* has been performed.
  * The app is compiled with the *dart2js* compiler for best performance.
* The command `flutter run --release` compiles to release mode.
* You can compile to release mode for a specific target with `flutter build <target>`.

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/testing/build-modes)

#### Q20: How would you execute code only in debug mode?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐

Solution is:<br>

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

then you can use `kReleaseMode` like<br>

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

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/49707028/check-if-running-app-is-in-debug-mode/55608318#55608318)

#### Q21: Explain async, await in Flutter/Dart?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

*Asynchronous* operations let your program complete work while waiting for another operation to finish. Here are some common asynchronous operations:

* Fetching data over a network.
* Writing to a database.
* Reading data from a file.

To perform asynchronous operations in Dart, you can use the `Future` class and the `async` and `await` keywords.

The `async` and `await` keywords provide a declarative way to define asynchronous functions and use their results. Remember these two basic guidelines when using `async` and `await`:

* To define an async function, add `async` before the function body
* The `await` keyword works only in `async` functions.

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.

Consider an example:<br>

```
import 'dart:async';

class Employee {
  int id;
  String firstName;
  String lastName;

  Employee(this.id, this.firstName, this.lastName);
}

void main() async {
  print("getting employee...");
  var x = await getEmployee(33);
  print("Got back ${x.firstName} ${x.lastName} with id# ${x.id}");
}

Future<Employee> getEmployee(int id) async {
  //Simluate what a real service call delay may look like by delaying 2 seconds   
  await Future<Employee>.delayed(const Duration(seconds: 2));
  //and then return an employee - lets pretend we grabbed this out of a database 
  var e = new Employee(id, "Joe", "Coder");
  return e;
}
```

🔗 **Source:** [dart.dev](https://dart.dev/codelabs/async-await)

#### Q22: What is Future in Flutter/Dart?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

* 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. For example:<br>

  ```
  Future<int> future = getFuture();
  future.then((value) => handleValue(value))
        .catchError((error) => handleError(error));
  ```
* If a future doesn’t produce a usable value, then the future’s type is `Future<void>`.
* A future represents the result of an *asynchronous* operation, and can have two states:
  1. **Uncompleted** When you call an *asynchronous* function, it returns an uncompleted future. That future is waiting for the function’s *asynchronous* operation to finish or to throw an error.
  2. **Completed** If the *asynchronous* operation succeeds, the future completes with a value. Otherwise it completes with an error.

🔗 **Source:** [api.dart.dev](https://api.dart.dev/stable/2.7.0/dart-async/Future-class.html)

#### Q23: What are the similarities and differences of Future and Stream?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

**Similarity:**

* `Future` and `Stream` both work *asynchronously.*
* Both have some potential value.

**Differences:**

* A `Stream` is a combination of **Futures**.
* `Future` has only one response but `Stream` could have any number of **Response**.

🔗 **Source:** [medium.com](https://medium.com/flutter-community/understanding-streams-in-flutter-dart-827340437da6)

#### Q24: What is the difference between double.INFINITY and MediaQuery?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

The difference can be summarised into:

* I want to be as big as my parent allows (`double.INFINITY`)
* I want to be as big as the screen (`MediaQuery`).

Usually, you'll want to use `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

🔗 **Source:** [api.flutter.dev](https://api.flutter.dev/flutter/widgets/MediaQuery-class.html)

#### Q25: How does Dart AOT work?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

* Dart source code will be translated into assembly files, then assembly files will be compiled into binary code for different architectures by the assembler.
* For mobile applications the source code is compiled for multiple processors ARM, ARM64, x64 and for both platforms - Android and iOS. This means there are multiple resulting binary files for each supported processor and platform combination.

🔗 **Source:** [flutterbyexample.com](https://flutterbyexample.com/stateful-widget-lifecycle/)

#### Q26: What is a difference between these operators "?? and ?."

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐

**??**

* It is 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.
```

**?.**

* It is a **conditional property access** which is used to guard access to a property or method of an object that might be null, put a question mark (?) before the dot (.):
* You can chain multiple uses of `?.` together in a single expression:<br>

  ```
  myObject?.someProperty?.someMethod()
  ```

  The preceding code returns null (and never calls `someMethod()`) if either `myObject` or `myObject.someProperty` is null.

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/testing/build-modes)

#### Q27: List some approaches for State management in Flutter

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐⭐

The state of an app is everything that exists in memory when the app is running. This includes the app’s assets, all the variables that the Flutter framework keeps about the UI, animation state, textures, fonts, and so on.

* There are some states ,e.g *textures*, that the flutter framework handles by itself.
* The states that we manage can be separated into two conceptual types:
  * Ephemeral state
  * App state

Some approaches to state management in Flutter are:

* `setState`
* `InheritedWidget` & `InheritedModel`
* Provider & Scoped Model
* Redux
* BLoC / Rx
* MobX

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/development/data-and-backend/state-mgmt/options)

#### Q28: Explain Stateful Widget Lifecycle in details

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐⭐

A stateful widget has the following lifecycle stages:<br>

```
- createState()
- mounted == true
- initState()
- didChangeDependencies()
- build()
- didUpdateWidget()
- setState()
- deactivate()
- dispose()
- mounted == false
```

**createState()**

* When Flutter is instructed to build a `StatefulWidget`, it immediately calls `createState()`. This method must exist. A `StatefulWidget` rarely needs to be more complicated than this.<br>

  ```
  class MyHomePage extends StatefulWidget {
    @override
    _MyHomePageState createState() => new _MyHomePageState();
  }
  ```

**mounted is true**

* When `createState` creates the state class, a `buildContext` is assigned to that state.
* A `BuildContext` is, overly simplified, the place in the widget tree in which this widget is placed.
* All widgets have a *bool* `this.mounted` property. It is turns true when the `buildContext` is assigned. It is an error to call `setState` when a widget is unmounted.

**initState()**

* This is the first method called when the widget is created (after the class constructor, of course.)
* `initState` is called once and only once. It must also call `super.initState()`.
* This @override method is the best time to:
  * Initialize data that relies on the specific `BuildContext` for the created instance of the widget.
  * Initialize properties that rely on this widgets 'parent' in the tree.
  * Subscribe to `Streams`, `ChangeNotifiers`, or any other object that could change the data on this widget.<br>

    ```
    @override
    initState() {
      super.initState();
      // Add listeners to this class
      cartItemStream.listen((data) {
        _updateWidget(data);
      });
    }
    ```

**didChangeDependencies()**

* The `didChangeDependencies` method is called immediately after `initState` on the first time the widget is built.
* It will also be called whenever an object that this widget depends on data from is called. For example, if it relies on an `InheritedWidget`, which updates.
* `build` is always called after `didChangeDependencies` is called, so this is rarely needed. However, this method is the first change you have to call `BuildContext.inheritFromWidgetOfExactType`. This essentially would make this State 'listen' to changes on a Widget it's inheriting data from.
* The docs also suggest that it could be useful if you need to do network calls (or any other expensive action) when an `InheritedWidget` updates.

**build()**

* This method is called often (think fps + render). It is a required, `@override` and must return a `Widget`.
* Remember that in Flutter all gui is a widget with a child or children, even '`Padding`', '`Center`'.

**didUpdateWidget(Widget oldWidget)**

* `didUpdateWidget()` is called if the parent widget changes and has to rebuild this widget (because it needs to give it different data), but it's being rebuilt with the same `runtimeType`, then this method is called.
* This is because Flutter is re-using the state, which is long lived. In this case, required is to initialize some data again, as one would in `initState()`.
* If the state's `build()` method relies on a `Stream` or other object that can change, unsubscribe from the old object and re-subscribe to the new instance in `didUpdateWidget()`.

> tip: This method is basically the replacement for '`initState()`' if it is expected the `Widget` associated with the widgets's state needs to to be rebuilt!

* Flutter always calls `build()` after this, so any subsequent further calls to `setState` is redundant.<br>

  ```
  @override
  void didUpdateWidget(Widget oldWidget) {
    if (oldWidget.importantProperty != widget.importantProperty) {
      _init();
    }
  }
  ```

**setState()**

* The '`setState()`' method is called often from the Flutter framework itself and from the developer.
* It is used to notify the framework that "data has changed", and the widget at this build context should be rebuilt.
* `setState()` takes a callback which cannot be *async*. It is for this reason it can be called often as required, because repainting is cheap<br>

  ```
  void updateProfile(String name) {
   setState(() => this.name = name);
  }
  ```

**deactivate()**

* This is rarely used.
* '`deactivate()`' is called when `State` is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because `State` objects can be moved from one point in a tree to another.

**dispose()**

* '`dispose()`' is called when the `State` object is removed, which is permanent.
* This method is where to unsubscribe and cancel all *animations*, *streams*, etc.
* **mounted is false**
* The state object can never remount, and an error is thrown is `setState()` is called.

🔗 **Source:** [flutterbyexample.com](https://flutterbyexample.com/stateful-widget-lifecycle/)

#### Q29: What is the difference between debug mode and profile mode?

> Topic: **Flutter**\
> Difficulty: ⭐⭐⭐⭐⭐

**Debug Mode:**

* It is used during **development** stage and when you want to use **hot reload**.
* By default, `flutter run` compiles to debug mode.
* Debug mode for **mobile apps** mean that:
  * Assertions are enabled.
  * Service extensions are enabled.
  * Compilation is *optimized* for fast development and run cycles (but not for execution speed, binary size, or deployment).
  * Debugging is enabled, and tools supporting source level debugging (such as *DevTools*) can connect to the process.
* Debug mode for a **web app** means that:
  * The build is not minified and *tree shaking* has not been performed.
  * The app is compiled with the *dartdevc* compiler for easier debugging.

**Profile Mode:**

* Profile mode is used when you want to **analyze** performance.
* The command `flutter run --profile` compiles to profile mode.
* Profile mode is disabled on the *emulator* and *simulator*, because their behavior is not representative of real performance.
* On **mobile**, profile mode is similar to release mode, with the following differences:
  * Some service extensions, such as the one that enables the performance overlay, are enabled.
  * Tracing is enabled, and tools supporting source-level debugging (such as *DevTools*) can connect to the process.
* Profile mode for a **web** app means that:
  * The build is not minified but *tree shaking* has been performed.
  * The app is compiled with the *dart2js* compiler.

🔗 **Source:** [flutter.dev](https://flutter.dev/docs/testing/build-modes)

> *Thanks 🙌 for reading and good luck on your interview!*\
> \&#xNAN;*Please share this article with your fellow devs if you like it!*\
> \&#xNAN;*Check more FullStack Interview Questions & Answers on 👉* [*www.fullstack.cafe*](https://www.fullstack.cafe/)

![heart](https://practicaldev-herokuapp-com.freetls.fastly.net/assets/emoji/emoji-one-heart-855b5a6263042e4c9448cf2cb0dd2e201598b77b1e3f1dc041492bc0128d9fb8.png)21![unicorn](https://practicaldev-herokuapp-com.freetls.fastly.net/assets/emoji/emoji-one-unicorn-695106da1194513bfa0092f1a75943f59089be7d6addbc7459bdfab80f5709e6.png)6![reading list](https://practicaldev-herokuapp-com.freetls.fastly.net/assets/emoji/emoji-one-bookmark-040f92162fa88c379d9d4e04bc5c192b1eb0b080d109dfaf3c9b1a60a1aeef0a.png)41[![twitter logo](https://practicaldev-herokuapp-com.freetls.fastly.net/assets/twitter-99c56e7c338b4d5c17d78f658882ddf18b0bbde5b3f42f84e7964689e7e8fb15.svg)](https://twitter.com/intent/tweet?text=%2229%20Flutter%20Interview%20Questions%20Mobile%20Devs%20Need%20To%20Know%22%20by%20Alex%20%F0%9F%91%A8%F0%9F%8F%BC%E2%80%8D%F0%9F%92%BBFullStack.Cafe%20%23DEVcommunity%20https://dev.to/fullstackcafe/29-flutter-interview-questions-mobile-devs-need-to-know-1fon)[DISCUSS (2)](https://dev.to/fullstackcafe/29-flutter-interview-questions-mobile-devs-need-to-know-1fon#comments)![dropdown menu icon](https://practicaldev-herokuapp-com.freetls.fastly.net/assets/three-dots-943ace87a6e3393984e260d09db4d12e3793f6658c33197e93c01ba552c165ba.svg)[![aershov24 profile](https://res.cloudinary.com/practicaldev/image/fetch/s--kybvKcq---/c_fill,f_auto,fl_progressive,h_180,q_auto,w_180/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/84431/873fcec3-9abd-4f12-9bec-cc0f04b35fe0.jpeg)](https://dev.to/aershov24)

**Alex 👨🏼‍💻FullStack.Cafe+ FOLLOW**

👋 Product enthusiast. FullStack Dev. 🇦🇺 Currently working on: ◀️ [www.FullStackResume.Com](http://www.FullStackResume.Com) ▶️ Job Winning Dev Resume Templates

[@aershov24](https://dev.to/aershov24) [![github](https://res.cloudinary.com/practicaldev/image/upload/v1456342401/github-logo_m841aq.png) aershov24](http://github.com/aershov24) [![link](https://res.cloudinary.com/practicaldev/image/upload/v1456342401/link-symbol_apfbll.png) www.fullstack.cafe](https://www.fullstack.cafe/)[FullStack.Cafe](https://dev.to/fullstackcafe)Helping Devs Never Fail Tech Interview Again

[www.fullstack.cafe](https://www.fullstack.cafe/)
