Home Blog Page 87

Shared Preferences in Flutter – shared preferences to keep user logged?

3
Shared Preferences in Flutter - shared preferences to keep user logged

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to use shared preferences in Flutter Application Development to keep users logged In.

In this example we gonna make use of flutter shared Preferences library, to keep logged in users data.

Brief about Shared Preferences?

In mobile app development their are many ways to shore data of an application. One of the way to shore data in mobile device itself is by making use of Shared Preferences.

It allows you to save and retrieve data in a form of key,value pair.

Video Tutorial

so Let’s begin adding and implementing Shared Preferences in Flutter with example of keeping users logged in.

In order to use this library, you need to first add the package in your flutter project to do so follow below 2 steps

Step 1 : Adding SharedPreferences Dependencies code

Visit the official website to get latest version of this library here

dependencies:
  shared_preferences: ^0.5.6+2 //add this line

Under you Flutter Project open pubspec.yaml file and add the dependences as show in below image.

adding shared preferences flutter dependences library

Step 2: Import the Flutter Shared Preferences package

Now, once you have added the dependencies in your flutter project now you can make use of the package through out your project just by importing the package.

How to import SharedPreferences ?

import 'package:shared_preferences/shared_preferences.dart';

Open dart file where you want to use shared Preferences to store and retrieve data, in my case it main.dart.

Note : This plugin must be used only to hold small data, in other words this plugin should not be used to store any kind of critical data.

In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

You need to call  a method SharedPreferences.getInstance and create a dart object names prefsdata.

SharedPreferences prefsdata = await SharedPreferences.getInstance();

Then, you can make use of this object ( prefsdata ) to store and retrieve data from sharedpreferences database.

How to store data in shared Preferences in flutter?

logindata.setString('username', username);

Here ‘username’ is a key and username is a value.

shared preferences key value example

How to retrieve data from shared Preferences?

String user = logindata.getString('username');

In the above snippet code ‘username’ is the key that holds the value.

Shared Preferences in Flutter – shared preferences to keep user logged?

In this Flutter tutorial for shared Preferences example i am going to create a simple login form note : without any backend database ( it’s just a dummy project )

for this project you need two dart pages. First to display login page (main.dart), Second to show successfully logged in user data ( mainpage.dart )

main.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'mainpage.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,
      ),
      home: MyLoginPage(),
    );
  }
}

class MyLoginPage extends StatefulWidget {
  @override
  _MyLoginPageState createState() => _MyLoginPageState();
}

class _MyLoginPageState extends State<MyLoginPage> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final username_controller = TextEditingController();
  final password_controller = TextEditingController();

  SharedPreferences logindata;
  bool newuser;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    check_if_already_login();
  }

  void check_if_already_login() async {
    logindata = await SharedPreferences.getInstance();
    newuser = (logindata.getBool('login') ?? true);

    print(newuser);
    if (newuser == false) {
      Navigator.pushReplacement(
          context, new MaterialPageRoute(builder: (context) => MyDashboard()));
    }
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    username_controller.dispose();
    password_controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(" Shared Preferences"),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              "Login Form",
              style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
            ),
            Text(
              "To show Example of Shared Preferences",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextField(
                controller: username_controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'username',
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextField(
                controller: password_controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Password',
                ),
              ),
            ),
            RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              onPressed: () {
                String username = username_controller.text;
                String password = password_controller.text;

                if (username != '' && password != '') {
                  print('Successfull');
                  logindata.setBool('login', false);

                  logindata.setString('username', username);

                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => MyDashboard()));
                }
              },
              child: Text("Log-In"),
            )
          ],
        ),
      ),
    );
  }
}

The above dart code will result UI something like below screenshot

Login screen for shared preferences example

mainPage.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttersharedpreferences/main.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyDashboard(),
    );
  }
}

class MyDashboard extends StatefulWidget {
  @override
  _MyDashboardState createState() => _MyDashboardState();
}

class _MyDashboardState extends State<MyDashboard> {
  SharedPreferences logindata;
  String username;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }

  void initial() async {
    logindata = await SharedPreferences.getInstance();
    setState(() {
      username = logindata.getString('username');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Shared Preference Example"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(26.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Center(
              child: Text(
                'WELCOME TO PROTO CODERS POINT  $username',
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
              ),
            ),
            RaisedButton(
              onPressed: () {
                logindata.setBool('login', true);
                Navigator.pushReplacement(context,
                    new MaterialPageRoute(builder: (context) => MyLoginPage()));
              },
              child: Text('LogOut'),
            )
          ],
        ),
      ),
    );
  }
}

Result

logged in user welcome screen with retrived data from shared preferences-min

 

Flutter Splash Screen Example with Loading Animation using Spinkit library

1
Flutter Splash Screen Example with Loading Animation using Spinkit library

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Flutter Splash Screen and showing a loading effect using Flutter Spinkit.

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.

There are many way to show a flutter splash screen. In this Flutter Tutorial we gonna learn the simplest way to show the Splash Screen using Timer class.

DEMO

Futter Splash Screen Example

Video Tutorial

So let’s begin implementing this in Flutter project without wasting any time.

Brief about Flutter Spinkit Library

The Flutter Spinkit package library is a collection of pre – animated loading indicator in flutter app development.

This Spinkit package library is been pre-animated with loading effect you just need to use those class wherever required.

How to add Flutter Spinkit package library?

Step 1: Add Spinkit dependencies in Pubspex.yaml file

To make use of spinkit library to show loading animation effect you need to add the library in your project.

dependencies:
  flutter_spinkit: ^4.1.2 // add this line

Step 2: Import the dart class where required

Then you need to import dart code in main.dart file to use the Spinkit library.

import 'package:flutter_spinkit/flutter_spinkit.dart';

Step 3 : Use the Spinkit widgets

SpinKitRotatingCircle(
  color: Colors.white,
  size: 50.0,
);

There are many type of spinkit widget.

Here are the list of all the spinkit loading widget that you can easily use to show loading effect. Experiment them one by one and select any one.

SpinKitRotatingCircle(color: Colors.white)

SpinKitRotatingPlain(color: Colors.white)

SpinKitChasingDots(color: Colors.white)

SpinKitPumpingHeart(color: Colors.white)

SpinKitPulse(color: Colors.white)

SpinKitDoubleBounce(color: Colors.white)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.start)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.center)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.end)

SpinKitThreeBounce(color: Colors.white)

SpinKitWanderingCubes(color: Colors.white)

SpinKitWanderingCubes(color: Colors.white, shape: BoxShape.circle)

SpinKitCircle(color: Colors.white)

SpinKitFadingFour(color: Colors.white)

SpinKitFadingFour(color: Colors.white, shape: BoxShape.rectangle)

SpinKitFadingCube(color: Colors.white)

SpinKitCubeGrid(size: 51.0, color: Colors.white)

SpinKitFoldingCube(color: Colors.white)

SpinKitRing(color: Colors.white)

SpinKitDualRing(color: Colors.white)

SpinKitRipple(color: Colors.white)

SpinKitFadingGrid(color: Colors.white)

SpinKitFadingGrid(color: Colors.white, shape: BoxShape.rectangle)

SpinKitHourGlass(color: Colors.white)

SpinKitSpinningCircle(color: Colors.white)

SpinKitSpinningCircle(color: Colors.white, shape: BoxShape.rectangle)

SpinKitFadingCircle(color: Colors.white)

SpinKitPouringHourglass(color: Colors.white)

Flutter Splash Screen Example with Loading Animation using Spinkit library

In this Flutter Tutorial we gonna make use of Timer() which loads page2 after 5 second.

To do so you need two Flutter dart pages, I have create 2 dart pages namely main.dart and HomePage.dart

Creating a dart page

To create a new dart file lib (right click) > New >  Dart File

creating new dart file in flutter
creating new dart file in flutter

Then i have named it HomePage.dart

My Project Structure

Flutter project structure

Snippet Code of Timer() in main.dart file

@override
  void initState() {
    // TODO: implement initState
    super.initState();

    Timer(
      Duration(seconds: 5),
      () => Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      ),
    );
  }

Here i will be waiting in main.dart file for 5 second to show Flutter loading Spinkit then after 5 second i will navigate from main.dart page —>  HomePage.dart this will work like a Flutter Splash Screen.

Complete Code Flutter Splash Screen with Spinkit library.

main.dart

Copy paste the below lines of Flutter dart code in main.dart file

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutterspinkit/Home_Page.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,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Timer(
      Duration(seconds: 5),
      () => Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      fit: StackFit.expand,
      children: <Widget>[
        Container(
          decoration: BoxDecoration(color: Colors.redAccent),
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "   Loading....",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 25,
            ),
            SpinKitWave(
              itemBuilder: (BuildContext context, int index) {
                return DecoratedBox(
                  decoration: BoxDecoration(
                    color: index.isEven ? Colors.white : Colors.green,
                  ),
                );
              },
            ),
          ],
        ),
      ],
    ));
  }
}

The above code will simply show a loading indicator for 5 seconds and then load the new page.

HomePage.dart

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Tutorial"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
                " This is an Example for Splash Screen and Loading Spin Kit Library")
          ],
        ),
      ),
    );
  }
}

This HomePage has simple text at the center of the screen.

Android bottom sheet dialog fragment popup with list selection

0
Bottom Sheet Layout Fragment Example with list selection
Bottom Sheet Layout Fragment Example with list selection

Hi Guys, Welcome to Proto Coders point, In this Android Tutorial we will implement Action bottom sheet dialog fragment Pop-Up box that let you select list of items.

Brief about Bottom Sheet Dialog Fragment

If you have gonna through Material design for BottomSheet, It says there are two types of Bottom Sheets:

  1. Modal bottom sheets: It Can be implemented using BottomSheetDialog or BottomSheetDialogFragment. Elevation is higher than the app. It is fundamentally acting as the dialog.
  2. Persistent bottom sheets: It can be implemented using BottomSheetBehavior in conjunction with a CoordinatorLayout.

So in this project we are making use of Model Bottom Sheet as we require to show a Fragment in our main activity class.

Refer official https://developer.android.com/reference/android/support/design/widget/BottomSheetDialogFragment

OK so lets start implementing  bottom sheet in our android project without wasting our time.

Demo

Bottom Sheet Layout Fragment Example

Step 1: Add Material dependencies

implementation 'com.google.android.material:material:1.0.0'

BottomSheet DialogFragment is integrated in material class dependencies so you need to add the material in Build.gradle file.

Step 2: Design XML layout for Bottom Sheet UI

You need to create a new XML layout file and name it as bottomsheetlayout or any thing.

Under res > layout (right click) create a new Layout Resource File.

bottomsheetlayout.xml

Then paste the below lines of xml code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="8dp">
    <TextView
        android:id="@+id/textView"
        android:layout_marginTop="8dp"
        android:text="Android"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        style="@style/ActionItem" />
    <TextView
        android:id="@+id/textView2"
        android:text="Flutter"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        style="@style/ActionItem"/>
    <TextView
        android:id="@+id/textView3"
        android:text="React Native"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        style="@style/ActionItem"
        />
    <TextView
        android:id="@+id/textView4"

        android:text="Web Development"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        style="@style/ActionItem" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Create a dimens.xml file

res > Values > Right Click ( New ) > Value Resource File.

Check if demens.xml file is exist in your project else create a new demins.xml file.

Then just paste the below dimension code in it.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>

    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="default_margin">16dp</dimen>

    <dimen name="drawable_padding">24dp</dimen>

    <dimen name="text_size">16sp</dimen>

    <dimen name="normal_padding">16dp</dimen>
</resources>

Step 4: add a new Styling in Style.xml

Now open style.xml  you will find it under values folder and add the below styling tag.

<style name="ActionItem">
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:drawablePadding">@dimen/drawable_padding</item>
    <item name="android:layout_width">0dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:padding">@dimen/normal_padding</item>
</style>

Step 5 : Create a new java file for ActionBottomSheetDialog and name it as  ActionBottomSheetDialog.java

App > java >your package name (right click) > New > java Class

Then just add the below lines of codes

package com.protocoderspoint.actionbottomsheet;


import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

public class ActionBottomSheetDialog extends BottomSheetDialogFragment
        implements View.OnClickListener {
    public static final String TAG = "ActionBottomDialog";
    private ItemClickListener mListener;
    public static ActionBottomSheetDialog newInstance() {
        return new ActionBottomSheetDialog();
    }
    @Nullable @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.botton_sheet_layout, container, false);
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.textView).setOnClickListener(this);
        view.findViewById(R.id.textView2).setOnClickListener(this);
        view.findViewById(R.id.textView3).setOnClickListener(this);
        view.findViewById(R.id.textView4).setOnClickListener(this);
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof ItemClickListener) {
            mListener = (ItemClickListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement ItemClickListener");
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override public void onClick(View view) {
        TextView tvSelected = (TextView) view;
        mListener.onItemClick(tvSelected.getText().toString());
        dismiss();
    }
    public interface ItemClickListener {
        void onItemClick(String item);
    }
}

In our java file ActionBottomSheetDialog we gonna extends BottomSheetDialogFragment.

Then it need to have 2 main implementation methods namely onCreateView,OnViewCreated.

Step 5: implements ActionBottomSheetDialog .ItemClickListener in MainActivity.java

package com.protocoderspoint.actionbottomsheet;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity  implements  ActionBottomSheetDialog.ItemClickListener{

    Button OpenBottomSheet;
    TextView selectedText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        OpenBottomSheet = (Button)findViewById(R.id.openButtomSheet);
        selectedText = (TextView)findViewById(R.id.selected_listItem);

        OpenBottomSheet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActionBottomSheetDialog openBottomSheet = ActionBottomSheetDialog.newInstance();

openBottomSheet.show(getSupportFragmentManager(),ActionBottomSheetDialog.TAG);

            }
        });
    }

    @Override
    public void onItemClick(String item) {
    selectedText.setText(item.toString());
    }
}

In the MainActivity.java I have just  initialized two widget that are button and a textview,

On Button click event we gonna invoke the android bottonsheet by creating newInstance of the View and then show the Bottom sheet Pop-Up.

then when used select any option from the bottomSheet in the android app  we gonna get the text from the selected option and show the text in textView.

Referred from androidwave.com.

Flutter Pull to refresh using SmartRefresher widget package library

0
Flutter Pull to refresh

Hi Guys, Welcome to proto coders point, In this Flutter Tutorial, we gonna Implement the pull to refresh the flutter package library.

Demo on how the final code will work for pull to refresh

flutter pull down to refresh package library

Brief about the pull to refresh

This widget is very useful when the user wants to scroll down to refresh the contents and even this widget can be pull up to load new content to the user. This widget Support both Android and iOS devices.

let’s begin the Implementation of pull to refresh flutter package library.

Step 1: Add Pull to Refresh Dependencies

Open pubspec.yaml file from your flutter project then you need to add the library dependencies.

dependencies:
  pull_to_refresh: ^1.5.8 // add this line

Here version may get updated so kindly check for the latest version on the official Flutter library

Once you add the dependencies you need to click on Packages Get then all the class will be added to your flutter project.

adding pull_to_refresh dependencies

Step 2: Import the flutter pull to refresh class where required

Then now once you have added the dependencies now you need to just import the library class there every required, In my case, I have imported in main. dart file

import 'package:pull_to_refresh/pull_to_refresh.dart';

Step 3:  Brief Snippet detail about SmartRefresh Flutter Widget

SmartRefresher(
      {Key key,
      @required this.controller,
      this.child,
      this.header,
      this.footer,
      this.enablePullDown: true,
      this.enablePullUp: false,
      this.enableTwoLevel: false,
      this.onRefresh,
      this.onLoading,
      this.onTwoLevel,
      this.onOffsetChange,
      this.dragStartBehavior,
      this.primary,
      this.cacheExtent,
      this.semanticChildCount,
      this.reverse,
      this.physics,
      this.scrollDirection,
      this.scrollController})

Here we need a controller that controls the loading and refreshing data when a user pulls down to refresh,

This SmartRefresh can have many properties example :

header: WaterDropMaterailHeader() used to show a header with a water drop Header animation effect.

enablePullDown true: to activity the pull-down to refresh

enablePullUp true: to activity the pull up to refresh

onRefresh: What should be performed when the user pulls down / pull up.

onLoading: basically used when we want to show a progress indicator to the user.

Step 4: Basic Snippet codes

List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()

    if (mounted)
      setState(() {
        items.add((items.length + 1).toString());
      });
    _refreshController.loadComplete();
  }

Step 5: Complete code

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.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,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
    "Item 7",
    "Item 8"
  ];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()

    print(items);
    if (mounted)
      setState(() {
        items.add((items.length + 1).toString());
      });
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Data time field"),
      ),
      body: Scrollbar(
        child: SmartRefresher(
          enablePullDown: true,
          header: WaterDropMaterialHeader(),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus status) {
              Widget body;
              if (status == LoadStatus.idle) {
                body = Text("pull up load");
              } else if (status == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (status == LoadStatus.failed) {
                body = Text("Load Failed!Click retry!");
              } else if (status == LoadStatus.canLoading) {
                body = Text("release to load more");
              } else {
                body = Text("No more Data");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            itemBuilder: (c, i) => Card(child: Center(child: Text(items[i]))),
            itemExtent: 100.0,
            itemCount: items.length,
          ),
        ),
      ),
    );
  }
}

 

 

Flutter Google Fonts Package Library – OR use Custom Fonts in Flutter ?

0
Flutter Google Fonts Package Library
Flutter Google Fonts Package Library

Hi Guys, Welcome to Proto Coders Point In this Flutter Tutorial we  Learn How to use google Fonts package library and also implement how can we add fonts in Flutter Applications.

Firstly Let’s make use of google fonts in our Flutter project

Brief about Flutter Google Fonts package?

The use Google_Fonts package in flutter application development allows use to make use of 977 free google fonts with their variants from fonts.google.com straight into your flutter app.

NOTE : as said in official flutter dev site that this package is in Beta testing, So the API is subjected to change anytime.

Official Site

With the use of Google Fonts package, Their is not need to store .ttf or .otf files in your flutter project assets folder and map in pubspec.yaml file.

Instead, this fonts package files is been fetched once via http at the runtime, and is been stored into cached memory of the app’s file system.

Let’s begin adding this library in flutter project.

Step 1 : Create a Flutter Project

Off-course you need to create a new flutter project or just work on your existing Flutter projects

File > New > New Flutter Project

Step 2 : Add Flutter Google Fonts package Dependencies

Once you Flutter Project is ready now to need to add the required dependencies in pubspec.yaml File

dependencies:
  google_fonts: ^0.3.9 // add this line

adding google font in flutter

Then once you have add the dependencies code just click on Packages get.

Step 3 : Import the fonts Packages

Once you add the dependencies now you can user the Fonts package wherever required in your flutter project

just you need to import the fonts package dart classes.

import 'package:google_fonts/google_fonts.dart';

Step 4 : Different ways to use Google Fonts in Flutter

with Default  Fonts TextStyle

Text(
              "Welcome to Proto Coders Point",
              style: GoogleFonts.pacifico(),
            )

flutter google font pacifico example

Text(
             "Welcome to Proto Coders Point",
             style: GoogleFonts.lacquer(),
           )

flutter google font package lacquer

using existing TextStyle

Text(
              'This is Google Fonts lato',
              style: GoogleFonts.lato(
                textStyle: TextStyle(color: Colors.blue, letterSpacing: .5),
              ),

Font styling in flutter

Making use of  fontSizefontWeight, or fontStyle:

In the below snippet code i have gave styling to the text using fontSize : 25 , fontweight : 700 , fontStyle : italic.

Text(
              'This is Google Fonts',
              style: GoogleFonts.tradeWinds(
                textStyle: Theme.of(context).textTheme.display1,
                fontSize: 25,
                fontWeight: FontWeight.w700,
                fontStyle: FontStyle.italic,
              ),

flutter google fonts size, weight, style

And there you go this is how we can use Google Font in flutter app.

Part 2 : How to use Custom Fonts in Flutter  Text Widget?

Here are the steps you need to follow to use of add Custom Fonts in Flutter Project

Steps to add custom font in flutter

Step 1 : Download and add/ import font file in flutter project

To download free google fonts go to https://fonts.google.com/

Then Select the Font that you  want to use in your project and download and extract the zip file.

How to download fonts from google fonts

Extract the Zip file of Font

google fonts downloaded file image

Now, Come back to Flutter project and Create a folder name ” fonts ”  and  copy the .ttf font file under that project.

Here is my project structure after creating fonts directory

creating a fonts directory in flutter project

I am making use of Vibur-Regular.ttf font to demonstrate.

Step 2 : Declare the font in Pubspec.yaml

fonts:
  - family: Vibur_fonts  #this family name will be used in textStyle
    fonts:
      - asset: fonts/Vibur-Regular.ttf

Note : In pubspec.yaml file the indentation is very much required, Even a single space might get you an error.

Step 4 : Use it is Text Widget

Now you can use the custom fonts in Text widget in your flutter application.

Text(
              "Text with Vibur Font Style",
              style: TextStyle(fontFamily: 'Vibur_fonts', fontSize: 30),
            ),

To apply the fontFamily use the family name we have declared in pubspec.yaml.

Flutter Custom font exmple

Complete Source code to Apply Google Fonts and Custom Fonts

just Copy paste the below code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.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,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Google Fonts in Flutter App ",
          style: GoogleFonts.lato(),
        ),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
              "Below is Example of Google Fonts Packages",
              style: TextStyle(color: Colors.indigo, fontSize: 20),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              "Default TextStyle",
              style: TextStyle(decoration: TextDecoration.underline),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              "Welcome to Proto Coders Point",
              style: GoogleFonts.lacquer(),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text("Using existing TextStyle",
                style: TextStyle(decoration: TextDecoration.underline)),
            SizedBox(
              height: 10.0,
            ),
            Text(
              'This is Google Fonts lato',
              style: GoogleFonts.lato(
                textStyle: TextStyle(color: Colors.blue, letterSpacing: .5),
              ),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              "Using properties size,weight,Style",
              style: TextStyle(decoration: TextDecoration.underline),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              'This is Google Fonts',
              style: GoogleFonts.tradeWinds(
                textStyle: Theme.of(context).textTheme.display1,
                fontSize: 25,
                fontWeight: FontWeight.w700,
                fontStyle: FontStyle.italic,
              ),
            ),
            SizedBox(
              height: 20.0,
            ),
            Text(
              "Below is Example of Custom Fonts",
              style: TextStyle(color: Colors.indigo, fontSize: 25),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              "Text with Vibur Font Style",
              style: TextStyle(fontFamily: 'Vibur_fonts', fontSize: 30),
            ),
          ],
        ),
      ),
    );
  }
}

Flutter List Wheel ScrollView – A 3D ListView in a flutter with Example

0
Flutter List Wheel ScrollView - A 3D ListView in flutter with Example
Flutter List Wheel ScrollView - A 3D ListView in flutter with Example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Widget of the week i.e  ListWheelScrollView used to build a listview with 3d scrollView effect in flutter.

Brief about Flutter ListWheelScrollView

ListView are great but sometimes ordinary Flutter ListView are boring, Therefore Flutter Team have built a new widget of the week that is List Wheel ScrollView.

This Widget is similar to a ListView but the difference here is that the  list will be somewhat like a 3d ListView. It’s a box in which a children is on a wheel can be scrolled.

Here i main thing to understand is When the list at the zero scroll offset,the first child is aligned with the middle on the screen, and when the list is at the final scroll offset, the list child is aligned with the middle viewport.

Here the children are been rendereed as a circular rotation rather then simple scrolling on a plane.

Visit official site to learn in depth Here

So Let’s set Implementing this Flutter Listwheelscrollview widget class in our project.

Widget Class Code for above widget

ListWheelScrollView(
             controller: _controller,
             itemExtent: 80,
             diameterRatio: 2.5,
             physics: FixedExtentScrollPhysics(),
             children: <Widget>[], //list of widget Here

ListWheelScrollView have many optional properties, where 2 property of them are mandatory @required children <Widget> [ ], and itemExtent : 80 

children <Widget> [ ] : accepts list of widgets

itemExtent : Specifies the pixel Height of each Children.

diameterRatio : you can tune the diameter of the list wheel widget.

offAxixFraction : -1.5 : Here is an Example on how the 3d listview looks when offassexFraction is set to -1.5.

Flutter List Wheel Scrollview Example

You can add a magnification effect to the flutter List Wheel ScrollView

magnification : used to set the zoomed size.

useMagnifier : true or false.

Here is an example for that

Flutter 3d Listview
usemagnifier is set to true

Creating a list of Widget

List<Widget> listtiles = [
  ListTile(
    leading: Icon(Icons.portrait),
    title: Text("Portrait"),
    subtitle: Text("Beautiful View..!"),
    trailing: Icon(Icons.arrow_forward_ios),
  ),
  ListTile(
    leading: Icon(Icons.landscape),
    title: Text("LandScape"),
    subtitle: Text("Beautiful View..!"),
    trailing: Icon(Icons.remove),
  ),
  ListTile(
    leading: Icon(Icons.map),
    title: Text("Map"),
    subtitle: Text("Map View..!"),
    trailing: Icon(Icons.wb_sunny),
  ),
  ListTile(
    leading: Icon(Icons.landscape),
    title: Text("LandScape"),
    subtitle: Text("Wonderful View..!"),
    trailing: Icon(Icons.wb_sunny),
  ),
  ListTile(
    leading: Icon(Icons.list),
    title: Text("List Example"),
    subtitle: Text("List Wheel Scroll view .!"),
    trailing: Icon(Icons.cloud),
  ),
  ListTile(
    leading: Icon(Icons.settings),
    title: Text("Settings"),
    subtitle: Text("Change the setting..!"),
    trailing: Icon(Icons.portrait),
  ),
  ListTile(
    leading: Icon(Icons.event),
    title: Text("Add data"),
    subtitle: Text("Data View..!"),
    trailing: Icon(Icons.add),
  ),
  ListTile(
    leading: Icon(Icons.landscape),
    title: Text("LandScape"),
    subtitle: Text("Beautiful View..!"),
    trailing: Icon(Icons.wb_sunny),
  ),
  ListTile(
    leading: Icon(Icons.email),
    title: Text("Email"),
    subtitle: Text("Check Email..!"),
    trailing: Icon(Icons.arrow_forward),
  ),
  ListTile(
    leading: Icon(Icons.games),
    title: Text("Games"),
    subtitle: Text("Play Games..!"),
    trailing: Icon(Icons.zoom_out_map),
  ),
];

In the above snippet code i have simply created a list of ListTile widgets .

The ListTile widgets simple have  some of it’s property like leading widget, title & subtitle of the listTile and a trailing widget as an Icon widget.

Then i m just using this List of Widgets in ListWheelScrollView Widgets to show the Items as it’s children.

ListWheelScrollView(
            controller: _controller,
            itemExtent: 80,
            magnification: 1.2,
            useMagnifier: true,
            physics: FixedExtentScrollPhysics(),
            children: listtiles, // Here listtiles is the List of Widgets.
          ),

Flutter List Wheel ScrollView – A 3D ListView in a flutter with Example

Complete Source code

Once you know the Basic of the Widget, Just Copy paste the Below lines of code in main.dart file.

import 'package:flutter/material.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,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FixedExtentScrollController _controller = FixedExtentScrollController();

  List<Widget> listtiles = [
    ListTile(
      leading: Icon(Icons.portrait),
      title: Text("Portrait"),
      subtitle: Text("Beautiful View..!"),
      trailing: Icon(Icons.arrow_forward_ios),
    ),
    ListTile(
      leading: Icon(Icons.landscape),
      title: Text("LandScape"),
      subtitle: Text("Beautiful View..!"),
      trailing: Icon(Icons.remove),
    ),
    ListTile(
      leading: Icon(Icons.map),
      title: Text("Map"),
      subtitle: Text("Map View..!"),
      trailing: Icon(Icons.wb_sunny),
    ),
    ListTile(
      leading: Icon(Icons.landscape),
      title: Text("LandScape"),
      subtitle: Text("Wonderful View..!"),
      trailing: Icon(Icons.wb_sunny),
    ),
    ListTile(
      leading: Icon(Icons.list),
      title: Text("List Example"),
      subtitle: Text("List Wheel Scroll view .!"),
      trailing: Icon(Icons.cloud),
    ),
    ListTile(
      leading: Icon(Icons.settings),
      title: Text("Settings"),
      subtitle: Text("Change the setting..!"),
      trailing: Icon(Icons.portrait),
    ),
    ListTile(
      leading: Icon(Icons.event),
      title: Text("Add data"),
      subtitle: Text("Data View..!"),
      trailing: Icon(Icons.add),
    ),
    ListTile(
      leading: Icon(Icons.landscape),
      title: Text("LandScape"),
      subtitle: Text("Beautiful View..!"),
      trailing: Icon(Icons.wb_sunny),
    ),
    ListTile(
      leading: Icon(Icons.email),
      title: Text("Email"),
      subtitle: Text("Check Email..!"),
      trailing: Icon(Icons.arrow_forward),
    ),
    ListTile(
      leading: Icon(Icons.games),
      title: Text("Games"),
      subtitle: Text("Play Games..!"),
      trailing: Icon(Icons.zoom_out_map),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("ListView ScrollView Wheel"),
        ),
        body: Center(
          child: ListWheelScrollView(
            controller: _controller,
            itemExtent: 80,
            magnification: 1.2,
            useMagnifier: true,
            physics: FixedExtentScrollPhysics(),
            children: listtiles, //List of widgets
          ),
        ));
  }
}