这就是我正在尝试构建的 这是代码
class LogisticsPageScreen extends StatefulWidget {
@override
_LogisticsPageScreenState createState() => _LogisticsPageScreenState();
}
class _LogisticsPageScreenState extends State<LogisticsPageScreen> {
List<LogisticsData> logisticsData = [];
@override
void initState() {
super.initState();
fetchLogisticsData();
}
Future<void> fetchLogisticsData() async {
try {
QuerySnapshot querySnapshot =
await FirebaseFirestore.instance.collection('allocations').get();
List<LogisticsData> tempData = querySnapshot.docs.map((doc) {
print("Document data: ${doc.data()}"); // Debug log for document data
return LogisticsData(
eventName: doc['event'] ?? 'N/A',
driver: doc['driver'] ?? 'N/A',
guide: doc['guide'] ?? 'N/A',
);
}).toList();
setState(() {
logisticsData = tempData;
// Print the fetched logistics data
print("Fetched logistics data: $logisticsData");
});
print(
"Logistics data loaded successfully"); // Debug log for successful data load
} catch (e) {
// Handle any errors that might occur
print("Error fetching logistics data: $e"); // Debug log for error
}
}
@override
Widget build(BuildContext context) {
return LogisticsPage(logisticsData: logisticsData);
}
}
我尝试使用 future builder 来实现另一种将数据传递到 UI 的方法,但它并不有效。 什么问题可能会阻止数据传递到 UI。 从控制台可以看到数据,但在 UI 上却没有显示。
当 LogisticsPageScreen 小部件最初构建时,物流数据为空。此时在initState中触发fetchLogisticsData函数,异步从Firestore中获取数据。但是,由于 fetchLogisticsData 是异步的,因此它不会阻止最初在 LogisticsData 为空的情况下构建小部件。
要处理这种情况,您应该确保在 LogisticsData 使用 Firestore 中的数据填充后 UI 会更新。您已在 fetchLogisticsData 中使用的 setState 方法会在 LogisticsData 更改时触发小部件的重建。以下是如何构建小部件以正确处理异步数据获取:
class LogisticsPageScreen extends StatefulWidget {
const LogisticsPageScreen({super.key});
@override
State<LogisticsPageScreen> createState() => _LogisticsPageScreenState();
}
class _LogisticsPageScreenState extends State<LogisticsPageScreen> {
Future<List<LogisticsData>> futureLogisticsData;
@override
void initState() {
super.initState();
futureLogisticsData = fetchLogisticsData();
}
Future<List<LogisticsData>> fetchLogisticsData() async {
try {
QuerySnapshot querySnapshot =
await FirebaseFirestore.instance.collection('allocations').get();
List<LogisticsData> tempData = querySnapshot.docs.map((doc) {
return LogisticsData(
eventName: doc['event'] ?? 'N/A',
driver: doc['driver'] ?? 'N/A',
guide: doc['guide'] ?? 'N/A',
);
}).toList();
return tempData;
} catch (e) {
return [];
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<LogisticsData>>(
future: futureLogisticsData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data.isEmpty) {
return Center(child: Text('No data available'));
} else {
return LogisticsPage(logisticsData: snapshot.data);
}
},
);
}
}