我正在使用 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}");
}
...
Run Code Online (Sandbox Code Playgroud)
问题是我的 StreamBuilder 中的文本小部件显示“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}");
}
...
Run Code Online (Sandbox Code Playgroud)
但它在我的文本小部件上显示为“未来实例:int”
我在 StreamBuilder 中的流参数没有问题。它显示了我期望从 BLoC 类获得的正确值。
我遇到的唯一问题是从我的 json 文件提供初始数据。
我究竟做错了什么?我将不胜感激任何形式的帮助。谢谢
[更新]
经过长时间的思考解决方案后,我放弃了使用initialData参数,因为在我添加到int这样StreamBuilder的参数之后StreamBuilder<int>(),它提示我它只会采用整数值。我无法向它提供 Future 或 Stream 类型,因此我决定不使用它。我所做的是通过 ConnectionState 将 FutureBuilder 嵌套在 StreamBuilder 中。
这是我现在的代码:
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}');
}
);
}
}
...
Run Code Online (Sandbox Code Playgroud)
我知道这个解决方案效率很低,但目前我想不出更好的解决方案。
小智 0
初始数据应该是在实际数据可用之前显示的数据。
放置0为初始数据。
StreamBuilder 有一个附加参数stream,负责获取流数据。在这里你可以做stream: getData().asStream,
编辑:
还要确保在 StreamBuilder 中指定您期望的数据类型。StreamBuilder<int>()
| 归档时间: |
|
| 查看次数: |
9425 次 |
| 最近记录: |