How can I get Api data in Streambuilder - Flutter

Viewed 658

I have an API, I want to show this API live. When the user removes any data delete live and also add any data from the backend I want to show it live.

Now how can I achieve it in flutter?

I am using Getx(Obx not working) , ListView.builder, and Dio package.

My Page.dart

import 'package:clipboard/clipboard.dart';
import 'package:dio/dio.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'package:isp_app/src/configs/appColors.dart';
import 'package:isp_app/src/configs/appConfigs.dart';
import 'package:isp_app/src/controllers/baseController.dart';
import 'package:isp_app/src/widgets/customButton.dart';
import 'package:isp_app/src/widgets/customRawText.dart';

import 'package:isp_app/src/widgets/kText.dart';
import 'package:shared_preferences/shared_preferences.dart';

class NewCollectionTab extends StatefulWidget with BaseController {
  @override
  State<NewCollectionTab> createState() => _NewCollectionTabState();
}

class _NewCollectionTabState extends State<NewCollectionTab>
    with BaseController {
  final keyRefresh = GlobalKey<RefreshIndicatorState>();

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 20),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 20),
          child: KText(
            text: 'Main',
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.black,
          ),
        ),
        SizedBox(height: 10),
        Obx( ()=>
            ListView.builder(
            shrinkWrap: true,
            primary: false,
            physics: BouncingScrollPhysics(),
            itemCount: connectionDataC.connection.length,
            itemBuilder: (context, index) {
              final item = connectionDataC.connection[index];
        
              return item.connectionStatus == true
                  ? Container()
                  : InkWell( child: Padding(
                        padding: EdgeInsets.only(bottom: 10),
                        child: ListTile(
                          leading: CircleAvatar(
                            radius: 30,
                            backgroundColor: black12,
                            backgroundImage: NetworkImage(
                              item.catImg.toString(),
                            ),
                          ),
                          title: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  KText(
                                    text: item.userName.toString(),
                                    fontSize: 16,
                                    maxLines: 2,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ],
                              ),
                              SizedBox(height: 5),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Icon(
                                    Icons.date_range,
                                    size: 12,
                                    color: black12,
                                  ),
                                  SizedBox(width: 5),
                                  KText(
                                    text: DateFormat('dd-MM-yyyy').format(
                                      DateTime.parse(
                                        item.confrmDate.toString(),
                                      ),
                                    ),
                                    fontSize: 12,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ],
                              ),
                              SizedBox(height: 5),
                            ],
                          ),
                          subtitle: KText(
                            text: item.description.toString(),
                            fontSize: 13,
                            color: black54,
                            maxLines: 3,
                            textAlign: TextAlign.justify,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                    );
            },
          ),
        ),
      ],
    );
  }
}

My Controller.dart

import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:isp_app/src/configs/appConfigs.dart';
import 'package:isp_app/src/models/connections.dart';

import 'package:shared_preferences/shared_preferences.dart';

class ConnectionController extends GetxController {
  // ignore: unused_field
  final _dio = Dio();
  // final RxList<dynamic> connectionList = RxList();

  final connection = RxList<Connection>();
 
  getconnectionList() async {
    print('++++++++++++++++++++++++++++++++++');

    try {
      final sharedPreferences = await SharedPreferences.getInstance();
      final token = sharedPreferences.get('accessToken');
      final userName = sharedPreferences.get('loginUserName');
      final res = await _dio.get(
        '$baseUrl/new_connection/?search=$userName',
        options: Options(
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": 'Token $token'
          },
        ),
      );

      print(res.statusCode);
      print(res.headers);
      // print(res.body);
      // print(res.unauthorized);
      print(res.realUri);
      print(res.statusMessage);
      print(res.data);
      print(res.realUri);
      print(res.requestOptions);

      print('++++++++++++++++++++++++++++++++++');

      if (res.statusCode == 200) {
  if (res.statusCode! >= 200 && res.statusCode! < 300) {
    connection.addAll(
        (res.data as List).map((e) => Connection.fromJson(e)).toList());
  }
      }
    } catch (e) {
      print(e);
    }
  }
}

My Api Data demo :

[
  {
    "id": 1,
    "confrm_date": "2022-01-17T07:14:06",
    "User_name": "গণপরিবহনে অঘোষিত নিয়ম",
    "Phone_Number": "0185455545",
    "Description": "পরিবহন খাতের সঙ্গে মো. রুবেল হোসেন যুক্ত সেই ১৯৯৭ সাল থেকে। শুরু থেকেই তিনি ‘পুলিশ পাস’-এর কথা শুনে আসছেন। আদৌ এ নিয়ে কোনো আইন বা নিয়ম আছে কি না, তা জানেন না তিনি। তাঁর মতো অনেক পরিবহনমালিক ও শ্রমিকের একই অবস্থা।\r\n\r\nএত দিন শিক্ষার্থীদের জন্য বাসে অর্ধেক ভাড়ার (হাফ পাস) কথা শোনা গেলেও গণপরিবহনে ভাড়াসংক্রান্ত আরেকটি বিষয় প্রচলিত আছে। সেটিই হলো ওই ‘পুলিশ পাস’। এ ক্ষেত্রে অর্ধেক ভাড়া নয়, কোনো ভাড়াই দিচ্ছেন না অনেক পুলিশ সদস্য।",
    "Connection_status": false,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 2,
    "confrm_date": "2022-01-17T07:14:06",
    "User_name": "অবৈধ রসিদে টোল",
    "Phone_Number": "0185455545",
    "Description": "অবৈধ রসিদ তৈরি করে রাজধানীর যাত্রাবাড়ীর মেয়র হানিফ উড়ালসড়ক থেকে টোল আদায় করার অভিযোগ উঠেছে সংঘবদ্ধ একটি চক্রের বিরুদ্ধে। বিভিন্ন যানবাহনের চালকদের ভয় দেখিয়ে টোলের নামে চাঁদা আদায় করছিল চক্রটি। না দিলে প্রাণনাশের হুমকি দিচ্ছিল তারা।",
    "Connection_status": false,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 3,
    "confrm_date": "2022-01-17T07:14:06",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "নরমাল ডেলিভারি হসপিটাল",
    "Connection_status": false,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 4,
    "confrm_date": "2022-01-17T07:14:06",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "কাশেম মঞ্জিল, তানযীমুল উম্মাহ হিফয মাদ্রাসা।",
    "Connection_status": false,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 5,
    "confrm_date": "2022-01-17T10:42:57",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "হাউজিং মারকাজ মসজিদের পিছনে - nstu teacher 2300 tk router +\r\nline charge 1000+ 360",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 6,
    "confrm_date": "2022-01-17T10:43:04",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "মাষ্টার পাড়া - হালিমা ভিলা ৩ তলায়",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 7,
    "confrm_date": "2022-01-17T10:44:25",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "মিঠুর কানেকশন আছে এখন , ১ তারিখ নিবে।",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 8,
    "confrm_date": "2022-01-17T10:44:49",
    "User_name": "User",
    "Phone_Number": "0185455545",
    "Description": "এতিম খানার পিছনে।",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 10,
    "confrm_date": "2022-01-20T07:09:03",
    "User_name": "User123",
    "Phone_Number": "0185455545",
    "Description": "54155",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  },
  {
    "id": 11,
    "confrm_date": "2022-01-20T07:09:48",
    "User_name": "12345",
    "Phone_Number": "0185455545",
    "Description": "546",
    "Connection_status": true,
    "cat_img": "http://103.137.75.74:82/media/cat_img/LOGO-01.png",
    "Connection_by": 1
  }
]
1 Answers

Thing is that APIs do not send you "updates" so the client in this case your application does not receive updates when the server, this would require another mechanism like a socket, in which you connect to a server, and listen for active updates, In terms of a normal web api it works as request vs response, the server only responds to a request, so if you want to have a behavior that simulates a "real time" you will need to code a timer, which makes the request every 5 seconds for example, in that case, you will try to fetch new information every certain amount of time. Make sense?

Related