如何实现FutureBuilder dart, flutter

How to implement FutureBuilder dart, flutter

我有这个静态函数,它 returns 来自我的数据库 (firebasefirestore) 的 Future。现在我需要它是一个 double,因为我必须为使用过的 Widget 提供一个 double。我发现 FutureBuilder 是一种可行的 Class 用于这种情况,我只是不确定如何在我的代码中正确实现它。请参阅下面的代码:

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),
                ],
              ),
            ),
          ],
        ),
      );
    }
  }

双人需要提供给FlSpot。我使用静态函数 spotData(day, queryDocumentSnapshot) 这样做 - 唯一的问题是:我返回的是 Future 而不是 double...

非常感谢您的帮助!


您可以执行如下操作:

  • initState()
  • 中初始化 futureDouble
  • 在里面使用FutureBuilder
  • 值是从snapshot.data!中获取的(这里是double,因为定义了FutureBuilder<double>,但是你可以为任何对象定义它)。
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(...
    );
  }
}

你也可以有一个双精度列表,例如

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

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

其中 snapshot.data! 将是 List<double>


要获得 return 值列表的方法,您可以使用类似的方法:

  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;
  }