Home Blog Page 49

How to Create Custom tabBar in Flutter App

0
Flutter create custom tabbar
Flutter create custom tabbar

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial article will learn how to create custom TabBar in flutter.

I have already cover the basic on how to create tabbar in flutter, you can read it & implement yourself.

How to make a custom TabBar in flutter

In flutter custom TabBar can be created outside AppBar i.e in body property of Scaffold widget (flutter tabbar without appbar).

To create custom tabbar, we can use tabBar widget to acheive customized flutter tabs designs.

Step to create custom tabBar in flutter app

1. Wrap scaffold widget with DefaultTabController & define length (number of Tabs).

2. In Body property of Scaffold widget will use Column widget.

3. Column widget will contain 2 children widget

1st Child -> Container will hold TabBar with custom design to tabbar using indicator property.

2nd Child -> Expanded widget that will have TabBarView which loads it’s children (i.e. different pages) depending on tabs user has selected.


Complete Source Code – To build custom TabBar in Flutter App

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // 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,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          title: Text("Flutter TabBar Example - Customized "),
        ),
        body: Padding(
          padding: EdgeInsets.all(8.0),
          child: Column(
            children: [
              Container(
                height: 45,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(25.0)
                ),
                child:  TabBar(
                  indicator: BoxDecoration(
                    color: Colors.green[300],
                    borderRadius:  BorderRadius.circular(25.0)
                  ) ,
                  labelColor: Colors.white,
                  unselectedLabelColor: Colors.black,
                  tabs: const  [
                    Tab(text: 'Chats',),
                    Tab(text: 'Status',),
                    Tab(text: 'Calls',),
                    Tab(text: 'Settings',)
                  ],
                ),
              ),
              const Expanded(
                  child: TabBarView(
                    children:  [
                      Center(child: Text("Chats Pages"),),
                      Center(child: Text("Status Pages"),),
                      Center(child: Text('Calls Page'),),
                      Center(child: Text('Settings Page'),)
                    ],
                  )
              )
            ],
          ),
        )
      ),
    );
  }
}

How to create TabBar in flutter

0
Flutter create tabbar with example code
Flutter create tabbar

Hi Guys, Welcome to Proto Coders Point. In this Flutter tutorial Article will learn how to create tabBar in flutter.

What is the TabBar Flutter

The tabs in flutter are used for page navigation, by using which user can easily switch between pages by simple tapping on the flutter tabs, so it will generate TabView pages with respective pages & display it at body TabBarView.

Note: The styling of TabBar may defer depending on the Operating System your flutter app is running on, looking into an example. Android devices will place TabBar at the top of the screen below appbar, while when you run flutter app in iOS then the TabBar get created at bottom of iOS devices.

Therefore if you want TabBars at bottom of screen then simply, then it better to make use of flutter bottom navigation bar instead of tabBar.


How to create TabBar in flutter

Video Tutorial

In flutter we can easily create a TabBar for Navigation between Pages content, In one main page you can load multiple page content using tabBarView.

To add tabs in flutter app, we need to Wrap Scaffold Widget with DefaultTabController & provide a length (the number of tabs you want to create), then in flutter appbar create tabBar with tabs, then in body use TabBarView & define some widget or pages that you want to show when tabs from flutter tabbar are selected.

Let’s get Started in step-by-step to create tabBar in flutter app.

1st Step: Open Existing Flutter Project or create new Project.

I use android Studio to build flutter apps.

so in your project in main.dart copy paste below code as a starting code.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            "Flutter TabBar Example",
          ),
        ),
        body: const  Center(
          child: Text("Here will show tab view seleted pages"),
        ) 
    );
  }
}

Here, we have Scaffold widget with appbar and body property.


2nd Step: Wrap Scaffold widget with DefaultTabController

To add TabBar in flutter you need to wrap scaffold widget with flutter DefaultTabController and define length ( The number of tabs you want to create in tab bar).

return DefaultTabController(
      length: 3,
      child: Scaffold(
          appBar: AppBar(
            title: const Text(
              "Flutter TabBar Example",
            ),

          ),
          body: const  Center(
            child: Text("Here will show tab view seleted pages"),
          ) ),
    );

3rd Step: Add Tabs in Appbar

As we have defined TabController length = 4, therefore we need to add 4 tab within TabBar, as I have done above.

Our here i have created 4 tabs ” Chats, Status, Calls, Settings tabs”. you can create as per your app UI needed.

DefaultTabController(
      length: 4 ,
      child: Scaffold(
          appBar: AppBar(
            title: Text("Flutter TabBar Example"),
            bottom: TabBar(
              tabs: [
                Tab(text: 'Chats',),
                Tab(text: 'Status',),
                Tab(text: 'Calls',),
                Tab(text: 'Settings',)
              ],
            ),
          ),
          body: const  Center(
            child: Text("Hello"),
          ) ),
    );

4th Step: Add TabBarView Pages in body property of Scaffold Widget

Now, We have successfully added tabBar in Appbar and Also wrapped Scaffold widget with DefaultTabBarController, now when user want’s to switch between Tabs in flutter app, we need show selected tab page, therefore in body property of scaffold widget we must use TabBarView with 4 childrens widget/pages.

body: TabBarView(
            children: [
              Center(child: Text('Chats Page'),),
              Center(child: Text('Status Page'),),
              Center(child: Text('Calls Page'),),
              Center(child: Text('Settings Page'),)
            ],
          ),

Complete Source Code – Flutter create TabBar using DefaultTabController

main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4 ,
      child: Scaffold(
          appBar: AppBar(
            title: const Text(
              "Flutter TabBar Example",

            ),
            centerTitle: true,
            bottom: TabBar(
              tabs: [
                Tab(text: 'Chats',),
                Tab(text: 'Status',),
                Tab(text: 'Calls',),
                Tab(text: 'Settings',)
              ],
            ),
          ),
          body: TabBarView(
            children: [
              Center(child: Text('Chats Page'),),
              Center(child: Text('Status Page'),),
              Center(child: Text('Calls Page'),),
              Center(child: Text('Settings Page'),)
            ],
          ),
      ),
    );
  }
}

Flutter – How to get App Name, Package Name, Version & Build number

0
Flutter Get App Package info

Hi Guys, Welcome to Proto Coders Point. In this flutter Article will learn how to get app name, package name, app version and build number of app programmatically by using flutter package info plus dependencies.

Package_info_plus

Flutter plugin that help us in getting app information, basically a API for querying detail info about the application programmatically.

Platform supported

Package info plus flutter plugin support all the OS : Android, iOS, MacOS, Web, Linux, Windows.

How to use package info plus

Installation

Open pubspec.yaml file & under dependencies section add plugin

dependencies:
  package_info_plus:

Then hit pub get button.

Alternatively, To add the package using terminal, in IDE terminal rub below cmd

flutter pub add package_info_plus

Import it

Now in dart file, where you want to use the package import it example: main.dart

import 'package:package_info_plus/package_info_plus.dart';

Code usage

Initialize

 PackageInfo packageInfo = await PackageInfo.fromPlatform();

Now by using packageInfo object, you can easily get appName, packageName, AppVersion & app build number.

    String appName = packageInfo!.appName;  

    String packageName = packageInfo!.packageName;

    String version = packageInfo!.version;

    String buildNumber = packageInfo!.buildNumber;

Complete Source Code – get package detail in flutter

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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

        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  PackageInfo? packageInfo;

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

  }

  void getPackage() async {
    packageInfo = await PackageInfo.fromPlatform();

    String appName = packageInfo!.appName;
    String packageName = packageInfo!.packageName;
    String version = packageInfo!.version;
    String buildNumber = packageInfo!.buildNumber;

    print("App Name : ${appName}, App Package Name: ${packageName },App Version: ${version}, App build Number: ${buildNumber}");
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body:  Center(
        child: Text("Flutter get Package info"),
      )
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Find the smallest positive missing number in array

0

Hi Guys, Welcome to Proto Coders Point. Here is the solution for a problem statement “Find the smallest positive number that does not appear in array”. – JAVA PROGRAM

You car given a Array (Sorted/UnSorted), You need to search the missing small number in the array.

Example

Array { 1, 4, 5, 7, 6 }

Here the missing smallest number starting from 1 to N is checked, so as you can see missing number in above array is 2. After 1 we directly have 4, 5, 7, 6. Therefore 2 is smallest number & is missing .

Example 2

Array { 6, 5, 1, 2, 3, 7 } output: 4.


Source Code JAVA Program – To Find the positive smallest number missing in Array

import java.util.*;
import java.util.Arrays;

class HelloWorld {
    public static void main(String[] args) {
       
        int arr[] = {6,5,1,2,3,7};

        int result = findMissSmall(arr);

       System.out.println(""+result );
    }

    static public int findMissSmall(int[] A) {
        
        int len = A.length;
        int min=1;
        Arrays.sort(A);
   
        if(A[len-1]>0)
        for(int i=0; i<len; i++){
            if(A[i]>0){
                if(A[i]==min) min=min+1;
                if(A[i]>min) break;
            }
        }
        return min;
    }
}

In code, we have manully declared an array & then we are passing the array to findMissSmall() function that iterate through the arrray and return us the smallest missing number in the list.

Let’s understand how findMissSmall() function works

  1. get length of array.
  2. set min = 1.
  3. sort the array.
  4. Perform for-loop to get smallest missing num.

Let’s take the array for tracing with above program

arr = { 6, 2, 1, 5 }

after sorting arr = { 1, 2, 5, 6 }

In for loop

Iteration 1

i = 0, len = 4, min = 1, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 1 = 1 true, so increment min
min = min + 1; // min = 2


Iteration 2

i = 1, len = 4, min = 2, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 2 = 2 true, so increment min
min = min + 1; // min = 3


Iteration 3

i = 2, len = 4, min = 3, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 5 = 3 false, so don’t increment min
min = min + 1;

if( A[i] > min)
break; // 5 > 3 true,

In iteration 3, A[i] is not equal to min i.e 5 != 3, so dont increment min, then check if A[i] > min i.e 5 > 3 so break the for loop and come out.


Finally we have found smallest missing number in Array, return min = 3.

Note: Trace above program by your own Array, it will improve your programming logic & skill & code thinking.

How random number generator works – python random module example

0
python randoan number generator
python randoan number

Welcome to Proto Coders Point, We will lead you to the most readily  understandable solution for your question. Then let’s understand How Random Number Generation (RNG) works in computer.  

It is evident that the game of Tambola involves pure luck, just like when we do things like randomly picking an item, rolling the dice, or considering other activities without the use of computers. 

Would you consider computer generated randomness to be luck? Right, but how does it work? It’s an algorithm,yes , which generates the randomness.

Random number

Let’s explore further. 

  • How RNG works set an example.
  • Need for RNG.
  • It’s Applications in use.
  • Methods: Built-in functions & creating a function for it.
  • Approaches of these Methods.
  • Summarization  

Have you ever thought about why it is impossible to predict what number will be chosen while you play Tambola? Have you ever considered why such randomness is needed? No, probably we think we love to play with our luck right? It seems  exciting, doesn’t it? But what if I told you that there is a shocking truth behind  such randomness. 

Computers were driven by the need to generate random numbers since humans  were not very good at creating them for various security purposes, such as  passwords and cryptography. If I tell you to generate 100 random numbers  between 0-99, you won’t be able to come up with 100100, since you know it will  take a long time, and the probability of the numbers will also be difficult to  understand. The problem will be solved if I give you a set of instructions to do it. However, it will be time-consuming, even after I set an algorithm for you to  generate the numbers.

What algorithm does the computer use to generate such an algorithm 

For instance, you like someone and you search for their name on some social site, only to find duplicate profiles with exactly the same name and picture. Oh wait,  how will you find out who the real person is and tell him/her about the fake  accounts? It’s not like you’re going to ask everyone if that’s really her/him. However, you could go and ask the right person personally for their numerical ID for that site. That would work better than falling victim to fraud. 

In simulations, there are thousands of cases in which a little randomness can  make a difference, whether it’s weather patterns, traffic patterns, or shuffling  cards. Then let’s understand how Random Number Generation (RNG) works in  computer. 

In order to simulate randomness, we create deterministic sequences of numbers  that are thought to resemble what random numbers would look like, calling this  pseudo-RNG. They are calculated through a seed value of an algorithm, there are  several pseudo-RNG implementations based on linear congruential generators  based on recurrence relations (Xn + 1 ≡ aXn + c (mod m)

What is python RNG

Additionally, There is something called truly/real-RNG. You can use this security measure to protect transactions such as purchases, tax payments, bank transfers, etc. In order to ensure security and effectively manage fraud & privacy, encryption should be used, since it shouldn’t be vulnerable to hacking.  

Hence a need for entropy, a starting point that cannot be replicated: the first digit you use to create an ID for each transaction must be unique; anything that is replicable is vulnerable. As a solution, truly-RNG uses internal hardware to physically generate randomness, such as number of clock cycles in the processor or mouse movements. It can be used to solve any complicated or sophisticated  application. 

Different Method to generate Random number in Python

It’s time to create a Random number generator python module like that, and what better tool to use than Python 

The Python language works best with less code, use built-in functions, or build any method module you want for it.

Let’s explore the code for pseudo RNG by understanding the basics of random number generation. In simple terms, let’s build for all 8 built-in functions for  generating random numbers in Python. 

NOTE: (*import random python*) Before performing any operations on random generations.

python random module

FUNCTION PURPOSE SAMPLE
Random() Radom floating-point  number [0-1] is  generated, but excludes 0  & 1Randome.random()
Uniform(a,b) Floating-point value  between a & b is  generated. Takes two  parameters to start & to  stop then return float  between them including  the limitsRandom.uniform(3,9)
Randint(a,b) Including a & b generates  random integer from a to  b. Within specified limit like a<= <result> <=brandom.randint(1,5)
Randrange(start,stop,step) Random integer  generated in the  range(start,stop,step) Default value of step is 1Random.randrange(0,1,3)
Shuffle(a) Shuffles list a in place and  return Nonealist = [34,12,94,65,71] print(random.shuffle(alist))
Seed(a) Every time seed(a) is  called same sequence of  random numbers are  generatedRandom.seed(2) Print(random.randint(1,100)) #need same random seed add  Random.seed(2) Print(random.randint(1,100))
Sample(population, n)  Selects n vigilant random  items from a given  population set seq = (23,65,12,90,06) random.sample(seq,3)
Choice(s)  Random item from non empty sequence seq is  chosen. seq = (23,65,12,90,06) random.choice(seq)

Python random number between 0 and 1

In Python to generate a random number between 0 and 1, we can make use of python ‘random’ module

import random

random_number = random.random()

print(random_number) // 0.8046595183024017

Conclusion

Here’s a quick Recap: Our lesson covered what random number generation (RNG)  is, its purposes, its applications, and its uses, as well as the two methodologies  that are used for RNG. As a final step, we learned about Python’s built-in  functions for RNG, with sample code. Make sure you practice this in your python  interpreter. Isn’t RNG been fun? In addition to its value in number generation  methods, it is used widely in many areas, which is driving the development of  technology. It certainly bears in the role of Data Science statistics, irrespective of  whether it is video games, security protection, or encryption. Now it’s time to  build your own module with a purpose. Continue to explore.

How to read contacts list in flutter & display it in listview

0
Flutter Read Contacts List
Flutter Read Contacts List

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial will learn how to access contact list in flutter app.

So here, we will read phone contact list & display it in flutter list & we will also implement making a call when user tap on any contact.

Let’s get started

Strat by creating new flutter project or open existing project in you favorite IDE, I use Android Studio.

Flutter get contact list & make call

Plugin used – Add Dependencies

  1. flutter_contacts: To read contacts from android & iOS devices.
  2. url_launcher: To Make a call when user tap on phone number list.

As i said ,from getting contact list froom phone will user flutter_contacts & to make a phone call will use url_launcher, so add those 2 dependencies in pubspec.yaml file under dependencies sections.

dependencies:
  flutter_contacts:
  url_launcher:

Here i am not defining any version so it will auto take latest version, now hit pub git to download & install above plugin.


Platform specific setup

Android Setup’s

Make sure, flutter android module is enabled to support AndroidX, goto android/gradle.properties

check it or add as below

android.useAndroidX=true
android.enableJetifier=true

Check for compileSdkVersion is 28 or above

android/app/build.gradle file

android {
    compileSdkVersion 31
}

Add permission to access device contact list

Open manifest file, android/add/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

To make a call, we must add DIAL action query in manifest file

<queries>
<!-- If your app makes calls -->
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
</queries>

iOS setup

For iPhone, you need to add NSContactsUsageDescription in info.plist file

ios/Runner/info.plist

<dict>
     ...
     <key>NSContactsUsageDescription</key>
     <string>Reason we need access to the contact list</string>
 </dict>

3. Import flutter_contacts & url_launcher

Now, In main.dart on top import the 2 required dependencies.

import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';

4. Code usage

Flutter plugin to read contacts, by using flutter contacts plugin we can read, create, update, delete contact from devices.

In this tutorial we ill only look into how to read contact in flutter & display in flutter app.

get all contact (lightly fetch)

List<Contact> contacts = await FlutterContacts.getContacts();

get all contacts (fully fetch)

 List<Contact> contacts = await FlutterContacts.getContacts(
      withProperties: true, withPhoto: true);

Get contact first name

contacts.name.first

Get contact last name

contacts.name.last

Get contact full name

contacts.displayname

Get contact email

contacts.emails.first.address

get contact photo

contacts.photo

Source Code – Flutter read contacts list & display it in listview builder

IN below code we are fetchiing all the contacts from contact list & display it in flutter listview builder and when user click or taps on particular phone number from list will make a phone call directly.

main.dart

import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Contact>? contacts;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getContact();
  }

  void getContact() async {
    if (await FlutterContacts.requestPermission()) {
      contacts = await FlutterContacts.getContacts(
          withProperties: true, withPhoto: true);
      print(contacts);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            "***  App Name  ***",
            style: TextStyle(color: Colors.blue),
          ),
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: (contacts) == null
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: contacts!.length,
                itemBuilder: (BuildContext context, int index) {
                  Uint8List? image = contacts![index].photo;
                  String num = (contacts![index].phones.isNotEmpty) ? (contacts![index].phones.first.number) : "--";
                  return ListTile(
                      leading: (contacts![index].photo == null)
                          ? const CircleAvatar(child: Icon(Icons.person))
                          : CircleAvatar(backgroundImage: MemoryImage(image!)),
                      title: Text(
                          "${contacts![index].name.first} ${contacts![index].name.last}"),
                      subtitle: Text(num),
                      onTap: () {
                        if (contacts![index].phones.isNotEmpty) {
                          launch('tel: ${num}');
                        }
                      });
                },
              ));
  }
}