Home > Software engineering >  How to implement FutureBuilder dart, flutter
How to implement FutureBuilder dart, flutter

Time:04-21

I have this static function which returns a Future from my database (firebasefirestore). Now I need that to be a double because I have to provide a double to the used Widget. I found FutureBuilder to be a viable Class to use for this kind of scenario, I'm just not sure how to properly implement it in my code. See code below:

class SomellierChart extends StatefulWidget {
  SomellierChart(
      {Key? key,
      required this.color,
      required this.textColor,
      required this.queryDocumentSnapshot})
      : super(key: key);
  Color textColor;
  Color color;
  List<QueryDocumentSnapshot> queryDocumentSnapshot;
  @override
  _SomellierChartState createState() => _SomellierChartState();
}

class _SomellierChartState extends State<SomellierChart> {
  static Future<double> spotData(String day, queryDocumentSnapshot) async {
    final documentSnapshot = await FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid.toString())
        .collection('activity')
        .doc('${globals.year}')
        .collection('week${globals.week}')
        .doc(day.toString())
        .get();

    if (documentSnapshot.exists) {
      print('Document exists');
      return documentSnapshot['usage'].toDouble();
    } else {
      print('Document doesnt exist');
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return LineChart(
        LineChartData(
          gridData: FlGridData(
            show: false,
          ),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: SideTitles(showTitles: false),
            topTitles: SideTitles(showTitles: false),
            leftTitles: SideTitles(showTitles: false),
            bottomTitles: SideTitles(
              showTitles: true,
              reservedSize: 20,
              interval: 1,
              getTextStyles: (context, value) => GoogleFonts.poppins(
                textStyle: TextStyle(
                  color: Theme.of(context).indicatorColor,
                  fontWeight: FontWeight.w600,
                  fontSize: 12,
                ),
              ),
              getTitles: (value) {
                switch (value.toInt()) {
                  case 0:
                    return 'Mon';
                  case 2:
                    return 'Tue';
                  case 4:
                    return 'Wed';
                  case 6:
                    return 'Thu';
                  case 8:
                    return 'Fri';
                  case 10:
                    return 'Sat';
                  case 12:
                    return 'Sun';
                }
                return '';
              },
              margin: 5,
            ),
          ),
          borderData: FlBorderData(show: false),
          minX: 0,
          maxX: 12,
          minY: 0,
          maxY: 3,
          lineBarsData: [
            LineChartBarData(
              spots: [
                FlSpot(0, spotData('1', widget.queryDocumentSnapshot)),
                FlSpot(2, spotData('2', widget.queryDocumentSnapshot)),
                FlSpot(4, spotData('3', widget.queryDocumentSnapshot)),
                FlSpot(6, spotData('4', widget.queryDocumentSnapshot)),
                FlSpot(8, spotData('5', widget.queryDocumentSnapshot)),
                FlSpot(10, spotData('6', widget.queryDocumentSnapshot)),
                FlSpot(12, spotData('7', widget.queryDocumentSnapshot)),
              ],
              isCurved: true,
              curveSmoothness: 0.5,
              preventCurveOverShooting: true,
              colors: [widget.textColor],
              barWidth: 3,
              isStrokeCapRound: true,
              dotData: FlDotData(
                show: false,
              ),
              belowBarData: BarAreaData(
                show: true,
                colors: [
                  widget.color.withOpacity(0.4),
                ],
              ),
            ),
          ],
        ),
      );
    }
  }

The double needs to be provided to the FlSpot. Im doing that using the static function spotData(day, queryDocumentSnapshot) - only problem: I'm returning a Future and not a double...

Thank's a lot for your help!


What its supposed to look like

What it looks like

CodePudding user response:

You can do something like the below:

  • Initialize futureDouble in initState()
  • Use it inside FutureBuilder
  • The value is obtained from snapshot.data! (which is double is this case, because FutureBuilder<double> was defined, but you can define it for any object).
class _SomellierChartState extends State<SomellierChart> {
  late Future<double> futureDouble;
  
  Future<double> spotData(String day, queryDocumentSnapshot) async {
    ...
  }

  @override
  void initState() {
    super.initState();
    futureDouble = spotData('', null);
  }


  @override
  Widget build(BuildContext context) {
    return FutureBuilder<double>(
        future: futureDouble,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return _lineChart(snapshot.data!);
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return const CircularProgressIndicator();
        });
  }

  Widget _lineChart(double value) {
    return LineChart(...
    );
  }
}

You can also have a List of double, e.g.

late Future<List<double>> futureDouble;
Future<List<double>> spotData(String day, queryDocumentSnapshot) async {
  ...
}

and

return FutureBuilder<List<double>>(...)

in which snapshot.data! would be List<double>.


To have a method to return a list of values, you can have something like:

  Future<List<double>> values() async {
    var list = <double>[];
    list.add(await value());
    list.add(await value());
    list.add(await value());
    list.add(await value());
    list.add(await value());
    list.add(await value());
    return list;
  }

  Future<double> value() async {
    return 1;
  }
  • Related