Home > OS >  Flutter: I have two function for reading firebase data in my flutter app. now I want to sum two func
Flutter: I have two function for reading firebase data in my flutter app. now I want to sum two func

Time:06-14

I want to sum two different firebase collection field values in my flutter app. That's why I write two functions. I can sum one collection field value but two collection field value sum in a single text widget is not working or I am not understanding how to do this..

Scaffold(
  body: SafeArea(
      child: Container(
    child: StreamBuilder<double?>(
      stream: getFundData(),
      builder: (context, snapshort) {
        if (snapshort.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        }
        if (snapshort.hasData) {
          double data = snapshort.data!;
          return Center(child: Column(
            children: [
              Text("$data"),
              
            ],
          ));
        }

        return Text("data");
      },
    ),
  )),
);

function code

Stream<double> getFundData() async* {
  final result =
  await FirebaseFirestore.instance.collection('Use-of-fund').get();
  double totalFundAmount = 0;
  for (var doc in result.docs) {
    totalFundAmount  = doc['Amount'];
  }
  yield totalFundAmount;
}

Stream<double> getUserBalanceData() async* {
  final result = await FirebaseFirestore.instance.collection('User-data').get();
  double userTotalAmount = 0;
  for (var doc in result.docs) {
    userTotalAmount  = doc['Balance'];
  }
  yield userTotalAmount;
}

Now I want to sum userTotalAmount and totalFundAmount

CodePudding user response:

Use RxDart (Observable package). Specifically, use CombineLatestStream for both getFundData and getUserBalanceData. It is there that you sum the outputs when either streams emit.

// ...

StreamBuilder<double>(
  stream: CombineLatestStream.combine2(
    getFundData(),
    getUserBalanceData(),
    (double a, double b) => a   b,
  ),
  builder: (context, snapshot) {

// ...

Remember that you have to install the rxdart package in your project. Run the following command in a terminal inside your project folder:

flutter pub add rxdart

Then import it at the top of the Dart file

import 'package:rxdart/rxdart.dart';

Explanation

So the problem is you want to be capable of summing the results from two different streams. Mainly because StreamBuilder takes only one Stream at a time. CombineLatestStream above from the rxdart package permits you to do this. The rxdart package provides easy ways to Observables in a reactive programming style. In this case, the streams are all from Firebase. And even if they weren't, you will still do something similar.

  • Related