How to create a Simple TabBar with Tabbarview in Flutter

In this post, we are going to see how to build a simple TabBar in Flutter. We will start with a very basic view to add a tab bar first within an AppBar. We will also see how to add icons and other customizations to a TabBar in a flutter.

Lets get started!

Step 1: Create a project in a flutter in android studio

First Go to your android studio/VS code and create a new flutter app and give the name as flutter_tabs with other default settings.

Step 2: Working with Main.dart

Since you already know that Flutter workes mostly by adding widget and when you run the main dart file the execution of your app starts.

Just give a try to run the app to make sure everything works fine.

To create a TabBar we need to create three things

  • Create a TabController.
  • Create the tabs.
  • Create content for each tab.


Step 3: Add a Stateless Widget to the Main.dart File and give the class name as TabBarDemo

 class TabBardemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Step 3.1 Update the Main() Method to execute the widget

void main() {
  runApp(TabBarDemo());
}
Step 4: Adding a TabController 

 Now we can go-ahead and add a TabController. To Make sure the view and the tabs are in sync we are going to use this TabController .You can create a TabController manually or automatically by using the DefaultTabController To add a default Tab Controller you can add the below code in you MaterialApp Widget.

home: DefaultTabController(
        length: 3,
        child: Scaffold())
Step 4.1: Create a Tab

 When a tab is selected, it needs to display content. You can create tabs using the TabBar widget. In this example, create a TabBar with three Tab widgets and place it within an AppBar.

home: DefaultTabController(
        length: 3,
        child: Scaffold(
          backgroundColor: Colors.blueGrey[50],
          appBar: AppBar(
            title: new Text("Simple Tab Demo"),
            backgroundColor: Colors.lightBlue[900],
            bottom: TabBar(
              tabs: [
                Tab(
                   text: ("One"),
                ),
                Tab(
                  text: ("Two"),
                ),
                Tab(
					text: ("Three"),
				)
              ],
            ),
          ),
        ),
      ),

Step 4.2: Add a TabView 

 we need to add content to each tab .To add content to we are going to add TabBarView Widget within body

body: TabBarView(children: [
            Center( child: Text("One",style: TextStyle(fontSize: 50),)),
            Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
            Center( child: Text("Three",style: TextStyle(fontSize: 50),))
          ]),


Step 5:
Run the App (main.dart File) 

 Final Code

import 'package:flutter/material.dart';

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

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          backgroundColor: Colors.blueGrey[50],
          appBar: AppBar(
            title: new Text("Simple Tab Demo"),
            backgroundColor: Colors.lightBlue[900],
            bottom: TabBar(
              tabs: [
                Tab(
                   text: ("One"),
                ),
                Tab(
                  text: ("Two"),
                ),
                Tab(text: ("Three"),)
              ],
            ),
          ),
          body: TabBarView(children: [
          Center( child: Text("One",style: TextStyle(fontSize: 50),)),
          Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
          Center( child: Text("Three",style: TextStyle(fontSize: 50),))
        ]),
        ),
      ),
    );
  }
}

class TabBardemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Build REST API in Django Using Rest Framework [Function based views]

1 . Introduction

In this post, we are going to learn about function based views in Django. Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn’t have to write boilerplate (i.e. the same code) code over and over again.



2. Setup

Let's create a project first and setup URLs (skip this section if you are already aware of this setup).

#Create a fresh virtual environment
mkvirtualenv env (On creating, env will be activated automatically. Activate it if you navigate to a new tab.)

#Install Django 
pip install Django

#Go to your favourite directory and create a new project
django-admin.py startproject StudentService

#Important step. Perform all the operations in this directory. When I say 'project_template' directory in future, it points to the directory present inside this, i.e,. project_directory/project_directory.
cd StudentService
Lets create a sample app 'students'.

python manage.py startapp students

3. Setting Up Project Settings.py
Add 'students' + rest_framework to installed apps in your settings.py files



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'students',
    'rest_framework'
]

Modify your Database settings as well. We are going to work with MYSQL Database

Add this to your settings.py file


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'studentdb',
        'USER': 'root',
        'PASSWORD': ''
    }
}

4. Working with models

Let's build the model for our API. In this example, we are going to see how to store students scores for examinations.

We are going to capture ID, NAME & score details of each individual student. 

Add the below code to the models.py inside the student's folder.


from django.db import models

# Create your models here.

class Students(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length = 20)
    score = models.DecimalField(max_digits=10,decimal_places=3)

    def __str__(self):
        return self.id+self.name+self.score

5. Adding Serializers

Now its time to create a Serializers for API. 

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

First, create a file called serializers.py and add the below code.


from rest_framework import serializers
from students.models import Students

class StudentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = ["id","name","score"]

in the fields, sections above you can use __all__ to add all the columns for serializations. If you want to capture individual ones you can pass a list of column names.


6. Updating the views.py

Finally, let's create Views.py

First we need to be able to fetch all the results by performing a GET and also should be able to add a new student record.

The below code helps you fetch all records on GET and add new student details. The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: 



@api_view(['GET','POST'])
def students_list(request):
    if request.method == 'GET':
        students = Students.objects.all()
        serializers = StudentSerializers(students,many=True)
        return Response(serializers.data)

    elif(request.method == 'POST'):
        serializers = StudentSerializers(data=request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data,status=status.HTTP_201_CREATED)
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)
In the next scenario we are going to see how to work with individual student records using GET,PUT,DELETE

The PK here is the primary key column in your database which is ID in our case. 


api_view(['GET','PUT','DELETE'])
def students_details(request,pk):
    try:
        student = Students.objects.get(pk=pk)
    except Students.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializers = StudentSerializers(Students)
        return Response(serializers.data)

    elif request.method == 'PUT':
        serializers = StudentSerializers(Students,request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data)
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        Students.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Make sure to import all the necessary modules 


from students.models import Students
from students.serializers import StudentSerializers
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

7. Finally Urls.py
Last we will add the URLs to make sure we are able to hit it via the endpoints

Add/update the URL patterns in urls.py in StudentService


urlpatterns = [
    path('admin/', admin.site.urls),
    path('students/', views.students_list),
    path('students/', views.students_details),

]


This function based views is very easy to implement and it’s very useful but the main disadvantage is that on a large Django project, usually a lot of similar functions in the views. If all objects of a Django project usually have CRUD operations so this code is repeated again and again unnecessarily and this was one of the reasons that the class-based views and generic views were created for solving that problem.

Conclusion:

We saw how to use the function based views in this post while there are other types of views as well which we will cover in upcoming posts. if you want to know if function based views are best among all then it all depends on the context and the needs. As I mentioned in the beginning of this post, class-based views does not replace function-based views. There are cases where function-based views are better. In other cases, class-based views are better.


How to build a User Registration(Login/Signup/Logout) System in Django

1. Introduction


In this post, we are going to see how to build a User registration system in Django using the auth module in Django. The example will cover steps to build your registration system where users can register(signup)/login using the credentials and logout of the system.



Let's get Started! 

2. Starting a new Project 

If you are new to Django, please make sure to check out the steps to create a virtual envt in python before creating a Django project. If you already have one you can continue to follow along with me.

Step #1 : Create a Django project

We are not going to use any database-model for this tutorial, we will cover soon in some other post. Let's create a new Django project by running the below command inside your virtual env.

 django-admin startproject mysite

Step #2: Create a Django app

In this tutorial, we’ll create our accounts app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp accounts

Once done you should be able to see a below folder structure with the below files.

Step #3: Update your Setting.py


Make sure to update your setting.py with a new app so that it can be picked up while running the server.

INSTALLED_APPS = [

    'accounts.apps.AccountsConfig',
	
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

3. Building your Base template for homepage/signup page/login page/login

First, we are going to build a base template for our homepage using Bootstrap. Navigate to mysite ((app) inside the main mysite project). create a template folder and add a file called base.html

You can paste the below code inside base.html .This will be a basic template which we are going to use in our project.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">


  <title>NintyZero</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body>

  <header>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="">NintyZero</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      </div>
    </nav>
  </header>
  <div class="container">
      {% block content %}
      {% endblock %}
  </div>

  <footer class="text-muted">
    <div class="container text-center">
      <p>This is a footer {% now "Y" %}</p>
      </div>
  </footer>

  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

</code></pre>

4.Updating the URL for navigation 

To update the URL pattern (for ex we want to show login page once user reaches account/login or account/signup. we can do that by adding the URL pattern in urls.py file(if not found create one) inside your mysite folder and add the below code.

from django.contrib import admin
from django.urls import path,include
from products import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name="home"),
    path('accounts/',include ('accounts.urls')),
]


5.Adding view for Login/Signup/Logout

Create a template/account folder inside account app and add two Html files named login.html and signup.html

Use the below code to create a Signup Page


{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Signup!</h1>

<form method = "POST" action="{% url 'signup' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password1" />
    <br/>
    confirm Password:
    <br/>
    <input type="password" name="password2" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "signup" />
    <br/>



</form>


{% endblock %}
Login.html

{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Login!</h1>

<form method = "POST" action="{% url 'login' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "Login" />
    <br/>



</form>


{% endblock %}

6. Adding the logic for login and signup

Open the view.py (create one if now found) inside accounts app folder and add the below code to it.

from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password1'] == request.POST['password2']:
            try:
                User.objects.get(username = request.POST['username'])
                return render (request,'accounts/signup.html', {'error':'Username is already taken!'})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['username'],password=request.POST['password1'])
                auth.login(request,user)
                return redirect('home')
        else:
            return render (request,'accounts/signup.html', {'error':'Password does not match!'})
    else:
        return render(request,'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'],password = request.POST['password'])
        if user is not None:
            auth.login(request,user)
            return redirect('home')
        else:
            return render (request,'accounts/login.html', {'error':'Username or password is incorrect!'})
    else:
        return render(request,'accounts/login.html')

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
    return redirect('home')


Conclusion:

In this post, we learned how to build a user login and signup systems. we also saw how to build views and use it to register and log in.

Getting Started with Django Quickly [Step by Step tutorial]

1. Introduction:


In this post, we are going to see an overview of Django (as a tutorial) and setting up the environment to get started with building WebApps or Rest APIs.

Before we start setting up the environment we can have a look into the features Django brings to help with development.


YouTube-Style Face Detect - Crop and Blur using python and OpenCV

This post will focus on the core concepts in image processing. These areas will act as the building blocks for more intricate image manipulations in a later post. Becoming familiar with these characteristics of using Python and OpenCV, we will then be able to jump around to the different concepts more easily. 

Face processing is a hot topic in artificial intelligence because a lot of information can be automatically extracted from faces using computer vision algorithms. 

The face plays an important role in visual communication because a great deal of non-verbal information, such as identity, intent, and emotion, can be extracted from human faces.

Face processing is a really interesting topic for computer vision learners because it touches on different areas of expertise, such as object detection, image processing, and landmark detection or object tracking.




A Simple Explanation of Regularization in Machine Learning

In this post, we are going to look into regularization and also implement it from scratch in python (Part02). We will see with example and nice visuals to understand it in a much better way. We already know about the Linear regression where this is used.


In-depth Explained Simple Linear Regression from Scratch - Part 1

In my opinion, most Machine Learning tutorials aren’t beginner-friendly enough. It very math-heavy or it doesn't help you with the algorithms behind it.
In this post, we are going to do the simple Linear Regression from scratch. We will see the mathematical intuition behind it and we write the code from scratch + test it and I'm super excited to get started!!




Overview Guide To Tensorflow 2.x with Examples


The most concise and complete explanation of what TensorFlow is can be found at (https://www.tensorflow.org/) and it highlights every important part of the library.

TensorFlow is an open-source software library for high-performance numerical computation.

Its flexible architecture allows easy deployment of computation across a range of platforms (CPUs, GPUs, and TPUs), from desktops to clusters of servers, to mobile and edge devices.

Originally developed by researchers and engineers from the Google Brain team within Google's AI organization, it comes with strong support for machine learning and deep learning,and therefore the flexible numerical computation core is employed across many other scientific domains.

In this blog post, we are going to see the basics for TensorFlow 2.x. This can be used as getting started guide to learn and understand it.

I'm not going to cover the installation/Setup of the Jupyter part as this can be found online easily.




Create a CRUD Restful Service API using Flask + Mysql [in 7 minutes!]

In this article, we will learn how to build Simple Restful API with flask and Mysql that have capabilities to create, read, update, and delete data from the database.

Flask being a microframework provides the flexibility of the data source for applications and also provides library support for interacting with different kinds of data sources. There are libraries to connect to SQL- and NoSQL-based databases in Flask.