如何通过postId flutter获取项目列表的信息



我有一个应用程序,其中主页使用json显示帖子列表。点击帖子后,我需要根据提供者导航/显示帖子评论列表。怎么做?

一个列出所有帖子的屏幕。https://jsonplaceholder.typicode.com/posts有评论列表的帖子详细信息屏幕。https://jsonplaceholder.typicode.com/posts/{post_id}/注释

主页:

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
// TODO: implement initState
final provider = Provider.of<GetPostProvider>(context, listen: false);
provider.getMyData();
super.initState();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<GetPostProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text('User Id'),
),
body: ListView.builder(
itemCount: provider.postModelClass.length,
itemBuilder: ((context, index) {
return Card(child: Consumer<GetPostProvider>(
builder: (context, value, child) {
return ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return CommentScreen(
postModelClass: value.postModelClass[index]);
//here comes error
}));
},
leading: CircleAvatar(
child: Text("${value.postModelClass[index].id}"),
),
title: Text("${value.postModelClass[index].title}"),
);
},
));
})));
}
}

评论页面:

class CommentPage extends StatefulWidget {
final CommentModel postModelClass;
const CommentPage({
Key? key,
required this.postModelClass,
}) : super(key: key);
@override
State<CommentPage> createState() => _CommentPageState();
}
class _CommentPageState extends State<CommentPage> {
@override
Widget build(BuildContext context) {
final commentprovider = Provider.of<GetCommentProvider>(context);
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: commentprovider.comment.length,
itemBuilder: ((context, index) {
return Text(commentprovider.comment[index].email.toString());
})));
}
}

PostDetailModel:

class PostModelClass {
int? userId;
int? id;
String? title;
String? body;
PostModelClass({
this.userId,
this.id,
this.title,
this.body,
});
Map<String, dynamic> toJson() {
return {'userId': userId, 'id': id, 'title': title, 'body': body};
}
factory PostModelClass.fromJson(Map<String, dynamic> data) {
final userId = data['userId'];
final id = data['id'];
final title = data['title'];
final body = data['body'];
return PostModelClass(id: id, userId: userId, title: title, body: body);
}
}

CommentModel:

class CommentModel {
int? userId;
int? id;
String? name;
String? email;
String? body;
CommentModel({
this.userId,
this.id,
this.name,
this.email,
this.body,
});
Map<String, dynamic> toJson() {
return {
'userId': userId,
'id': id,
'name': name,
'email': email,
'body': body
};
}
factory CommentModel.fromJson(Map<String, dynamic> data) {
final userId = data['userId'];
final id = data['id'];
final name = data['name'];
final email = data['email'];
final body = data['body'];
return CommentModel(
userId: userId, id: id, name: name, email: email, body: body);
}
}

PostProvider:

class GetPostProvider with ChangeNotifier {
bool isLoading = false;
List<PostModelClass> postModelClass = [];
getMyData() async {
isLoading = true;
postModelClass = await getAllPost();
isLoading = false;
notifyListeners();
}
Future<List<PostModelClass>> getAllPost() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
List<PostModelClass> mylist = [];
try {
if (response.statusCode == 200) {
final jsonDecode = await json.decode(response.body);
for (var i in jsonDecode) {
PostModelClass _model = PostModelClass.fromJson(i);
mylist.add(_model);
}
return mylist;
} else {
return mylist;
}
} catch (e) {
throw 'aaaaaaaaaa';
}
}
}

CommentProvider:

class GetCommentProvider with ChangeNotifier {
bool isLoading = false;
List<CommentModel> comment = [];
late int userId;
getComment() async {
isLoading = true;
comment = await getAllComment(userId);
isLoading = false;
notifyListeners();
}
Future<List<CommentModel>> fetchComment(int id) async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts/${id}/comments'));
try {
if (response.statusCode == 200) {
final jsonDecode = json.decode(response.body)['comments'] as List;
return jsonDecode
.map((comments) => CommentModel.fromJson(comments))
.toList();
} else {
throw Exception('Failed to load model');
}
} catch (e) {
throw 'error + $e';
}
}
Future<List<CommentModel>> getAllComment(int userId) async {
final response = await http.get(Uri.parse(
'https://jsonplaceholder.typicode.com/posts/$userId/comments'));
List<CommentModel> mylist = [];
try {
if (response.statusCode == 200) {
final jsonDecode = await json.decode(response.body);
for (var i in jsonDecode) {
CommentModel _model = CommentModel.fromJson(i);
mylist.add(_model);
}
return mylist;
} else {
return mylist;
}
} catch (e) {
throw 'aaaaaaaaaa';
}
}
}

我认为值本身是postModelClass的列表,因此您可以使用以下命令来访问它

postModelClass.value[index];

要获得特定帖子的评论:

更新GetCommentProvider类

class GetCommentProvider with ChangeNotifier {
List<CommentModel> comment = [];
....
getComment(int postId) async {
isLoading = true;
comment = await fetchComment(postId);//update
isLoading = false;
notifyListeners();
}
....
....
}

然后在CommentPage的initState((中添加这个

@override
void initState() {
final provider = Provider.of<GetCommentProvider>(context, listen: false);
provider.getComment(widget.postModelClass.id);//update
}

读取值的最简单方法是使用[BuildContext]上的扩展方法:

  • context.watch((,它使小部件侦听T上的更改
  • context.read((,它在不侦听的情况下返回T

更新您的评论页面:

class _CommentPageState extends State<CommentPage> {
@override
void initState() {
// TODO: implement initState
super.initState();
context.read<GetCommentProvider>().getComment(widget.postModelClass.id!);
}
@override
Widget build(BuildContext context) {
final commentProvider = context.watch<GetCommentProvider>();
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: commentProvider.comment.length,
itemBuilder: ((context, index) {
return Text(commentProvider.comment[index].email.toString());
}),
),
);
}
}

并修复GetCommentProvider:

class GetCommentProvider with ChangeNotifier {

...

getComment(int postId) async {
isLoading = true;
comment = await getAllComment(postId);
isLoading = false;
notifyListeners();
}
...

相关内容

  • 没有找到相关文章

最新更新