【问题标题】:How do I map Stream<List<double>> to List<double> in Dart Flutter如何在 Dart Flutter 中将 Stream<List<double>> 映射到 List<double>
【发布时间】:2021-12-21 00:35:36
【问题描述】:

我们正在尝试将 Stream 转换为 Dart Flutter 中的 List。

List<double> _DeadliftWeightsList(QuerySnapshot snapshot){
List <Weights?> weights = snapshot.docs.map((doc){
  Weights(
      date: doc.get('date') ?? DateTime.now(),
      weight: doc.get('deadLiftWeight') ?? 0);
}).toList();
final List<double> normalized = NormalizedData(weights);
return normalized;}



List<double> DLWeights() {
List <double> weights = [];
usersCollection.snapshots()
    .map(_DeadliftWeightsList).listen((List<double> weights1) {
  weights = weights1;
});
return weights;}

这是我们的返回列表函数

 List<double> returnList (String key){
List<double> values = [];
if(key == "Dead Lift"){
  values = DLWeights();
}
else if (key == "Back Squat"){
  values = BSWeights();
}
else if (key == "Hip Thrust") {
  values = HTWeights();
}
else if (key == "Leg Press") {
  values = LPWeights();
}
else if (key == "Bench Press") {
  values = BPWeights();
}
else if (key == "Lateral Pulldown ") {
  values = LateralPDWeights();
}
else if (key == "Bicep Curl") {
  values = BCWeights();
}
else if (key == "Tricep Extension") {
  values = TEWeights();
}


return values;


}

这些函数旨在从 Stream 中获取数据并返回一个列表。然而,它并没有抓取数据,而是给我们一个糟糕的状态错误。

【问题讨论】:

    标签: database flutter dart google-cloud-firestore


    【解决方案1】:

    下面是一个简短的示例,说明如何将 Stream&lt;List&lt;double&gt;&gt; 转换为 List&lt;double&gt;

    Stream<List<double>> listOfDoubleStream() async* {
      for (int i = 1; i <= 100; i++) {
        yield [i.toDouble()];
      }
    }
    
    Future<void> main() async {
      List<double> result = await listOfDoubleStream().expand((e) => e).toList();
      print(result);
    }
    

    expand 方法在某些其他语言中等效于flatMap。调用 expand 可以将Stream&lt;List&lt;double&gt;&gt; 转换为Stream&lt;double&gt;,然后调用toList 将得到List&lt;double&gt;

    另一种方法是使用 collection-for 和扩展运算符 ...

    List<double> result = [
      await for (final item in listOfDoubleStream()) ...item,
    ];
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      相关资源
      最近更新 更多