Thursday 12 October 2023

Flutter | Create A Scrollable Pagination | Horizontal

 



Flutter | Create A Scrollable Pagination | Horizontal

-------------------------------

Link 1 Code (Data table) :-

https://unpossiblepog.blogspot.com/2023/10/Flutter-Datatable-With-Horizontal-Scroll-Display-Data-From-Rest-API.html

Note : Watch the video to understand how the code was made so that you can easily make changes as per your need.

Subscribe my Channel:-

http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Gaming Channel:-

https://www.youtube.com/@unpoggaming9532

Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

Facebook Page:-

https://www.facebook.com/UnpossibleNS

Twitter Account:-

https://twitter.com/UnpossiblePOG

Blog:-

https://unpossiblepog.blogspot.com/

Website:-

https://unpossiblepog.com/

========================

Important Note : Make sure to add “http: any” dependency in pubspec.yaml file.

main.dart code :

import 'package:flutter/material.dart';

import 'package:flutter/foundation.dart';

import 'package:http/http.dart' as http;

import 'dart:convert';

void main() {

runApp(const showListingPage());

}

List? dataList;

int totalPages = 0;

String filterListingString = "";

class showListingPage extends StatelessWidget {

const showListingPage({Key? key}) : super(key: key);

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'View All',

routes: {

},

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: const ViewAllPage(title: 'View All'),

);

}

}

class ViewAllPage extends StatefulWidget {

const ViewAllPage({Key? key, required this.title}) : super(key: key);

final String title;

@override

State<ViewAllPage> createState() => _ViewAllPageStateViewAll();

}

class _ViewAllPageStateViewAll extends State<ViewAllPage> {

int total_records = 0;

List _posts = [];

int curr_page = 1;

int count_per_page = 2;

void loadDataFromAPI(int page_number,int per_page) async {

try {

final res =

await http.get(Uri.parse("http://unpossiblepog.com/apis/getFlutterPaginationApi.php?page="+page_number.toString()+"&per_page="+per_page.toString()));

setState(() {

_posts = json.decode(res.body);

if(_posts.length>0)

{

dataList = _posts;

total_records = int.parse(_posts[0]['count']);

totalPages =

(total_records / count_per_page).ceil();

}

});

} catch (err) {

if (kDebugMode) {

print('Something went wrong');

}

}

}

double numberFunction(int i)

{

int nun = i.toString().length;

String finalString = "0.";

for(int j=0;j<nun;j++)

{

finalString += "1";

}

finalString += "0";

return double.parse(finalString);

}

MaterialColor getColorForThis(int i)

{

MaterialColor c=Colors.green;

if(i==curr_page)

{

c=Colors.blue;

}

return c;

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: const Text('View All'),

centerTitle: true,

actions: <Widget>[],

),

body: ListView(children: <Widget>[

SingleChildScrollView(

padding: const EdgeInsets.all(8.0),

scrollDirection: Axis.horizontal,

child: DataTableOutputViewAll(),

),

SingleChildScrollView(

scrollDirection: Axis.horizontal,

child: Row(children: <Widget>[

SizedBox(

width: MediaQuery.of(context).size.width * 0.05,

),

//totalPages

for(var i=0;i<totalPages;i++) ...[

Container(

width: MediaQuery.of(context).size.width * numberFunction(i) * 1.5,

margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),

height: 50.0,

child: RaisedButton(color: getColorForThis(i+1),

child: new Text(""+(i+1).toString(),style: TextStyle(color: Colors.white),),

onPressed: (){

curr_page = i+1;

loadDataFromAPI(i+1,count_per_page);

},

),

)

],

SizedBox(

width: MediaQuery.of(context).size.width * 0.05,

),

],),

)

]),

);

}

@override

void initState() {

super.initState();

dataList = null;

totalPages = 0;

if (dataList == null) {

loadDataFromAPI(1,count_per_page);

}

}

@override

void dispose() {

super.dispose();

}

}

class DataTableOutputViewAll extends StatelessWidget {

const DataTableOutputViewAll({Key? key}) : super(key: key);

List<InlineSpan> getData(Map<String, String> amount_entry_details) {

List<InlineSpan> temp = [];

amount_entry_details.forEach((k, v) => {

temp.add(

TextSpan(

style: const TextStyle(

color: Colors.black,

),

children: <TextSpan>[

TextSpan(

text: k + ' : ',

style: const TextStyle(fontWeight: FontWeight.bold)),

TextSpan(text: v + '\n'),

],

),

),

});

return temp;

}

@override

Widget build(BuildContext context) {

List<DataRow> rows = [];

if (dataList != null) {

for (int i = 0; i < dataList!.length; ++i) {

rows.add(DataRow(

cells: <DataCell>[

DataCell(Text(

'' + dataList![i]['language'].toString(),

style: TextStyle(fontSize: 15)),onTap: (){

}),

DataCell(

Text(

'' + dataList![i]['post_title'].toString(),

style: TextStyle(fontSize: 15)),onTap: (){

}),

],

));

}

}

return DataTable(

columns: const <DataColumn>[

DataColumn(

label: Text(

'Language',

style: TextStyle(fontStyle: FontStyle.italic),

),

numeric: false,

),

DataColumn(

label: Text(

'Title',

style: TextStyle(fontStyle: FontStyle.italic),

),

numeric: false,

),

],

rows: rows,

);

}

}

========================

Hey guys.

I have made a code which will generate a scrollable pagination feature in Flutter App. Today I am going to be sharing it’s code with you guys. Let’s get started.

The tutorial is divided into 2 phases.

1st is displaying data in data table.

2nd is adding scrollable pagination at bottom.

To execute the phase 1, what we shall do is a copy-paste from my blog. The link is given in the description with a title as “Link 1 Code (Data table)”

Instructions are given, we just have to follow it.

In new project, we shall add a dependency.

Make sure that it is at the same level as a flutter text.

Then, you can download that dependency using the command.

Copy-paste the whole code and paste it in main.dart file.

Let’s run the project.

You will see the data in data-table which itself is a scrollable.

The data is coming from the Rest API.

Each row is sending the total number of rows in count. Every API may send total row count in different key and at difference places or won’t send it at all so take a note to make sure it sends a total number of rows.

Lets begin a phase 2.

We already created a code to get total pages which will be shown at the bottom of an APP page.

Here, we will add another singlechildscrollview.

We will allow it to scroll horizontally.

Add a row as a child, advantage is that we can add multiple children in it which will be our pagination buttons.

The sizedbox is required, let me tell you why in a minute.

Let’s add a width in it.

Here you can see that the text ABC is appearing the right side of a screen.

We will do some mathematics to make it at the level of a data table.

Then I will be using a for loop.

Inside that will be our page buttons.

We will be using container with some specific width. This width will be dynamic, depending upon the length of a page number. I shall explain it in a minute.

For a button, we will be using a RaisedButton as a child.

Inside RaisedButton, we will temporarily add a 1 text.

OnPressed function is necessary.

Button appears.

We shall temporarily change the page count as 10 in for loop.

We will create a function called numberFunction which will be deciding the width of every button.

Let’s create that function which will return a double value.

Whenever the length of a page number changes, so will the float amount of that button.

Now the width looks OK.

Add i+1 as a text which will accurately display page number.

On pressed, we will change the current page number to highlight it.

Let’s make number’s color as white.

Because there are only 15 records, there are only 2 pages.

So let’s make 2 records per page.

We will add sizedBox at the end of container too to make some spacing from the right side.

To make some gap between buttons, we shall add margin as 10 from right side.

Set height property as 50.

To change content when clicked on button, call the loadDAtaFromAPI method on button’s onPressed function.

In pagination, there is always a feature will tells users the current page by highlighting it.

So let’s change the color of current page.

Because it is dynamic, we shall create another function called getColorForThis.

It will return a color by checking if that page number matches with current one.

There is some error.

So the return type should be MaterialColor.

Let’s run the project again.

You will see the pagination as expected. It is scrollable and go up to infinite.

There is a link in description called “Link 2 Code (Final Pagination)”. You can refer that if your code is not executing as expected.

Enjoy the code, play with it to create your own version.

Thanks for watching. Like, Share and Subscribe.

Saturday 7 October 2023

Flutter | Data-Table With Horizontal Scroll | Display Data From Rest API




1. Create a new project

-----------------------------

2. Add following line in dependencies (pubspec.yaml).

http: any

-----------------------------

3. Click on PUB GET button, or enter the command "flutter pub get" in terminal.

-----------------------------

4. Copy-paste the following code.


import 'package:flutter/material.dart';

import 'package:flutter/foundation.dart';

import 'package:http/http.dart' as http;

import 'dart:convert';

void main() {

  runApp(const showListingPage());

}

List? dataList;

int totalPages = 0;

String filterListingString = "";

class showListingPage extends StatelessWidget {

  const showListingPage({Key? key}) : super(key: key);

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'View All',

      routes: {

      },

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

      home: const ViewAllPage(title: 'View All'),

    );

  }

}

class ViewAllPage extends StatefulWidget {

  const ViewAllPage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override

  State<ViewAllPage> createState() => _ViewAllPageStateViewAll();

}

class _ViewAllPageStateViewAll extends State<ViewAllPage> {


  int total_records = 0;

  List _posts = [];

  int curr_page = 1;

  int count_per_page = 10;

  void loadDataFromAPI(int page_number,int per_page) async {

    try {

      final res =

      await http.get(Uri.parse("http://unpossiblepog.com/apis/getFlutterPaginationApi.php?page="+page_number.toString()+"&per_page="+per_page.toString()));

      setState(() {

        _posts = json.decode(res.body);

        if(_posts.length>0)

        {

          dataList = _posts;

          total_records = int.parse(_posts[0]['count']);

          totalPages =

              (total_records / count_per_page).ceil();

        }

      });

    } catch (err) {

      if (kDebugMode) {

        print('Something went wrong');

      }

    }

  }



  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('View All'),

        centerTitle: true,

        actions: <Widget>[],

      ),

      body: ListView(children: <Widget>[

        SingleChildScrollView(

          padding: const EdgeInsets.all(8.0),

          scrollDirection: Axis.horizontal,

          child: DataTableOutputViewAll(),

        ),

      ]), 

    );

  }

  @override

  void initState() {

    super.initState();

    dataList = null;

    totalPages = 0;

    if (dataList == null) {

      loadDataFromAPI(1,count_per_page);

    }

  }

  @override

  void dispose() {

    super.dispose();

  }


}

class DataTableOutputViewAll extends StatelessWidget {

  const DataTableOutputViewAll({Key? key}) : super(key: key);

  List<InlineSpan> getData(Map<String, String> amount_entry_details) {

    List<InlineSpan> temp = [];

    amount_entry_details.forEach((k, v) => {

      temp.add(

        TextSpan(

          style: const TextStyle(

            color: Colors.black,

          ),

          children: <TextSpan>[

            TextSpan(

                text: k + ' : ',

                style: const TextStyle(fontWeight: FontWeight.bold)),

            TextSpan(text: v + '\n'),

          ],

        ),

      ),

    });

    return temp;

  }

  @override

  Widget build(BuildContext context) {

    List<DataRow> rows = [];

    if (dataList != null) {

      for (int i = 0; i < dataList!.length; ++i) {

        rows.add(DataRow(

          cells: <DataCell>[

            DataCell(Text(

                '' + dataList![i]['language'].toString(),

                style: TextStyle(fontSize: 15)),onTap: (){

            }),

            DataCell(

                Text(

                    '' + dataList![i]['post_title'].toString(),

                    style: TextStyle(fontSize: 15)),onTap: (){

            }),

          ],

        ));

      }

    }

    return DataTable(

      columns: const <DataColumn>[

        DataColumn(

          label: Text(

            'Language',

            style: TextStyle(fontStyle: FontStyle.italic),

          ),

          numeric: false,

        ),

        DataColumn(

          label: Text(

            'Title',

            style: TextStyle(fontStyle: FontStyle.italic),

          ),

          numeric: false,

        ),

      ],

      rows: rows,

    );

  }

}


x

Thursday 27 July 2023

PHP Stock Contribution Logic | How To Split The Quantity In Sequence


 
PHP Contribution Logic | How To Split The Contribution In Sequence
-------------------------------

Code :

<?php
$friends = array("TONY STARK"=>500,"STEVE ROGERS"=>210,"NATASHA"=>290);
$foods = array("SHWARMA"=>450,"PIZZA"=>300,"BURGER"=>250);
echo "<pre>";print_r($friends);echo "</pre>";
echo "<pre>";print_r($foods);echo "</pre>";

while(sizeof($friends)>0)
{
$first_friend = array_key_first($friends);
$first_friend_amount = $friends[$first_friend];

//echo $first_friend." - ".$first_friend_amount;


$first_food = array_key_first($foods);
$first_food_amount = $foods[$first_food];

//echo $first_food." - ".$first_food_amount;
$final_amount = 0;
if($first_friend_amount<$first_food_amount)
{
$final_amount = $first_friend_amount;
}
else
{
$final_amount = $first_food_amount;
}

echo "<div>".$first_friend." - ".$first_food." - ".$final_amount."</div>";

$first_friend_amount = $first_friend_amount - $final_amount;
$friends[$first_friend] = $first_friend_amount;

$first_food_amount = $first_food_amount - $final_amount;
$foods[$first_food] = $first_food_amount;

if($friends[$first_friend]<=0)
{
unset($friends[$first_friend]);
}
if($foods[$first_food]<=0)
{
unset($foods[$first_food]);
}

//echo "<pre>";print_r($friends);echo "</pre>";
//echo "<pre>";print_r($foods);echo "</pre>";

//exit;
}
?>

-------------------------------

Copy The Code:-
Subscribe my Channel:-
http://www.youtube.com/user/SanketRooney?sub_confirmation=1
Facebook Page:-
https://www.facebook.com/UnpossibleNS
Twitter Account:-
https://twitter.com/UnpossiblePOG
Blog:-
https://unpossiblepog.blogspot.com/
Website:-
https://unpossiblepog.com/
Gaming Instagram:- (@unpog.gaming)
https://www.instagram.com/unpog.gaming/

========================
Hey guys, This is Unpossible POG.
Today I am going to demonstrate the contribution split logic using PHP language.
So suppose there are 2 arrays.
1st array represents people who contributes money for the food.
Their contribution’s total is 1000.
The 2nd array is the food’s amount in sequence.
So, the output we want is something like this.
Because TONY STARK spent 500, and Shawarma’s cost is 480, he actually paid full money for shwarama. And because of it 20 amount is left.
So it is adjusted to next food item which is PIZZA. Now PIZZA’s amount is reduced from 300 to 280.
Next is STEVE ROGERS, who spent all his money on PIZZA. And so on.
Here is the code.
We will be using a WHILE loop which is risky one if we don’t break it. So just add exit at the end which will be temporary.
Any ways, the logic is to find first elements from each array, in this case, a first person and first food.
I will be using some short-cuts to avoid typing.
Let’s print first elements.
We will create a variable which will hold the least amount of person or food. So let’s compare first amounts from both array.
Assign which one is the least to FINAL AMOUNT.
Let’s print.
Now, we have to deduct that FINAL AMOUNT from both array’s first amount.
And overwrite the first element’s amount from both arrays.
Let’s run to see the current situation.
SHWARMA’s amount is set to zero and TONY STARK’s amount is reduced down to 50.
If any PERSON AMOUNT or FOOD AMOUNT becomes zero after the subtraction, we will unset that element using UNSET function.
Now, arrays are overwritten.
Now we can remove exit from the bottom and see the result.
That’s it.
Code link is given in the description.
Thanks for watching. Like, Share and Subscribe.