Home Blog Page 67

Notes App – To do list app in Flutter – using Provider

0
flutter todo app tutorial using provider app

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will discuss on flutter provider,

By using provider in flutter we will develop an simple Notes app or to do list app in flutter.

DEMO

To do list Notes app flutter GIF IMAGE

What is Flutter provider?

A Provider in flutter is a wrapper around Inherited widget to make it easier to use & more reusable.

By using flutter provider instead of manual writting inheritedwidget, you get simplied alocation of resourse & greatly reduce boilerplate over making new class each time when data gets changed.

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.

Learn more about Flutter Provider

Beginner in provider? Have a look at basic of it : https://protocoderspoint.com/flutter-provider-for-beginners-tutorial-with-example/

So let’s begin…

Video Tutorial

Creating Notes/ To do List app using flutter – provider

Step 1: Create a new Flutter Project

Offcourse you need to create new flutter project, In my case i am making use of android studio as my IDE to develop flutter applications.

Step 2: Add required dependencies – Provider library and Slidable library

Then, as we are building Notes app/to do list app in flutter by using Provider class we need to add Provider dependencies in our flutter project.

And then, we also need Slidable  so that using can easily slide the listTile to delete or remove any notes to do.

Slidabe listTile to delete list

slidable listtile flutter to delete list

add this both dependencies in pubspec.yaml file as soon in below screenshot

adding dependencies provider and slidable

Learn more about this plugin library

Provider official Site

Slidable Official Site

Step 3: Create 2 folder in lib directory and create dart files

Then in lib directory of your flutter project, you need to create 2 directory by name

  • model : Will have 2 files : Notes.dart and NotesProvider.dart
  • Screen : Will have 1 file : Home_Screen.dart

Create respective dart files under those folder as shown below

creating directory and files in flutter

Step 4: Source code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:flutter_note_app_provider/screens/Home_Screen.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 ChangeNotifierProvider(
      create: (context)=>NotesProviders(),
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home_Screen()
      ),
    );
  }
}



Under Model folder

Notes.dart

In Notes Class we have 2 field to hold data i.e title,description and a Constructor.

This class will work and data model to handle them.

class Notes{
  String title;
  String description;

  Notes(this.title,this.description);
}

NotesProviders.dart

In NotesProviders class has a list of type<Notes> where we gonna store all the data the user create to store ToDo List notes.

It has 2 function

addNotes: that will help us to add data to the List of Array notes.

removeNotes: that will help us deleting/removing notes from the List

NoteProvider class is extended with ChangeNotifier because whenever any data is been changed or when user add notes, the data consumer will get notified, for that we make use of  notifyListeners(); to notify all the data consumer.

import 'package:flutter/cupertino.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
class NotesProviders extends ChangeNotifier {

  //Notes List
 List<Notes> _notes = new List<Notes>();

 List<Notes> get getNotes{
   return _notes;
 }

// function to add data to list of notes 
 void addNotes(String title,String descriptions)
 {
   Notes note = new Notes(title, descriptions);

   _notes.add(note);

    notifyListeners();
 }

 // function to remove or delete notes by using list index position
 void removeNotes(int index)
 {
   _notes.removeAt(index);
   notifyListeners();
 }


}


Screen Folder

Home_Screen.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:provider/provider.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

// ignore: camel_case_types
class Home_Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.purple[600],
     appBar: AppBar(
         titleSpacing: 0.0,
       toolbarHeight: 200,
       title: Image.network("https://9to5mac.com/wp-content/uploads/sites/6/2019/11/how-to-quickly-select-move-delete-notes-iphone-ipad-two-finger-tap.jpeg?quality=82&strip=all",fit: BoxFit.cover,)
     ),

      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Consumer<NotesProviders>(
          builder: (context,NotesProviders data,child){
            return data.getNotes.length !=0 ? ListView.builder(
              itemCount: data.getNotes.length,
              itemBuilder: (context,index){
                return CardList(data.getNotes[index],index);
              },
            ): GestureDetector(onTap: (){
              showAlertDialog(context);
            },child: Center(child: Text("ADD SOME NOTES NOW",style: TextStyle(color: Colors.white,),)));
          },
        ),
      ),

      floatingActionButton: FloatingActionButton(onPressed: () {
        showAlertDialog(context);
      },
          backgroundColor: Colors.white,
          child: Icon(Icons.add,color: Colors.black,),
      ),
    );

  }

}

// ignore: must_be_immutable
class CardList extends StatelessWidget {
  final Notes notes;
  int index;

  CardList(this.notes,this.index);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child:Slidable(
        actionPane: SlidableDrawerActionPane(),
        actionExtentRatio: 0.25,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              topLeft: Radius.circular(10),

            )
          ),
          child: ListTile(
           leading: Icon(Icons.note),
              title: Text(notes.title),
            subtitle: Text(notes.description),
            trailing: Icon(Icons.arrow_forward_ios,color: Colors.black26,),
          ),
        ),

        secondaryActions: <Widget>[
          IconSlideAction(
            caption: 'Delete',
            color: Colors.red,
            icon: Icons.delete,
            onTap: (){
              print("HELLO DELETED");
              Provider.of<NotesProviders>(context,listen: false).removeNotes(index);
            }
          ),
        ],
      ),
    );
  }
}

showAlertDialog(BuildContext context) {

  TextEditingController _Title = TextEditingController();
  TextEditingController _Description = TextEditingController();
  // Create button
  Widget okButton = FlatButton(
    child: Text("ADD NOTE"),
    onPressed: () {
      Provider.of<NotesProviders>(context,listen: false).addNotes(_Title.text, _Description.text);
      Navigator.of(context).pop();
    },
  );

  // Create AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("ADD A NEW NOTE "),
    content: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextField(
          controller: _Title,
          decoration: InputDecoration(hintText: "Enter Title"),
        ),
        TextField(
          controller: _Description,
          decoration: InputDecoration(hintText: "Enter Description"),
        ),
      ],
    ),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}


 

Download the Project from GITHUB 

Flutter Interview Questions and Answers for fresher – beginner

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 interview questions asked for flutter job profile for fresher. Flutter Developer job 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:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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.
[/bg_collapse]


2. What are the advantage of flutter app?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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.

[/bg_collapse]


3. What are the type of widget in flutter?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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.

[/bg_collapse]


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

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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).

[/bg_collapse]


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:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide Answer” ]
We can access screen size and other properties like pixel density, aspect ratio etc with the help of MediaQuery.
[/bg_collapse]

Syntax:

MediaQuery.of(context).size.width;

MediaQuery.of(context).size.height;

6. What is Provider & How it works?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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.

[/bg_collapse]


7. What are the best Editor for Flutter development?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide 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

[/bg_collapse]


8. What is pubspec.yaml file?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide Answer” ]

[/bg_collapse]

9. How to access native feature of a platform?

Answer:

[bg_collapse view=”button-orange” color=”#72777c” icon=”arrow” expand_text=”Show Answer” collapse_text=”Hide Answer” ]
We can access native feature of a particular platform by making use of Method Channel in flutter.
[/bg_collapse]

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.


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

Recommended Book