【发布时间】:2022-11-03 13:15:10
【问题描述】:
我正在尝试从 Firebase 实时数据库中读取数据并在条形图中使用它。
我的代码首先从数据库中读取数据(特别是项目名称),然后将它们存储在列表中(项目名称)。这一切都在 activateListeners() 方法中完成。
从这一点开始,我在 generateData() 方法中调用了 activateListners() 方法,以便开始将 itemNames 列表中的数据用于条形图。由于 activateListeners() 方法是异步的,我使用“await”关键字来确保在继续之前将项目名称存储在列表中。
在此之后,我计划使用数据库中每个项目的名称以及数量创建 Product Sales 对象。这将通过从项目名称列表中获取项目名称来完成。
但是,在我这样做之前,我正在测试条形图是否可以正常处理测试数据。
问题是当我运行代码时,条形图不显示,因为它似乎没有读取数据。但是,如果我从 generateData() 方法中删除“await activateListners()”,条形图会完美地显示测试数据。
为什么当我等待 activateListeners() 方法首先执行时,ber 图表不显示数据?
任何帮助将非常感激!
class _ProductBarChartState extends State<ProductBarChart> {
//Ref to DB
final DatabaseReference _dbRef = FirebaseDatabase.instance.ref();
late DataSnapshot _itemStream;
//Stores the description of each menu item in the DB
String itemName = "";
String itemID = "";
List<String> itemNames = [];
List<String> itemIDs = [];
//Reads the item names from the DB and adds them to a list
Future _activateListeners() async {
for (int i = 1; i <= 10; i++) {
itemID = "J$i";
_itemStream = await _dbRef.child("menuItem/$itemID/itemName").get();
itemName = _itemStream.value.toString();
itemNames.addAll([itemName]);
}
}
List<charts.Series<ProductSales, String>> _seriesBarData =
[]; //A list that will store all the sales data for the bar chart report
_generateData() async {
await _activateListeners();
var BarChartData = [
//Stores all ProductSales objects for the product report
ProductSales("Hake", 8),
ProductSales("Toasted", 15),
ProductSales("Chick strips", 28),
ProductSales("Kota", 40),
];
//Adding the BarChartData (seen above) to the list
_seriesBarData.add(charts.Series(
id: 'SalesPerProduct',
colorFn: (_, __) =>
charts.ColorUtil.fromDartColor(Color.fromARGB(255, 255, 157, 38)),
domainFn: (ProductSales productSales, _) => productSales.productName,
measureFn: (ProductSales productSales, _) => productSales.noOfProductSold,
data: BarChartData,
));
}
@override
void initState() {
// TODO: implement initState
super
.initState(); //This runs the original initState function that we inherited from the material app class (even though we override i)
_seriesBarData = <charts.Series<ProductSales, String>>[];
_generateData(); //Generates all the data for the chart (method specified above)
}
【问题讨论】:
-
1. 声明返回类型。
_generateData是异步的,应声明为返回Future。 2. 启用unawaited_futureslint。 3. 为什么不用FutureBuilder?initState无法等待异步函数完成。当您的Future完成时,您必须使用FutureBuilder(或等效的东西)来重建小部件树。 -
我现在看到我必须在构建方法中添加一个未来的构建器。现在可以了。太感谢了!!
标签: flutter firebase dart google-cloud-firestore