-1

I am using stream builder for fetching api in my app, what I am trying to achieve is to get notification or print message in the console every time the stream gives a new entry. I have heard there are packages for notifications but I don't know where exactly to write function that notifies me about new entry. the below is my code. please help.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';


void main() async {
runApp(MaterialApp(home: PeriodicRequester(),));
}



class PeriodicRequester extends StatelessWidget {
Stream<http.Response> getRandomNumberFact() async* {
yield* Stream.periodic(Duration(seconds: 5), (_) {
  return http.get(Uri.parse("https://script.google.com/macros/s/AKfycbwhbpF4ZxuMUcTZZvObAqvE1pAbEfPt7gZHRV1vVp8PuKt39-ouOm-kQJ1U1LtlEwV-/exec"));
}).asyncMap((event) async => await event);
}

@override
Widget build(BuildContext context) {
return StreamBuilder<http.Response>(
  stream: getRandomNumberFact(),
  builder: (context, snapshot) => snapshot.hasData
      ? Center(child: Text(snapshot.data!.body))
      : CircularProgressIndicator(),
);
}
}

1 Answers1

0

It depends on the data you are recieving. A stream builder may rebuild on multiple occasions including on network state change. so you can't add it directly to the build method. For example if its returning a list of items, then you can create a variable and update this variable with the length of the response. for example if the length is 5 in the first response. Update the variable to 5 and on next instance from stream you may get a 6 then check if the existing value is lesser than the current length. Then perform your custom action here (print or notification) and update the length.

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • bro i'm totally new to flutter but i really need to complete this project someway. Can you please tell me where should i keep that variable and how do i update it,,plzzzz @Kaushik Chandru – MOBILES RECOVERY Jul 24 '22 at 16:18