问题描述
我正在尝试在 Appbar 中显示总文档的实时计数。我在我的控制台中得到了正确的信息,但是当我尝试通过提供者传递它时,它返回一个“未来”的实例。有人能告诉我为什么即使我等待结果并且结果在我的控制台中正确打印,我仍然得到一个 Instence 吗?
这是我获取 Future int 并将结果打印到我的控制台的地方。
class AuthenticationService extends ChangeNotifier {
Future<int> totalJumps(jumpDict) async {
var respectsQuery = _db.collection(jumpDict);
var querySnapshot = await respectsQuery.get();
var result = querySnapshot.docs.length;
print(result);
// notifyListeners();
return result;
}
}
class LazyListOnline extends StatefulWidget {
static const String id = 'Lazy_list_online';
@override
_LazyListOnlinestate createState() => _LazyListOnlinestate();
}
class _LazyListOnlinestate extends State<LazyListOnline> {
@override
Widget build(BuildContext context) {
String userDict = Provider.of<AuthenticationService>(context).findJumpDict;
var _firestoreDb =
FirebaseFirestore.instance.collection(userDict).snapshots();
var totalJump = Provider.of<AuthenticationService>(context)
.totalJumps(userDict)
.toString();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),onpressed: () {
Navigator.popAndPushNamed(context,HomeDrawer.id);
}),title: Text('totalJumps'),body: Stack(children: [
Padding(
padding: const EdgeInsets.all(18.0),child: Container(
decoration: Boxdecoration(),),StreamBuilder<QuerySnapshot>(
stream: _firestoreDb,builder: (context,snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return ListView.builder(
itemCount: snapshot.data.docs.length,itemBuilder: (context,int index) {
return JumpItem(
snapshot: snapshot.data,index: index,);
});
}),]),);
}
}
解决方法
我认为您只需要在 Provider 中以 int 形式存储文档数量即可。
class DocumentData extends ChangeNotifier {
int documentLength;
void setCurrentLengthOfDocuments(int length) {
this. documentLength = length;
notifyListeners();
}
}
然后在 StreamBuilder 中。每次更改数据。你只需要更新。重新升级到你的例子就像这样。
StreamBuilder<QuerySnapshot>(
stream: _firestoreDb,builder: (context,snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
// Update amount of documents length
Provider.of<DocumentData>(context,listen: false)
.setCurrentLengthOfDocuments(lengthOfCurrentDocuments);
return ListView.builder(
itemCount: snapshot.data.docs.length,itemBuilder: (context,int index) {
return JumpItem(
snapshot: snapshot.data,index: index,);
});
}),]),
然后,您只需使用 Consumer 小部件即可获取此页面上每个位置的文档长度。或者直接从 Provider 获取值。