Firestore数据获取类型不匹配异常及Bloc Sink数据添加求助
Let's break down your issues one by one and fix them step by step:
1. Fixing Unhandled Exception: type 'Future<void>' is not a subtype of type 'Future<Photography>'
The root problem here is that you're using setData()—a method for writing data to Firestore that returns Future<void>—but your function is declared to return Future<Photography>. Since your goal is to fetch data (not write it), you need to use Firestore's get() method to retrieve the document snapshot, then convert it to your Photography model.
Here's the corrected function:
Future<Photography> getPhotography() async { // Fetch the document snapshot from Firestore DocumentSnapshot snapshot = await db .collection('photography') .document('0yUc5QBGHNNq6WK9CyyF') .get(); // Convert snapshot data to your Photography model if (snapshot.exists) { return Photography.fromJson(snapshot.data as Map<String, dynamic>); } else { // Handle the case where the document doesn't exist throw Exception("Photography document not found in Firestore"); } }
Key changes:
- Added
asyncto the function (required when usingawait) - Replaced
setData()withget()to fetch data instead of writing it - Used your existing
Photography.fromJson()method to parse the snapshot data into a model object
If you actually wanted to write data first then fetch it, here's how to do that properly (without redundant jsonDecode(jsonEncode(...))):
Future<Photography> setAndGetPhotography() async { // Write data to Firestore await db .collection('photography') .document('0yUc5QBGHNNq6WK9CyyF') .setData(Photography( [AllImages(["list"])], "image_url", "Shanika", "image_url", "lovely couple", "Bhanuka" ).toJson()); // Fetch the newly written data DocumentSnapshot snapshot = await db .collection('photography') .document('0yUc5QBGHNNq6WK9CyyF') .get(); if (snapshot.exists) { return Photography.fromJson(snapshot.data as Map<String, dynamic>); } else { throw Exception("Document not found after writing to Firestore"); } }
2. Fixing The argument type 'Future' can't be assigned to the parameter type 'Photography'
Your getPhotography() function returns a Future<Photography>—this means it's an asynchronous operation that will eventually give you a Photography object. You can't pass the Future directly to your Bloc Sink; you need to wait for it to complete and get the actual Photography instance first.
There are two clean ways to do this:
Option 1: Use async/await (recommended for readability)
Make sure this code runs inside an async function:
// Inside an async function final Photography result = await db.getPhotography(); inFirestore.add(result);
Option 2: Use then() for chaining
If you can't use async/await in the current context:
db.getPhotography().then((Photography result) { inFirestore.add(result); }).catchError((error) { // Handle any errors that occur while fetching data print("Failed to fetch photography data: $error"); });
内容的提问来源于stack exchange,提问作者user9139407

