【发布时间】:2020-07-21 04:39:19
【问题描述】:
我的 BLoC 实现有问题,我在 synchronize.dart 中有这段代码:
...
class _SynchronizeState extends State<Synchronize> {
UserBloc userBloc;
//final dbRef = FirebaseDatabase.instance.reference();
@override
Widget build(BuildContext context) {
userBloc = BlocProvider.of(context);
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Container(
...
),
child: StreamBuilder(
stream: dbRef.child('info_tekax').limitToLast(10).onValue,
builder: (context, snapshot) {
if(snapshot.hasData && !snapshot.hasError){
Map data = snapshot.data.snapshot.value;
List keys = [];
data.forEach( (index, data) => keys.add(index) );
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) => SynchronizeItem(title: keys[index], bottom: 10, onPressed: (){ print(keys[index]); })
);
}else{
return Container(
child: Center(
child: Text('Loading...'),
),
);
}
}
),
),
);
}
}
previos 代码,工作正常,但我想实现 bloc 模式,我有 userBloc 然后我想把这个
userBloc.getDevicesForSinchronized()
代替
dbRef.child('info_tekax').limitToLast(10).onValue,
我的问题是这样的:
void getDevicesForSynchronized() {
return dbRef.child(DEVICES).limitToLast(10).onValue;
}
我收到此错误**无法从方法“getDevicesForSynchronized”返回“Stream”类型的值,因为它的返回类型为“void”
错误很清楚,但是不知道需要返回什么类型,试试:
Furure<void> getDevicesForSynchronized() async {
return await dbRef.child(DEVICES).limitToLast(10).onValue;
}
或
Furure<void> getDevicesForSynchronized() async {
dynamic result = await dbRef.child(DEVICES).limitToLast(10).onValue;
}
还有另一种解决方案,但我不知道如何正确返回值以在 StreamBuilder 中使用
【问题讨论】:
标签: flutter firebase-realtime-database bloc