29 Flutter Interview Questions Mobile Devs Need To Know

Alex 👨🏼‍💻FullStack.Cafe - Jan 13 '20 - - Dev Community

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

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

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

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

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

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

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

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

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:

🔗 Source: stackoverflow.com

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:

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:

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

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/

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.

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

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

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

    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

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

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

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

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:

    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:

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

🔗 Source: dart.dev

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

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

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

Topic: Flutter
Difficulty: ⭐⭐⭐

Solution is:

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

🔗 Source: stackoverflow.com

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:

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

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:

    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

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

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

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

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:

    myObject?.someProperty?.someMethod()
    

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

🔗 Source: flutter.dev

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

Q28: Explain Stateful Widget Lifecycle in details

Topic: Flutter
Difficulty: ⭐⭐⭐⭐⭐

A stateful widget has the following lifecycle stages:

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

    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.

      @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.

    @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

    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

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

Thanks 🙌 for reading and good luck on your interview!
Please share this article with your fellow devs if you like it!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player