22 Dart Interview Questions (ANSWERED) Flutter Dev Must Know in 2020

Alex 👨🏼‍💻FullStack.Cafe - Feb 27 '20 - - Dev Community

Dart is an open source, purely object-oriented, optionally typed, and a class-based language which has excellent support for functional as well as reactive programming. Dart was the fastest-growing language between 2018 and 2019, with usage up a massive 532%. Follow along and check 22 common Dart Interview Questions Flutter and Mobile developers should be prepared for in 2020.

Originally published on FullStack.Cafe - Don't F*ck Up Your Next Tech Interview

Q1: 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

Q2: What is Fat Arrow Notation in Dart and when do you use it?

Topic: Flutter
Difficulty: ⭐⭐

The fat arrow syntax is simply a short hand for returning an expression and is similar to (){ return expression; }.

The fat arrow is for returning a single line, braces are for returning a code block.

Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression

// Normal function
void function1(int a) {
  if (a == 3) {
    print('arg was 3');
  } else {
    print('arg was not 3');
  }
}

// Arrow Function
void function2(int a) => print('arg was ${a == 3 ? '' : 'not '}3');

🔗 Source: stackoverflow.com

Q3: 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

Q4: Differentiate between named parameters and positional parameters in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐

Both named and positional parameters are part of optional parameter:

Optional Positional Parameters:

  • A parameter wrapped by [ ] is a positional optional parameter.

    getHttpUrl(String server, String path, [int port=80]) {
      // ...
    }
    
  • You can specify multiple positional parameters for a function:

    getHttpUrl(String server, String path, [int port=80, int numRetries=3]) {
      // ...
    }
    

    In the above code, port and numRetries are optional and have default values of 80 and 3 respectively. You can call getHttpUrl with or without the third parameter. The optional parameters are positional in that you can't omit port if you want to specify numRetries.

Optional Named Parameters:

  • A parameter wrapped by { } is a named optional parameter.

    getHttpUrl(String server, String path, {int port = 80}) {
      // ...
    }
    
  • You can specify multiple named parameters for a function:

    getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) {
      // ...
    }
    

    You can call getHttpUrl with or without the third parameter. You must use the parameter name when calling the function.

  • Because named parameters are referenced by name, they can be used in an order different from their declaration.

    getHttpUrl('example.com', '/index.html', numRetries: 5, port: 8080);
    getHttpUrl('example.com', '/index.html', numRetries: 5);
    

🔗 Source: stackoverflow.com

Q5: 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

Q6: 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

Q7: 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

Q8: How do you check if an async void method is completed in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐

Changing the return type to Future<void>.

Future<void> save(Folder folder) async {  
   .....
}

Then you can do await save(...); or save().then(...);

🔗 Source: stackoverflow.com

Q9: How to declare async function as a variable in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐

Async functions are normal functions with some sugar on top. The function variable type just needs to specify that it returns a Future:

class Example {
  Future<void> Function() asyncFuncVar;
  Future<void> asyncFunc() async => print('Do async stuff...');

  Example() {
    asyncFuncVar = asyncFunc;
    asyncFuncVar().then((_) => print('Hello'));
  }
}

void main() => Example();

🔗 Source: stackoverflow.com

Q10: How to duplicate repeating items inside a Dart list?

Topic: Flutter
Difficulty: ⭐⭐⭐

Consider the code:

final List<Ball> _ballList =[Ball(),Ball(),Ball(),Ball(),Ball(),]

What can to be done in order to not repeat Ball() multiple times.


Using collection-for if we need different instances of Ball()

final List<Ball> _ballList = [
  for (var i = 0; i < 5; i += 1) Ball(),
];

If we need the same instance of Ball(), List.filled should be used

final List<Ball> _ballList = List<Ball>.filled(5, Ball());

🔗 Source: stackoverflow.com

Q11: How is whenCompleted() different from then() in Future?

Topic: Flutter
Difficulty: ⭐⭐⭐

  • .whenComplete will fire a function either when the Future completes with an error or not, while .then returns a new Future which is completed with the result of the call to onValue (if this future completes with a value) or to onError (if this future completes with an error)
  • .whenCompleted is the asynchronous equivalent of a "finally" block.

🔗 Source: stackoverflow.com

Q12: How to get difference of lists in Flutter/Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐

Consider you have two lists [1,2,3,4,5,6,7] and [3,5,6,7,9,10]. How would you get the difference as output? eg. [1, 2, 4]


You can do something like this:

List<double> first = [1,2,3,4,5,6,7];
List<double> second = [3,5,6,7,9,10];
List<double> output = first.where((element) => !second.contains(element));

alternative answer:

List<double> first = [1,2,3,4,5,6,7];
List<double> second = [3,5,6,7,9,10];
List<double> output = [];

first.forEach((element) {
    if(!second.contains(element)){
    output.add(element);
}
});

//at this point, output list should have the answer

note that for both cases, you need to loop over the larger list.

🔗 Source: stackoverflow.com

Q13: 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

Q14: 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

Q15: 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

Q16: 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

Q17: 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

Q18: What's the difference between async and async* in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐⭐

  • async gives you a Future while async* gives you a Stream
  • You add the async keyword to a function that does some work that might take a long time. It returns the result wrapped in a Future.
  • You add the async* keyword to make a function that returns a bunch of future values one at a time. The results are wrapped in a Stream.
  • async* will always returns a Stream and offer some syntax sugar to emit a value through yield keyword.

🔗 Source: stackoverflow.com

Q19: How to compare two dates that are constructed differently in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐⭐

You can do that by converting the other date into utc and then comparing them with isAtSameMomentAs method.

void main(){
  String dateTime = '2020-02-03T08:30:00.000Z';
  int year = 2020;
  int month = 2;
  int day = 3;
  int hour = 8;
  int minute = 30;

  var dt = DateTime.utc(year,month,day,hour,minute);

  print(DateTime.parse(dateTime).isAtSameMomentAs(dt));
}

🔗 Source: stackoverflow.com

Q20: What does "non-nullable by default" mean in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐⭐

  • Non-nullable by default means that any variable that is declared normally cannot be null.
  • Any operation accessing the variable before it has been assigned is illegal.
  • Additionally, assigning null to a non-nullable variable is also not allowed.
void main() {
  String word;
  print(word); // illegal

  word = 'Hello, ';
  print(word); // legal
}
void main() {
  String word;

  word = null; // forbidden
  world = 'World!'; // allowed
}

🔗 Source: stackoverflow.com

Q21: What does a class with a method named ._() mean in Dart/Flutter?

Topic: Flutter
Difficulty: ⭐⭐⭐⭐

  • In Dart, if the leading character is an underscore, then the function/constructor is private to the library.
  • Class._(); is a named constructor (another example might be the copy constructor on some object in Flutter: AnotherClass.copy(...);).
  • The Class._(); isn't necessary unless you don't want Class to ever be accidentally instantiated using the implicit default constructor.

🔗 Source: stackoverflow.com

Q22: How do you convert a List into a Map in Dart?

Topic: Flutter
Difficulty: ⭐⭐⭐⭐

You can use Map.fromIterable:

var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);

or collection-for (starting from Dart 2.3):

var result = { for (var v in l) v[0]: v[1] };

🔗 Source: stackoverflow.com

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .