【发布时间】:2019-10-09 08:38:18
【问题描述】:
我正在尝试从数据库中获取数据并使用流将该数据传输到屏幕。
我使用FutureBuilder 完成此操作,该解决方案按预期工作,但我需要使用streambuilder
谁能帮我找到问题。
我有一个从数据库中获取数据的方法
Future<List<CementSandAggregateView>> getAllRatios() async{
List<CementSandAggregateView> ratioList = new List();
var types = await ratioRepository.getAll();
for(int i = 0 ; i < types.length ; i ++){
CementSandAggregateView view = new CementSandAggregateView();
String cementRatio = types[i].cement.floor() < types[i].cement ? types[i].cement.toStringAsFixed(1):types[i].cement.toStringAsFixed(0);
String sandRatio = types[i].sand.floor() < types[i].sand ? types[i].sand.toStringAsFixed(1):types[i].sand.toStringAsFixed(0);
String aggregateRatio = types[i].aggregate.floor() < types[i].aggregate ? types[i].aggregate.toStringAsFixed(1):types[i].aggregate.toStringAsFixed(0);
view.ratio = "$cementRatio:$sandRatio:$aggregateRatio (${types[i].name})";
view.id = types[i].id;
view.name = types[i].name;
print(view.ratio);
ratioList.add(view);
}
return ratioList;
}
我想使用流发送这些数据
class CementSandAggregateMixBloC {
BehaviorSubject<Future<List<CementSandAggregateView>>> _cSAMixController;
BLoCProvider provider;
CementSandAggregateMixBloC(){
provider = new BLoCProvider();
_cSAMixController = new BehaviorSubject<Future<List<CementSandAggregateView>>>();
_cSAMixController.add(provider.getAllRatios());
}
Observable<Future<List<CementSandAggregateView>>> inputObservable() => _cSAMixController.stream;
void dispose() {
_cSAMixController.close();
}
}
在我的屏幕中,我使用 streambuilder 的流
Widget _buildBottomNavigationBar1() {
List<BottomNavigationBarItem> items = List();
return StreamBuilder(
stream: _rationBloC.inputObservable(),
builder: (context,
AsyncSnapshot<Future<List<CementSandAggregateView>>> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
snapshot.data.then((onValue) => {
onValue.forEach((mix) => {})
});
return BottomNavigationBar(
items: items,
currentIndex: _selectedRatio,
fixedColor: Theme.of(context).buttonColor,
onTap: _onItemTapped);
} else {
return new Center(
child: new CircularProgressIndicator(),
);
}
} else {
return new Container(width: 0.0,height: 0.0,);
}
},
);
}
但是数据没有出现在屏幕上
我试过这个solution 但没有机会!
谁能帮我将未来的结果转换成流?
谢谢。
【问题讨论】:
-
你需要
BehaviorSubject<List<CementSandAggregateView>>,而不是BehaviorSubject<Future<List<CementSandAggregateView>>>- 这同样适用于你的Stream -
好的。如果我使用
BehaviorSubject<List<CementSandAggregateView>>而不是BehaviorSubject<Future<List<CementSandAggregateView>>>,则应该更改提供者的返回类型,不是吗? -
不是真的:阅读this - 第二段说如何处理它:
"Asynchronous operations let your program complete other work while waiting for an operation to finish. Dart uses Future objects (futures) to represent the results of asynchronous operations. To work with futures, you can use either async and await or the Future API." -
链接失效了,谢谢你的信息。当内容可用时我会检查它。
-
它正在工作:我在一秒钟前仔细检查了它
标签: dart flutter stream future