Flutter - 将变量传递到另一个屏幕以获得 URL GET JSON

Flutter - Pass variable to another screen for URL GET JSON

我是 Flutter 新手。在我的主屏幕上,我有一个 ListView,其中包含 Json。我想将点击时的 JSON 变量 ex:id 传递给下一个 screen/class 'contantPage' 以显示从 URL 加载的另一个 Json id 添加。 ex.https:/example.com/myjson.php?id=1

拜托!给我指路。

main.dart

onTap: () {
    Navigator.push(context,MaterialPageRoute(
     builder(context)=>ContentPage(
     photo: photos[index]
)),);},

并且在我的 ContentPage.dart 中应该将 id 值添加到 URL 作为 GET ex:?id=1

Future<Album> fetchAlbum() async {
  // final query1 = Text(photo.publishDate);
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums.php?id=I WANT ID HERE'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

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

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

//void main() => runApp(MyApp());

class ContentPage extends StatefulWidget {
//  ContentPage({Key? key, Photo photo}) : super(key: key);
  ContentPage({Key? key, required Photo photo}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<ContentPage> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

喜欢照片传递你的photoid如下:

onTap: () {
        Navigator.push(context,MaterialPageRoute(
         builder(context)=>ContentPage(
         photo: photos[index],
    id:photos[index].id,
    )),);},

然后在ContentPage中创建构造函数如下:

class ContentPage extends StatefulWidget {
Photo photo;
String id;

  ContentPage({Key? key, required this.photo,required this.id,}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

在 initstate 中按如下方式传递您的 ID:

 @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum(widget.id);
  }

最后你的 fetchAlbum 如下:

Future<Album> fetchAlbum(var id) async {
  // final query1 = Text(photo.publishDate);
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums.php?id=id'));



 if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

我无法理解如何使用我的代码显示多个字段。我有来自 Json 的 title 字段和 contentIntro 字段,想一起显示。

body: Center(
        child: FutureBuilder<Album>(
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Center(
                child: Text(snapshot.data!.contentIntro),
                //child: Text(snapshot.data!.Title),
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

            // By default, show a loading spinner.
            return CircularProgressIndicator();
          },
        ),
      ),