Wednesday, January 8, 2020

Flutter - Interview questions


Flutter interview questions
 

What is Dart?
  • Dart is a client-optimized, object-oriented, class-based, garbage-collected, programming language that can be used to build mobile, desktop, server, and web applications. Dart can compile to either native code or JavaScript. It supports interfaces, abstract classes, mixins, reified generics, and type inference.

What is Flutter?
  • Flutter is a open-source mobile UI framework that is created by Google. It allows us to develop a multi platforms application with one programming language(Dart) and one code-base. It uses own high-performance rendering engine to draw widgets and systems such as animation, gesture, and widgets.

What is the Difference between Stateless and Stateful widget?
  • The Stateless widget does not require a mutable state. Stateless widgets are not dynamically changed whenever you update any value. For example, if you want to make a button or text whose title doesn't need to change dynamically, then you can create a separate widget for a button as a Stateless widget. 
  • The Stateful widget has a mutable state. It means, when you want to make something that you want to change dynamically according to how a user interacts with it, then you can use the Stateful widget. For example, if you want to change the background color of the app on the click of a button, you can make use of a Stateful widget in this case.
Read more...


What is a Widget in Flutter SDK?
  • A widget is an element of a graphical user interface (GUI) that displays information or provides a specific way for a user to interact with the operating system or an application. 
  • The Widgets are high-level objects that are used to describe any part of an application. 
Read more...

What is the difference between main() and runApp() functions in Flutter?

  • main():  is the entry point of a Dart program. This method acts as a starting point for Flutter apps as well.
  • runApp(): In this method, you can pass the instance of MaterialApp and widgets(Stateless/Stateful). such as:
    // Passing instance of widget.
    void main()=>runApp(new DeveloperLibs());
    class DeveloperLibs extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return MaterialApp(
                ...
            );
        }
    }
                         OR
    // Passing instance of MaterialApp      
    void main()=>runApp(
        MaterialApp(
           ...
        );
    );      
The hot reload feature of Flutter does not work. If you pass an instance of MaterailApp.



What is the scaffold widget in Flutter SDK?
  • A Scaffold provides a framework that implements the basic material design visual layout structure of the flutter app. It provides APIs for showing drawers, snack bars, and bottom sheets, etc. The Scaffold contains almost everything you need to create a functional and responsive app. Its constructor has the following properties that help to create app design.
    //Constructor of Scaffold
    Scaffold({
      Key key,
      this.appBar,
      this.body,
      this.floatingActionButton,
      this.floatingActionButtonLocation,
      this.floatingActionButtonAnimator,
      this.persistentFooterButtons,
      this.drawer,
      this.endDrawer,
      this.bottomNavigationBar,
      this.bottomSheet,
      this.backgroundColor,
      this.resizeToAvoidBottomPadding = true,
      this.primary = true,
    }) 
Read more...

Explain Stateful Widget Lifecycle?  or What is didUpdateWidget in Flutter?
A stateful widget has the following lifecycle stages of a widget:
  • 1. createState(): To create a stateful widget, the Flutter framework instruct to createState() method. 
  • 2. mounted(true/false): Once we create a State object, the framework mounted the State object by associating it with a BuildContext before calling initState() method.  
  • 3. initState(): This is the first method called when a stateful widget is created after the class constructor. 
  • 4. didChangeDependencies(): This method is called immediately after initState() method on the first time the widget is built. 
  • 5. build(): it shows the part of the user interface represented by the widget. 
  • 6. didUpdateWidget(Widget oldWidget): If the parent widget change configuration and has to rebuild this widget.  
  • 7. setState(): This method is called from the framework and the developer. We can change the internal state of a State object and make the change in a function that you pass to setState(). 
  • 8. deactivate(): This is called when State is removed from the widgets tree, but it might be reinserted before the current frame change is finished. 
  • 9. dispose(): This is called when the State object is removed permanently.
Read more...

What is Pubspec.yaml file in the Flutter project?
  • The pubspec.yaml file is the place where you provide all the required meta data, public and private dependencies of the Flutter project. The Pubspec.yaml file written in YAML(Yaml Ain’t Markup Language). 
  • When we want to use Assets/Images from the local app directory then we have to put the Assets/Images folder path in Pubspec.yaml file to notify the project that we have included some new folders in it.
Example: Pubspec.yaml

What are Global Keys?
  • With the help of global keys, we can uniquely identify child widgets. The Global keys must be globally unique across the entire widget hierarchy. A global key can be used to retrieve the associated state of a widget.
  • Global keys are relatively expensive. If you don't need any of the features. Then we should consider Keys, ValueKey, ObjectKey, or UniqueKey instead of Global keys.

How can we debug the Flutter user interface?

The Flutter framework provides us lots of flags to debug UI of mobile all. Some flags are here:
void main() {
  debugPaintSizeEnabled = false;
  debugPaintBaselinesEnabled = false;
  debugPaintLayerBordersEnabled = false;
  debugPaintPointersEnabled = false;
  debugRepaintRainbowEnabled = false;
  debugRepaintTextRainbowEnabled = false;
  debugCheckElevationsEnabled = false;
  debugDisableClipLayers = false;
  debugDisablePhysicalShapeLayers = false;
  debugDisableOpacityLayers = false;
  runApp(PageApp());
}


When to use WidgetsBindingObserver?
This class send us notifications for many system and app changes. Here, we have some functions of this class:

  • didPopRoute(): This method is invoked in Android application when the user press the back button. 
  • didChangeLocales(…): This method is invoked when the sytem notify the app that the user change the system’s language settings. 
  • didChangeAppLifecycleState(…): This method is invoked when the system puts the app in the background or foreground.

Difference between HotRestart and Hot Reload?
Hot Reload:
  • The hot reload work with the combination of Small r key on command prompt or Terminal. 
  • Hot reload quickly compile the newly added code in our file and sent the code to Dart Virtual Machine after that the Code Dart Virtual Machine update the app UI with widgets. 
  • Hot Reload takes less time then Hot restart. 
  • There is also a drawback in Hot Reload, If you are using States in your application then Hot Reload preservers the States.
Hot Restart:
  • Hot restart destroys the preserves State value and set them to their default. So if you are using state value in your application then after every hot restart the developer gets 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.

What is the difference between Material and MaterialApp in Flutter?
  • MaterialApp is a widget that introduces many tools such as title, Navigator, home and Theme to help develop Flutter application. With the help of MaterialApp can access all the other components and widgets that is provided by Flutter SDK.
  • Material is also a widget that can be used to define a UI element to respect Material rules. It defines elevation, shape, and stuff to reused by many material widgets such as Appbar, Card and FloatingButton.
 


What is the home argument of MaterialApp?

  • The home argument is the route that is displayed first when the application is started normally, unless initialRoute is specified and can't be displayed. As you can see, we have defined the Scaffold widget inside the home argument of MaterialApp. Inside the Scaffold we can define various properties like body, appBar, floatingActionButton, backgroundColor, etc.
    Example: In the appBar property we have used the AppBar() widget in which as a title we have passed DeveloperLibs which will be displayed at the top of the application in appbar.

    import 'package:flutter/material.dart';
    void main() {
    runApp(MaterialApp(
    title: 'DeveloperLibs',
    theme: ThemeData(
    primarySwatch: Colors.green
    ),
    home: Scaffold(
    appBar: AppBar(
    title:Text(
    'DeveloperLibs'
    )
    ),
    ),
    ));
    }

What is a build method in widgets?
  • As we know, everything is a widget in the Flutter application. The framework replaces the subtree below current widget with the widget returned by build method. The build method can updating the subtree or removing the subtree and inflating a new subtree. In the build methed, the BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this widget in the tree. The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object.

Why is the build method on State, and not StatefulWidget?
  • Using a Widget build(BuildContext context) method on State rather than using a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when extending StatefulWidget.
    Example: AnimatedWidget is a child class of StatefulWidget that introduces an abstract Widget build(BuildContext context) method for its child classes to implement. If StatefulWidget already had a build method that took a State argument, AnimatedWidget would be forced to provide its State object to subclasses even though its State object is an internal implementation detail of AnimatedWidget.

What are Packages in Flutter?
  • A package is a namespace that contains a group of similar types of classes, interfaces, and sub-packages. In Flutter, Dart organizes and shares a set of functionality through a package. Flutter always supports shared packages, which is contributed by other developers community to the Flutter and Dart ecosystem. The packages allow us to build the app without having to develop everything from scratch. According to the functionality, we can categorize the package into two types:
Dart Package: It is a core package, which is written in the dart language, such as a path package. This package can be used in web and mobile platform. It also contains some Flutter specific functionality that depend on dependency on the Flutter framework, such as fluro package.

Plugin Package: It is a specialized Dart package that includes an core API written in Dart code and depends on the Flutter framework. It can be combined with a platform-specific implementation for an underlying platform such as Android (using Java or Kotlin), and iOS (using Objective C or Swift). The example of this package is the battery and image picker plugin package.





What are Future Operations?

Future operations are the operations which takes time to perform actions and return the result later. To handle this problem, we have to use Asynchronous functions. It can complete with success(.then) or with an error(.catchError).


What is Asynchronous Function?
The asynchronous operations let program run continue other operations while the current operation is being performed. The Dart language uses Future objects to display the results of asynchronous operations. To handle asynchronous operations, we have to use Async/await. But we can't integrate async and await on widgets. To solve this problem Flutter providing us a widget that called Future Builder. Here, we have some example of
asynchronous operations that we can perform in a Flutter application.
  • Fetching data over a network.
  • Writing to a database.
  • Reading data from a file.

What is Future Builder?
Future builder calls the future function to wait for the result, and as soon as it produces the result. It calls the builder function where we build the widget to display the content.


Explain await and async
  • The await allow us to run the function asynchronously and, when it is done, we can do other work of next line of code.
  • The async means that this function is asynchronous and you have to wait a bit to get its result.
void main() async {
await doSomeLongTask();
print('all done');
}

Here, you can see use of await and asunc in above method.
  • We used the async modifier on the main method because we are going to run the doSomeLongTask() function asynchronously.
  • We placed the await modifier front of our asynchronous function.

What is the difference between async and async* in Dart?
  • The async gives a Future object. When we 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 can get that result by awaiting the Future:
    main() async {
    int result = await doSomeLongTask();
    print(result); // prints '42' after waiting 1 second
    }
  • The async* gives a Stream object. When we 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.
    Stream<int> countForOneMinute() async* {
    for (int i = 1; i <= 60; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
    }
    }

What is fat arrow function declaration => in Flutter?
  • Fat Arrow Expression or Lambda Function Expression is a syntax to write a function on a single line using => syntax. This is a cleaner way to write functions with a single statement.
    void main() {


    void sayHello ( String name ) => print( "Hello $name." );

    // automatically returns result of expression `a * a`
    // Data Types are inferred at runtime
    var getSquare = ( a ) => a * a;

    // same as the above but with explicit Data Type declaration for the arguments
    var add = ( num a, num b ) => a + b;

    sayHello( "John" ); // this function does not return anything
    print( getSquare(3) ); // print returned value
    print( add(1, 2) ); // print returned value

    }

How to notify Flutter SDK to rebuild UI? 

  • Flutter Framework is notified that the internal state is changed when setState() is called from anywhere. This will schedule a widgets build method, rebuilding the UI and reflecting the new state.




Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...