Home Blog Page 76

Flutter Interview Questions and Answers

3
Flutter interview question and answer 2020
Flutter interview question and answer 2020

Hi Guys, Welcome to Proto Coders Point, This article will be on Flutter Technical Interview Questions asked for flutter job profile for fresher. Flutter Developer interview questions and answers for beginners.

So let’s begin with…

flutter job interview

Flutter interview questions for freshers

Job interview image

1. What is Flutter?

Answer: A Flutter is Cross platform development toolkit by Google, which help to deploy on multiple platform like ANDROID,IOS & WEB with single codebase & Flutter gives a greate UI design quality.


2. What are the advantage of flutter app?

Answer:

The most popular advantabe of flutter framework are:

  • Cross-platform development
  • Faster development
  • Good Community Support
  • Live and Hot Reloading feature
  • Minimal code
  • UI focused
  • easy to understand flutter Documentation.

3. What are the type of widget in flutter?

Answer:

In Flutter dart, everything view is an widget.

But Mainly, There are two types of widgets in flutter

  • StateFull Widget.
  • StateLess Widget.

When Flutter Interviewer ask you the above question, then there are many chances they he/she may also ask you the Question 4 i.e.


4. What is the difference between StateFull Widget and StateLess Widget?

Answer:

In StateFull Widget class, Holds state of the widgets & can we rebuilt with state change, by using setState() method;

Whereas, in Stateless Widget as built only once when it been created or when parent changes. (we can’t change stateless widget on data change).


5. How to access screen size in flutter?

This question may come in various kinds, the Interviewer may ask you how to access pixel density in flutter or he might ask you how to access aspect ration in flutter.

Answer:
We can access screen size and other properties like pixel density, aspect ratio etc with the help of MediaQuery.

Syntax:

MediaQuery.of(context).size.width;

MediaQuery.of(context).size.height;

6. What is Provider & How it works?

Answer:

Provider is a simplest way to handle state management.

The Flutter Provider works on a concept of PUB-SUB, Which means there is one provider & multiple Subscriber, Here Subscriber is Consumer.

Wherever any data change occurred, with notifyChangeListener it will get updated to all the consumer.


7. What are the best Editor for Flutter development?

Answer:

The best flutter editor tools make flutter development faster and smooth,

Flutter IDE need some plugin to develop mobile application.

The popular IDE tools for flutter development are :

  • Android Studio.
  • Visual Studio.
  • IntelliJ IDEA
  • IntelliJ IDEA
  • XCode

8. What is pubspec.yaml file?

Answer: The pubspec.yaml file is a crucial configuration file in a Flutter or Dart project. It is used to manage the project’s dependencies, metadata, and other settings.

9. How to access native feature of a platform?

Answer: We can access native feature of a particular platform by making use of Method Channel in flutter.

10. What is Scaffold in Flutter?

In flutter scaffold widgedis a basic material design layout structure. It has various properties like you can implement Appbar, BottomAppBar, FloatingActionButton, Drawer, BottomNavigationBar & much more.

By using Scaffold widget you can easily change the appearance of your flutter app.

11. What is SafeArea flutter?

In Flutter SafeArea Widget is very important widget, That automatically make user interface dynamic, basically SafeArea is simple a padding which simply add a padding depending on the device app is running.

12. What is Flex Flutter?

By using Flex widget in flutter user can alter/change the axis along with it child. Flexible widget are very important to make the flutter application responsive.

13. How do you handle errors in Flutter?

Answer: Error handling in Flutter can be done using try-catch blocks for synchronous code and .catchError or Future.catchError for asynchronous code. Additionally, the Flutter framework provides error widgets and logging mechanisms for uncaught errors.

14. Can you describe the Flutter rendering process?

Answer: Flutter’s rendering process involves three stages: layout, paint, and compositing. During the layout phase, the widget tree is built and sized. In the paint phase, the tree is drawn, and in the compositing phase, layers are combined and rendered on the screen.

15. How do you implement a custom widget in Flutter?

Answer: A custom widget can be created by extending StatelessWidget or StatefulWidget and implementing the build method to define the widget’s UI.

16. How do you optimize the performance of a Flutter app?

Answer: Performance optimization in Flutter includes minimizing widget rebuilds, using const constructors, leveraging lazy loading, optimizing images, and using effective state management techniques.

17. What is the difference between a Future and a Stream in Dart?

Answer: A Future represents a single asynchronous computation that returns a value or an error. A Stream is used for handling a sequence of asynchronous events, delivering multiple results over time.

18. Explain the Navigator and routing in Flutter.

Answer: The Navigator widget manages a stack of Route objects, allowing for navigation between different screens in a Flutter app. Routing can be handled using named routes or by directly pushing and popping routes.

19. How does Flutter handle state management?

Answer: Flutter offers several state management solutions, including setState(), InheritedWidget, Provider, Riverpod, Bloc, Redux, and more. The choice depends on the complexity and requirements of the app.

20. Explain the Flutter widget tree?

Answer: In Flutter, everything is a widget. Widgets are the basic building blocks of a Flutter app’s UI. The widget tree is a hierarchy of widgets that determines the UI’s layout.

21. What is an InheritedWidget?

Answer: An InheritedWidget is a base class for widgets that efficiently propagate information down the widget tree. It is used to share data between widgets in the widget tree.


5 Best coding books for beginners

Easiest way to create splash screen in flutter

0
Creating Splash Screen in Flutter
Creating Splash Screen in Flutter

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Easiest way to create splash screen in flutter

What is Splash Screen?

In any Mobile or Web Application a Splash Screen is the first screen that is visible to the user when it app is been launched… Usually Splash Screen are used to show company logo and then launch the main screen of the application after some time.

Easiest way to create splash screen in flutter

The Logic behind showing Splash Screen in app.

We are going to make use of Future.delayed method in flutter to load Main page after few seconds

Here is a snippet code

@override
 void initState() {
  
   Future.delayed(Duration(seconds:3),(){
     print("After 3 seconds");

     //This block of code will execute after 3 sec of app launch
     Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>MyHomePage()));
   });

   super.initState();
 }

In Flutter Class that extends StateFull widget, we are going to make use of an override function i.e initState().

Inside initState function we gonna call Future.delayed() that gets execute after few seconds.

Then, as you can see in above Snippet code Duration is set with 3 secs.

So, the Inner statement get loaded after 3 seconds.

Splash Screen in Flutter ( Source code )

Video Tutorial

Project Structure

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_splash/Splash_Screen.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashScreen(),  //calling Splash Screen page
    );
  }
}


SplashScreen.dart

import 'package:flutter/material.dart';
import 'package:flutter_splash/MyHomePage.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds:100),(){
      print("After 3 seconds");

      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>MyHomePage()));
    });

    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: FlutterLogo(
              size: 200,
              colors: Colors.pink,
            ),
          ),
        ],
      ),
    );
  }
}

MyHomePage.dart

import 'package:flutter/material.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("This is Home page After Splash Screen"),
      ),
    );
  }
}

 

Similar Articles

https://protocoderspoint.com/flutter-splash-screen-example-with-loading-animation-using-spinkit-library/

Flutter provider for beginners tutorial with app example

3
Flutter Provider tutorial example using changeNotifierProvider
Flutter Provider tutorial example using changeNotifierProvider

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna learn about Provider in Flutter.

Here is Official Library document https://pub.dev/packages/provider

What is Flutter Provider?

In Short, Provider is like a way to use an InheritedWidget.

For Example: If any data gets changed and need to updated into the App UI, then Instead of rebuilding full hierarchy of Widgets, we can simply Update value of Flutter Provider Consumer Widgets.

Video Tutorial

Below Example is by using setState() method

Using setState method is good when there is Small UI data change.

why setstate method in flutter is not good for huge UI update

Normally by making us of setState() method whole application UI gets rebuilt and continuously keeps rebuilding full application which is not a good sign to be a Flutter developer and this may give lots of load to the flutter engine (which may led to app performance issue).

As you can see in above screenshot:  i have made use of Count timer to decrement a variable value then simple display the updated variable value into the UI

Here Count down will be from 10 – 0, and every 1 second decrement the value by 1 and as value gets updated, whole app UI gets rebuilt for 10 time

You can view the logcat print statement above.

For a simple application which has very few data change/update then, it’s fine to make use of setState() method, but it is better to make use of other method like flutter provider when it comes for complex application build.

Flutter provider tutorial and Explaination

In provider we have 3 important part that are :

Flutter provider flowchart example
  • ChangeNotifierProvider
  • Update/ChangeNotifier
  • Consumer

ChangeNotifierProvider : which creates the instance of your data, as you can see in above diagram changeNotifierProvider will create instance of DataModel class

Update: from any where inside your page you want to update the value, you just get instance of that provider and manupulate that value as per and then as soon as the value is been change, data model will notify all the Flutter Consumer widgets.

And then once the consumer get Notified about the data change, you can update your widget as per.

Flutter provider tutorial with Example

Step 1: Creating a new Flutter Project

Step 2: Open pubspec.yaml file and add the dependencies

dependencies:
  provider: ^4.3.2+2  #latest version check official site

Step 3: Create a new Dart file in lib directory

After adding dependencies, then create a new dart file in lib directory on your flutter project

then name it as “Timer_Data.dart”

Timer_Data.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';

class Timer_Data extends ChangeNotifier
{
  int _time_remain_provider=11; // initial value of count down timer

  int gettime_remain_provider() => _time_remain_provider;   //method to get update value of variable

  updateRemainingTime(){
    _time_remain_provider --;  //method to update the variable value

    notifyListeners();
  }

}

In above source we have a variable that holds initial value,

then there is a method that gets updated value of variable

and then it has updateRemainingTime() method that will decrement the value by -1.

Step 4: Create one more dart file for UI Design (Homepage.dart)

Homepage.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_provider/Timer_Data.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  var remaining = 10;

  @override
  void initState() {
    // TODO: implement initState

    Timer.periodic(Duration(seconds: 1), (j){
      setState(() {
        remaining --;
      });

      if(remaining == 0)
        {
          j.cancel();
        }


    });

    Timer.periodic(Duration(seconds: 1), (t){

      var timeinfo = Provider.of<Timer_Data>(context,listen: false);

      timeinfo.updateRemainingTime();

      print(timeinfo.gettime_remain_provider());

      if(timeinfo.gettime_remain_provider() == 0)
        {

          t.cancel();
        }


    });
    super.initState();


  }
  @override
  Widget build(BuildContext context) {

    print("Rebuilt... complete UI... Not Good for Flutter Engine");
    return Scaffold(
      appBar: AppBar(title: Text("Flutter Provider Example"),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("With setState property",style: TextStyle(fontSize: 20),),
            Text("$remaining",style: TextStyle(fontSize: 30),),
            
            SizedBox(height: 25,),
            
            Text("By using providers",style: TextStyle(fontSize: 20),),
            Consumer<Timer_Data>(builder: (context, data,child) {
              return Text(data.gettime_remain_provider()?.toString()?? " ",style: TextStyle(fontSize: 30),);
            },)
          ],
        ),
      ),
    );
  }
}

Step 5: create instance using ChangeNotifierProvider in main.dart

This ChangeNotifier Provider will create a instance of Data_Model and then we can easily use the instance value any where inside it’s child widget.

import 'package:flutter/material.dart';
import 'package:flutter_provider/HomePage.dart';
import 'package:flutter_provider/Timer_Data.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ChangeNotifierProvider(create: (BuildContext context) =>Timer_Data(),
      child: HomePage()),
    );
  }
}


Result

Flutter Provider Example

Conclusion

In this Tutorial we learnt basic of flutter provider example – Flutter Application development

Related Articles

Firebase Login using Flutter Provider

Android Jetpack Compose tutorial with State management Example

2
Android Jetpack Compose basic tutorial with example
Android Jetpack Compose basic tutorial with example

Hi, Guys Welcome to Proto Coders Point, In this android tutorial, we will learn about android jetpack compose and will build a simple app using state management (MutableState) in jetpack that will update UI when State or Variable value changes on button click.

Android Jetpack Compose tutorial – A declarative UI Toolkit

What is Android Jetpack Compose?

A Jetpack compose is a modern toolkit using which we can build a Native android UI Application, It’s based on the declarative programming model, so all you need is to simply describe how your app UI should look like and the compose will take care of the rest of app state changes, and UI gets Automatically Changed.

What do we mean by declarative UI?

Declarative UI means the developer can design the UI by the means of Programming Code, This Android Jetpack compose is been inspired by React.js and Flutter development.

Why Compose Jetpack?

Easy way to Explain you :

Whenever we design a screen in android we are making use of XML to create UI design & then giving functionality to the UI using code in Java or kotlin.

  • Fewer Lines of Code
  • No XML Needed

When we use Android JetPack compose there is no need to write XML UI Files, we just need to write the whole UI Code in Kotlin language itself.

Building Block of jetpack

  1. Composable
  2. Model
  3. Preview

If you are designing a UI using jetpack compose, then you are basically writing function by making use of @Composable,

Then to check the preview display of your android application UI design in the android studio preview section you just need to add @Preview on top of @Composable.

A Composing is a function whatever we write in it get printed on the mobile screen as a widget view.

Note: As in Flutter all everything is a widget likewise in android jetpack every view is a widget

For Now, Android-Studio Stable version does not support Jetpack Compose so you need to make use of the Android Studio Canary version

Download Canary version from here https://developer.android.com/studio/preview?authuser=1

Project Creation

Start Android-Studio and create a new Android project and in the Template section select “Empty Compose Activity”  then finish building a project

Now, Let’s go into build.gradle file & check what new is been added for the Android Jetpack Compose project

As you can see in the below screenshot of build.gradle file everything is same as in normal android project except, you can see highlighted, there is a new thing that is integrated.

There are 2 new things you would see in this Gradle file

the first is to build features with compose as true

second, there are 3 new dependencies added. UI, material, tooling

jetpack compose build.gradle

Android jetpack android example – Increment number on Button Click

MainActivity.kt

package com.example.myapplication

import android.os.Bundle
import android.text.Layout
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.state
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.unit.TextUnit
import androidx.ui.tooling.preview.Preview
import com.example.myapplication.ui.MyApplicationTheme

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme() {
                MyApp()
            }

        }
    }
    @Preview
    @Composable
    private fun MyApp() {
       setupStateUsingState()

    }

    @Composable
    private fun setupStateUsingState() {

        Column {

            //Using MutableState in Compose
            var counterState: MutableState<Int> = state { 0 }

            TopAppBar(
                    title = { Text(text = "State Management") }
            )

            Text(
                    text = "Clicked:  ${counterState.value}",color = Color.White,fontSize = TextUnit.Sp(20)//set new value
            )
            Button(onClick = {
                //update value
                counterState.value +=1

            }) {
                Text(text = "Click to Add by +1")
            }
        }

    }
}

Output

jetpack compose state management tutorial output

As you can see in the above kotlin code,

I have created a @Composable function by the name “MyApp()” and this, in turn, calls another Composable function names “setupStateUsingState()”

It has a Column widget that has 3 children, i.e TopAppBar, Text, and a Button

Then, I have a variable of MutableState dataType Int initial value is set to 0.

And The value is printed into Text Widget.

whenever the user clicks on the button the variable counterState gets incremented by +1 and the changed value is printed on the screen.

Any Question/Query please do comment below

Thank You