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

No comments:

Post a Comment