Flutter interview questions with answers

Published November 25, 2020

1. What is the difference between a StatelessWidget and a StatefulWidget in Flutter?

Stateless Widget A stateless widget can not change its state during the runtime of an app which means it can not redraw its self while the app is running. Stateless widgets are immutable.

Stateful Widget A stateful widget can redraw itself multiple times, while the app is running which means its state is mutable. For example, when a button is pressed, the state of the widget is changed

 

2. Explain the Stateful Widget Lifecycle?

The lifecycle has the following simplified steps: createState() mounted == true initState() didChangeDependencies() build() didUpdateWidget() setState() deactivate() dispose() mounted == false

life cycle

 

3.What is Flutter tree shaking (flutter web)?

When compiling a Flutter web application, the JavaScript bundle is generated by the dart2js compiler. A release build has the highest level of optimization, which includes tree shaking your code. Tree shaking is the process of eliminating dead code, by only including code that is guaranteed to be executed. This means that you do not need to worry about the size of your app’s included libraries because unused classes or functions are excluded from the compiled JavaScript bundle

 

4.What is a Spacer widget?

Spacer manages the empty space between the widgets with a flex container. Evenly with the Rowand Column MainAxis alignment, we can manage the space as well

 

5.What is the difference between hot restart and hot reload?

What is Hot Reload in Flutter:

Flutter hot reload features works with a 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 than Hot restart. There is also a drawback in Hot Reload, If you are using States in your application then Hot Reload preservers the States so they will not update on Hot Reload our set to their default values

What is Hot Restart in Flutter:

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 a fully compiled application and all the states will set to their defaults. The app widget tree is completely rebuilt with a new typed code. Hot Restart takes much higher time than Hot reload

 

6. What is an InheritedWidget?

Flutter provides an InheritedWidget that can define provide context to every widget below it in the tree.

InheritedWidget is a special widget that can store and retrieve data, and subcomponents can obtain stored data. Commonly used MediaQuery and Theme are inherited from InheritedWidget

 

7. Why is the build() method on State and not StatefulWidget?

stateful_build

 

8. What is a pubspec file in Dart?

The pubspec file manages the assets and dependencies for a Flutter app.

 

9. How is Flutter native?

Flutter uses only the canvas of the native platform and draws the UI and all the components from scratch. All the UI elements look the same as native ones. This mainly reduces the burden of time for converting from some language to the native one and speeds up the UI rendering time. As a result, the UI performance is remarkably high

 

10. What is a Navigator and what are Routes in Flutter?

Navigation and routing are some of the core concepts of all mobile application, which allows the user to move between different pages. We know that every mobile application contains several screens for displaying different types of information. For example, an app can have a screen that contains various products. When the user taps on that product, immediately it will display detailed information about that product

 

11. What is a PageRoute?

Allow us to add animation transaction to the route https://github.com/divyanshub024/Flutter-route-transition

 

12. Explain asyncawait and Future?

Async means that this function is asynchronous and you might need to wait a bit to get its result. Await literally means - wait here until this function is finished and you will get its return value. Future is a type that ‘comes from the future’ and returns the value from your asynchronous function. It can complete with success(.then) or with an error(.catchError)

https://www.youtube.com/watch?v=SmTCmDMi4BY

 

13. how can you update a listview dynamically?

By using setState to update the listview item source and rebuild the UI

 

14. What is a Stream?

A stream is like a pipe, you put a value on the one end and if there’s a listener on the other end that listener will receive that value. A Stream can have multiple listeners and all of those listeners will receive the same value when it’s put in the pipeline. The way you put values on a stream is by using a StreamController

 

15. What are keys in Flutter and when should you use it?

You don't need to use Keys most of the time, the framework handles it for you and uses them internally to differentiate between widgets. There are a few cases where you may need to use them though.

A common case is if you need to differentiate between widgets by their keys, ObjectKey and ValueKey can be useful for defining how the widgets are differentiated

Another example is that if you have a child you want to access from a parent, you can make a GlobalKey in the parent and pass it to the child's constructor. Then you can do a global key.state to get the child's state (say for example in a button press callback). Note that this shouldn't be used excessively as there are often better ways to get around it

https://www.youtube.com/watch?v=kn0EOS-ZiIc&feature=emb_title

 

16. What are GlobalKeys?

GlobalKeys have two uses: they allow widgets to change parents anywhere in your app without losing state, or they can be used to access information about another widget in a completely different part of the widget tree. An example of the first scenario might if you wanted to show the same widget on two different screens, but holding all the same state, you’d want to use a global key

 

17. When can you use double.INFINITY?

When you want the widget to be big as the parent widget allow

 

18. What is TickerTween and AnimatedBuilder?

ticker

Animation Sequences To achieve sequence animation we’ll introduce a new Widget that also helps with reducing animation code called AnimatedBuilder which allows you to rebuild your widget through a builder function every time a new animation value is calculated

 

19. What is ephemeral state?

ephemeral

 

20. What is an AspectRatio widget used for?

AspectRatio Widget tries to find the best size to maintain aspect ratio while respecting it’s layout constraints. The AspectRatio Widget can be used to adjust the aspect ratio of widgets in your app

 

21. How would you access StatefulWidget properties from its State?

Using the widget property

 

22. Mention two or more operations that would require you to use or turn a Future

  • Calling api using http
  • Getting result from geolocator package
  • With FutureBuilder widget

 

23. What is the purpose of a SafeArea?

SafeArea is basically a glorified Padding widget. If you wrap another widget with SafeArea, it adds any necessary padding needed to keep your widget from being blocked by the system status bar, notches, holes, rounded corners and other "creative" features by manufactures

 

24. When to use a mainAxisSize?

When you use MainAxisSize on your Column or Row, they will determine the size of the Column or Row along the main axis, i.e, height for Column and width for Row

 

25. List the Visibility widgets in flutter and the differences?

  • Visibility
  • Opacity
  • Offstage

 

26. Can we use Color and Decoration property simultaneously in the Container?

No, The color property is a shorthand for creating a BoxDecoration with a color field. If you are adding a box decoration, simply place the color on the BoxDecoration.

 

27. Inorder for the CrossAxisAlignment.baseline to work what is another property that we need to set?

crossAxisAlignment: CrossAxisAlignment.baseline textBaseline: TextBaseline.ideographic

 

28. when should we use a resizeToAvoidBottomInset?

If true the body and the scaffold's floating widgets should size themselves to avoid the onscreen keyboard whose height is defined by the ambient MediaQuery's MediaQueryData.viewInsets bottom property.

For example, if there is an onscreen keyboard displayed above the scaffold, the body can be resized to avoid overlapping the keyboard, which prevents widgets inside the body from being obscured by the keyboard

 

29. What is the difference between as,show and hide in an import statement?

as

 

30. What is the importance of a TextEditingController?

Whenever the user modifies a text field with an associated TextEditingController, the text field updates value and the controller notifies its listeners. Listeners can then read the text and selection properties to learn what the user has typed or how the selection has been updated

 

31. How do we use a Reverse property in a Listview?

List animals = ['cat', 'dog', 'duck'];

List reversedAnimals = animals.reversed.toList();

 

32. How is an Inherited Widget different from a Provider?

Provider basically takes the logic of InheritedWidgets, but reduce the boilerplate to the strict minimum

 

33. Difference between these operators ?? and ?.

?? expr1 ?? expr2 If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.

?. Like. but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)

https://dart.dev/guides/language/language-tour

 

34. What is the purpose of ModalRoute.of()?

ModalRoute.of() method. This method returns the current route with the arguments

final args = ModalRoute.of(context).settings.arguments;

 

35. Difference between a Navigator.pushNamed and Navigator.pushReplacementNamed?

pushNamed

 

36. Difference between getDocuments() vs snapshots()?

getDocuments

 

37. What is a vsync?

Vsync basically keeps the track of screen, so that Flutter does not renders the animation when the screen is not being displayed

 

38.  When does the animation reach completion or dismissed status?

animations that progress from 0.0 to 1.0 will be dismissed when their value is 0.0. An animation might then run forward (from 0.0 to 1.0) or perhaps in reverse (from 1.0 to 0.0). Eventually, if the animation reaches the end of its range (1.0), the animation reaches the completed status.

 

39. Difference between AnimationController and Animation?

AnimationController is for how long the animation would be and how to control from time, upper and lower boundary, how to control data with time, length, sequence, etc. while AnimationTween is for the range of animation with time, color, range, sequence, etc as long the animation would be while

 

40. Define a TweenAnimation ?

 In a tween animation, the beginning and ending points are defined, as well as a timeline, and a curve that defines the timing and speed of the transition. The framework calculates how to transition from the beginning point to the endpoint

 

41. Why do we need a mixins ?

Mixins are very helpful when we want to share behavior across multiple classes that don’t share the same class hierarchy, or when it doesn’t make sense to implement such behavior in a superclass

 

42. When do you use the WidgetsBindingObserver?

To check when the system puts the app in the background or returns the app to the foreground

 

43. Define what is an App State?

The App State is also called an application state or shared state. The app state can be distributed across multiple areas of your app and the same is maintained with user sessions.

Following are the examples of App State:

Login info User preferences The shopping cart of an e-commerce application

 

44. What are the two types of Streams available in Flutter?

Single subscription streams:

It is a popular and common type of stream. It consists of a series of events that are parts of a large whole. Here all events have to be delivered in a defined order without even missing a single event. It is a type of stream that you get when you get a web request or receive a file. This stream can only be listed once. Listing it, again and again, means missing initial values and the overall stream makes no sense at all. When the listing starts in this stream the data gets fetched and provided in chunks.

Broadcast streams:

This stream is meant for the individual messages that can be handled one at a time. These types of streams are commonly used for mouse events in a browser. You can list this type of stream at any time. Multiple listeners can listen at a time and also you have a chance to listen after the cancellation of the previous subscription

 

45. What is a Flutter inspector?

Flutter inspector is a tool that helps in visualizing and exploring the widget trees. It helps in understanding the present layout and diagnoses various layout issues

 

46. Stream vs Future?

The difference is that Futures are about one-shot request/response (I ask, there is a delay, I get a notification that my Future is ready to collect, and I'm done!) whereas Streams are a continuous series of responses to a single request (I ask, there is a delay, then I keep getting responses until the stream dries up or I decide to close it and walk away)

 

47. What's the difference between async and async* in Dart?

async

 

48. How to convert a List into a Map in Dart?

list

 

49. What is the difference between main function and the runApp() function in Flutter?

In Dart, main() acts as the entry point for the program whereas runApp() attaches the given widget to the screen.

 

50. Where are the layout files? Why doesn’t Flutter have layout files?

In the Android framework, we separate an activity into layout and code. Because of this, we need to get references to views to work on them in Java. (Of course, Kotlin lets you avoid that.) The layout file itself would be written in XML and consist of Views and ViewGroups.

Flutter uses a completely new approach where instead of Views, you use widgets. A View in Android was mostly an element of the layout, but in Flutter, a Widget is pretty much everything. Everything from a button to a layout structure is a widget. The advantage here is in customizability. Imagine a button in Android. It has attributes like text which lets you add text to the button. But a button in Flutter does not take a title as a string, but another widget. Meaning inside a button you can have text, an image, an icon, and pretty much anything you can imagine without breaking layout constraints. This also lets you make customized widgets pretty easily whereas in Android making customized views is a rather difficult thing to do

 

 

This collection of Flutter Interview Questions and Answers collected by Omar Jakmira, Reach him at  https://power19942.github.io/

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2399 Views