无法使用 http Wikipedia 介绍在 Flutter 中显示从互联网获取的数据 Api
Can't display data Fetched from the internet in Flutter using http Wikipedia intro Api
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:http/http.dart' as http;
class Home extends StatelessWidget
{
@override
Widget build(BuildContext context)
{
return MyApp(post: fetchPost());
}
}
Future<Post> fetchPost() async {
final response = await http.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Zambia');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int pageid;
final int ns;
final String title;
final String extract;
Post({this.pageid, this.ns, this.title, this.extract});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
pageid: json['pageid'],
ns: json['ns'],
title: json['title'],
extract: json['extract'],
);
}
}
class ImageCarousel extends StatelessWidget
{
final carousel = Carousel(
showIndicator: false,
boxFit: BoxFit.cover,
images: [
AssetImage('assets/images/animals.jpg'),
AssetImage('assets/images/bigfalls.jpg'),
AssetImage('assets/images/resort.jpg'),
AssetImage('assets/images/soca.jpg'),
AssetImage('assets/images/towncity.jpg')
],
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(microseconds: 20000),
);
@override
Widget build(BuildContext context)
{
double screenHeight = MediaQuery.of(context).size.height / 3;
return ListView(
children: <Widget>[
Container(
height: screenHeight,
color: Colors.red,
child: carousel,
),
const Text('About Zambia', style: TextStyle(fontWeight: FontWeight.bold)),
],
);
}
}
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Container(
child: FutureBuilder<Post>(
future: post,
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();
},
),
);
}
}
我正在使用 flutter 文档中关于如何从互联网获取数据的示例 (https://flutter.io/docs/cookbook/networking/fetch-data), and in place of https://jsonplaceholder.typicode.com/posts/1 I'm using ( https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Zambia ) 但是由于某些原因,我无法在我的应用程序上显示信息,请原谅无知,但我是编程和 flutter 的新手...
您正在以错误的方式解析 json:来自 url 的 json 具有不同的结构,您尝试获取的键嵌套在 "query":{"pages":{"34415"
当您在顶层搜索它们时。
例如在这种情况下,这个:
pageid: json['pageid']
应该是:
pageid: json['query']['pages']['34415']['pageid']
但它仅适用于这种特定情况。相反,您应该首先从 json['query']['pages']
获取通过该查询获得的所有页面,然后遍历键 (获得的每个页面的 ID) 并获取页面。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:http/http.dart' as http;
class Home extends StatelessWidget
{
@override
Widget build(BuildContext context)
{
return MyApp(post: fetchPost());
}
}
Future<Post> fetchPost() async {
final response = await http.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Zambia');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int pageid;
final int ns;
final String title;
final String extract;
Post({this.pageid, this.ns, this.title, this.extract});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
pageid: json['pageid'],
ns: json['ns'],
title: json['title'],
extract: json['extract'],
);
}
}
class ImageCarousel extends StatelessWidget
{
final carousel = Carousel(
showIndicator: false,
boxFit: BoxFit.cover,
images: [
AssetImage('assets/images/animals.jpg'),
AssetImage('assets/images/bigfalls.jpg'),
AssetImage('assets/images/resort.jpg'),
AssetImage('assets/images/soca.jpg'),
AssetImage('assets/images/towncity.jpg')
],
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(microseconds: 20000),
);
@override
Widget build(BuildContext context)
{
double screenHeight = MediaQuery.of(context).size.height / 3;
return ListView(
children: <Widget>[
Container(
height: screenHeight,
color: Colors.red,
child: carousel,
),
const Text('About Zambia', style: TextStyle(fontWeight: FontWeight.bold)),
],
);
}
}
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Container(
child: FutureBuilder<Post>(
future: post,
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();
},
),
);
}
}
我正在使用 flutter 文档中关于如何从互联网获取数据的示例 (https://flutter.io/docs/cookbook/networking/fetch-data), and in place of https://jsonplaceholder.typicode.com/posts/1 I'm using ( https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Zambia ) 但是由于某些原因,我无法在我的应用程序上显示信息,请原谅无知,但我是编程和 flutter 的新手...
您正在以错误的方式解析 json:来自 url 的 json 具有不同的结构,您尝试获取的键嵌套在 "query":{"pages":{"34415"
当您在顶层搜索它们时。
例如在这种情况下,这个:
pageid: json['pageid']
应该是:
pageid: json['query']['pages']['34415']['pageid']
但它仅适用于这种特定情况。相反,您应该首先从 json['query']['pages']
获取通过该查询获得的所有页面,然后遍历键 (获得的每个页面的 ID) 并获取页面。