无法显示使用http Wikipedia简介Api从Flutter从互联网获取的数据

时间:2018-12-21 07:42:58

标签: dart flutter wikipedia-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)获取数据,而我使用的是(https://jsonplaceholder.typicode.com/posts/1)来代替https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Zambia,但是由于某些原因,我无法在我的App上显示信息,请原谅您的无知,但我是编程和入门的新手。

1 个答案:

答案 0 :(得分:0)

您以错误的方式解析json:来自该url的json具有不同的结构,当您在顶层搜索它们时,您试图获取的键嵌套在"query":{"pages":{"34415"中。

例如在这种情况下,这是

pageid: json['pageid'] 

应为:

pageid: json['query']['pages']['34415']['pageid']

但是它仅在这种特定情况下有效。相反,您应该首先从json['query']['pages']获取通过该查询获取的所有页面,然后遍历键(获取的每个页面的ID)并获取页面。

相关问题