-1

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();
            },
          ),
    );
  }
}

I'm using the example in flutter's documentation on how to fetch data from the internet (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 ) but for some reason, I can't get the information to be displayed on my App, forgive the ignorance but I'm new to programming and flutter...

1 Answers1

0

You are parsing the json in the wrong way: the json from that url has a different structure, the keys you are trying to fetch are nested inside "query":{"pages":{"34415" while you are searching for them at the top level.

E.g. in this case, this :

pageid: json['pageid'] 

should be:

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

But it works only in this specific case. Instead, you should first fetch all the pages you get by that query from json['query']['pages'] then loop over the keys (the ids of every page got) and fetch the pages.

anmol.majhail
  • 48,256
  • 14
  • 136
  • 105
Francesco Mineo
  • 137
  • 1
  • 6
  • Not, that was just an example to show you the correct structure of that json, You need something like that: var resp = json.decode(response.body); var pages = resp['query']['pages'] as Map; pages.forEach((k,v) { // here you can parse "v" as the page with the Post.fromJson }); – Francesco Mineo Dec 21 '18 at 09:52