flutter 如何将json数据从一个路由发送到另一个路由

qpgpyjmq  于 2023-02-13  发布在  Flutter
关注(0)|答案(1)|浏览(141)

在我的Flutter应用程序中,我尝试将JSON数据从一个路由传递到另一个路由。我面临的挑战是如何将列表作为参数传递。第一个屏幕包含已获取的JSON数据列表,我的目标是当用户单击相应的ListTile时显示每个项的完整细节。
您将在***JsonParsingPodo.dart***中找到***onTap()***

这是我的密码:

  • posts.dart*(普通旧dart对象文件)
class PostList {
  final List<Post> posts;

  PostList({required this.posts});
  factory PostList.fromJson(Map<String, dynamic> parsedJson) {
    List<dynamic> postsJson = parsedJson['posts'] as List;
    List<Post> posts = <Post>[];
    posts = postsJson.map((e) => Post.fromJson(e)).toList();

    return PostList(posts: posts);
  }
}

class Post {
  int userId;
  int id;
  String title;
  String body;

  Post(
      {required this.id,
      required this.body,
      required this.title,
      required this.userId});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        id: json['id'],
        body: json['body'],
        title: json['title'],
        userId: json['userId']);
  }
}
  • JsonParsingPodo.dart *(第一个屏幕)
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:podo_practice/posts.dart';

import 'display.dart';

class JsonParsingPodo extends StatefulWidget {
  const JsonParsingPodo({super.key});

  @override
  State<JsonParsingPodo> createState() => _JsonParsingPodoState();
}

class _JsonParsingPodoState extends State<JsonParsingPodo> {
  late Future<PostList> data;

  @override
  void initState() {
    super.initState();
    Network network = Network("https://dummyjson.com/posts");
    data = network.loadPost();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: const Text("PODO: json"),
        ),
        body: Center(
          // ignore: avoid_unnecessary_containers
          child: Container(
            child: FutureBuilder(
                future: data,
                builder: (context, AsyncSnapshot<PostList> snapshot) {
                  List<Post> allposts;
                  if (snapshot.hasData) {
                    allposts = snapshot.data!.posts;
                    return createListView(allposts, context);
                  }
                  return const CircularProgressIndicator();
                }),
          ),
        ));
  }

  Widget createListView(List<Post> data, BuildContext context) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, int index) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Divider(
                height: 5.0,
              ),
              ListTile(
                title: Text("${data[index].title}"),
                subtitle: Text("${data[index].body}"),
                leading: Column(
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.green,
                      radius: 23,
                      child: Text("${data[index].id}"),
                    ),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const DisplayData()),
                        // *what to pass here??*
                  );
                },
              ),
            ],
          );
        });
  }
}

class Network {
  final String url;

  Network(this.url);

  Future<PostList> loadPost() async {
    final response = await get(Uri.parse(Uri.encodeFull(url)));

    if (response.statusCode == 200) {
      //ok
      return PostList.fromJson(json.decode(response.body));
    } else {
      throw Exception("Failed to load data. ");
    }
  }
}
  • 显示数据.dart*(第二个屏幕)
import 'package:flutter/material.dart';
import 'package:podo_practice/posts.dart';

class DisplayData extends StatefulWidget {
  const DisplayData({super.key});

  @override
  State<DisplayData> createState() => _DisplayDataState();
}

class _DisplayDataState extends State<DisplayData> {
  late Future<PostList> data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Display Post"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Card(
          child: Column(
            children: [
              // Text(data);
            ],
          ),
        ),
      ),
    );
  }
}

我最近才开始学习Flutter,而且知识不多。我试着阅读有关堆栈溢出的文章,但是我不太理解。所以,我决定发布一个问题寻求帮助。请帮助我完成下面的代码。
在“Display Data”页面上,我需要在用户单击ListItem时显示title及其description

jutyujz0

jutyujz01#

onListile点击使用索引发送特定对象

Widget createListView(List<Post> data, BuildContext context) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, int index) {
Post post = data[index]
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Divider(
                height: 5.0,
              ),
              ListTile(
                title: Text("${data[index].title}"),
                subtitle: Text("${data[index].body}"),
                leading: Column(
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.green,
                      radius: 23,
                      child: Text("${data[index].id}"),
                    ),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const DisplayData(post:post)),
                        // *what to pass here??*
                  );
                },
              ),
            ],
          );
        });
  }
}

获取构造函数上的post以显示

import 'package:flutter/material.dart';
import 'package:podo_practice/posts.dart';

class DisplayData extends StatefulWidget {
 final Post post;
  const DisplayData({super.key,required this.post});

  @override
  State<DisplayData> createState() => _DisplayDataState();
}

class _DisplayDataState extends State<DisplayData> {
  late Future<PostList> data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Display Post"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Card(
          child: Column(
            children: [
              // Text(data);
            ],
          ),
        ),
      ),
    );
  }
}

相关问题