【发布时间】:2021-07-02 22:44:31
【问题描述】:
我正在尝试StreamBuilder,所以我调用了 API,快照的返回值始终为空。当我打印print(snapshot.error.toString()); 时,它返回null。我试过以不同的方式解析数据,但没有这样做。完整代码如下:
var posts = <Post>[];
var controller = StreamController<List<Post>>();
@override
void initState() {
super.initState();
fetchPosts();
}
fetchPosts() async {
final resp =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
final data = json.decode(resp.body);
posts = data.map<Post>((e) => Post()).toList();
print(posts.isEmpty); // returns false
pirnt(data); // returns the entire data
controller.add(posts);
}
bool isSwitched = false;
void toggleSwitch(bool value) {
if (isSwitched == false) {
controller.add(posts..sort((k1, k2) => k1.id.compareTo(k2.id)));
print('Switch Button is ON');
} else {
controller.add(posts..sort((k1, k2) => k2.id.compareTo(k1.id)));
print('Switch Button is OFF');
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
child: TextButton(
child: Text('sort ascending'),
onPressed: () {
toggleSwitch(isSwitched = !isSwitched);
}),
),
],
),
Expanded(
child: StreamBuilder<List<Post>>(
initialData: posts,
stream: controller.stream,
builder: (ctx, snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
print(snapshot.error.toString);
Post post = snapshot.data[index];
return ListTile(
title: Text('${posts[index].id}'), // returns null
subtitle: Text('${post.id}'), // returns null
trailing: Text('${snapshot.data[index].id}'), // returns null
);
},
);
},
),
),
],
);
}
后模型:
import 'package:flutter/foundation.dart';
import 'dart:core';
class Post extends ChangeNotifier {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
我是否在 API 调用中解析了错误的数据?或者是别的什么?提前感谢您的帮助。
【问题讨论】:
-
print(snapshot.error.toString);->print(snapshot.error);(或print(snapshot.error.toString());) -
它返回
null。我没有意识到我错过了打印语句中的括号,我将编辑问题。 -
所以如果
snapshot.error为空也没关系,你需要改变:(e) => Post()->(e) => Post.fromJson(e) -
我总是忘记在dart中解析
JSON对象是不同的,它不像JS。再次感谢伙计,这些天你是我的救星/朋友。 :)
标签: json flutter mobile flutter-dependencies