【发布时间】:2019-03-26 01:35:55
【问题描述】:
我正在使用 StreamBuilder 小部件来显示一些数据。最近打开应用程序时,我想显示我的 json 文件中的一些初始数据并将其提供给 StreamBuilder 的 initialData 可选关键字参数。
这是我喂它的方法:
MyStorage m = new MyStorage(); // Using path_provider, I accessed the json file inside this class
int x;
@override
void initState(){
super.initState();
getData();
}
getData() async{
Map<String, dynamic> myMap = await m._getMap;
x = int.parse(myMap["total"]);
}
...
@override
Widget build(BuildContext context){
...
child: StreamBuilder(
stream: mystream, // coming from my BLoC class
initialData: x,
builder: (context, snapshot){
return new Text("${snapshot.data}");
}
...
问题在于我的 StreamBuilder 中的 Text 小部件显示为“null”。
我试图将我的代码重写为:
MyStorage m = new MyStorage();
Future<int> getData() async{
Map<String, dynamic> myMap = await m._getMap;
return int.parse(myMap["total"]);
}
...
@override
Widget build(BuildContext context){
...
child: StreamBuilder(
stream: mystream, // coming from my BLoC class
initialData: getData(),
builder: (context, snapshot){
return new Text("${snapshot.data}");
}
...
但它在我的文本小部件上显示为“Future 实例:int”
我在 StreamBuilder 中的流参数没有问题。它显示了我对 BLoC 类的期望的正确值。
我遇到的唯一问题是从我的 json 文件中输入 initialData。
我做错了什么?我将不胜感激任何帮助。谢谢
[更新]
经过长时间思考解决方案后,我放弃了使用 initialData 参数,因为在我将 int 添加到 StreamBuilder 之后,就像这样 StreamBuilder<int>() 它提示我它只会采用整数值。我不能用 Future 或 Stream 来喂它,所以我决定不使用它。我所做的是通过 ConnectionState 在 StreamBuilder 中嵌套了一个 FutureBuilder。
这是我现在的代码:
MyStorage m = new MyStorage();
Future<int> getData() async{
Map<String, dynamic> myMap = await m._getMap;
return int.parse(myMap["total"]);
}
...
@override
Widget build(BuildContext context){
...
child: StreamBuilder<int>(
stream: mystream, // coming from my BLoC class
//initialData: getData(),
builder: (context, snapshot){
swith(snapshot.connectionState){
case ConnectionState.none:
return new FutureBuilder(
future: getData(),
builder: (context, snapshot){
return new Text('${snapshot.data}');
}
);
case ConnectionState.active:
case ConnectionState.waiting:
return new FutureBuilder(
future: getData(),
builder: (context, snapshot){
return new Text('${snapshot.data}');
}
);
case ConnectionState.done:
if (snapshot.hasData){
return new Text('${snapshot.data}');
}
return new FutureBuilder(
future: getData(),
builder: (context, snapshot){
return new Text('${snapshot.data}');
}
);
}
}
...
我知道这个解决方案效率很低,但目前我想不出更好的解决方案。
【问题讨论】: