1
votes

I'm trying to get weekly stock data from an API in Flutter. However, the response is cut off quite early. What am I missing?

static Future<List<StockWeek>> fetchAll() async {
    // creates: https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=MSFT&apikey=demo
    var uri = Endpoint.uri('', queryParameters: { "function" : "TIME_SERIES_WEEKLY", "symbol" : "MSFT", "apikey" : "demo" });

    final resp = await http.get(uri.toString());

    if (resp.statusCode != 200) {
      throw (resp.body);
    }

    print(resp.body.toString());

    List<StockWeek> list = new List<StockWeek>();

    // parse JSON

    return list;
  }

What I'm getting at the time of the print statement is this:

I/flutter (19224): {
I/flutter (19224):     "Meta Data": {
I/flutter (19224):         "1. Information": "Weekly Prices (open, high, low, close) and Volumes",
I/flutter (19224):         "2. Symbol": "MSFT",
I/flutter (19224):         "3. Last Refreshed": "2018-12-03",
I/flutter (19224):         "4. Time Zone": "US/Eastern"
I/flutter (19224):     },
I/flutter (19224):     "Weekly Time Series": {
I/flutter (19224):         "2018-12-03": {
I/flutter (19224):             "1. open": "113.0000",
I/flutter (19224):             "2. high": "113.4200",
I/flutter (19224):             "3. low": "110.7300",
I/flutter (19224):             "4. close": "112.0900",
I/flutter (19224):             "5. volume": "34275048"
I/flutter (19224):         },
I/flutter (19224):         "2018-11-30": {
I/flutter (19224):             "1. open": "104.7900",
I/flutter (19224):             "2. high": "111.3300",
I/flutter (19224):             "3. low": "104.5800",
I/flutter (19224):             "4. close": "110.8900",
I/flutter (19224):             "5. volume": "170037931"
I/flutter (19224):         },
I/flutter (19224):         "2018-11-23": {
I/flutter (19224):             "1. open": "108.2700",
I/flutter (19224):             "2. high": "108.5600",
I/flutter (19224):             "3. low": "99.3528",
I/flutter (19224):             "4. close": "103.0700",
I/flutter (19224):             "5. volume": "150780076"
I/flutter (19224):         },
I/flutter (19224):         "2018-11-16": {
I/flutter (19224):             "1. open": "109.4200",
I/flutter (19224):             "2. high": "109.9600",
I/flutter (19224):             "3. low": "103.9100",
I/flutter (19224):             "4. 

It consistently stops at this point. As opposed to what the reply should look like:

https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=MSFT&apikey=demo

2
It's probably just the log output that gets truncated. - Günter Zöchbauer
Makes sense, thanks! Since my json parsing throws an exception I thought the response might be incomplete. But I guess the problem lays elsewhere.. - dan
Set a breakpoint and investigate the value there. - Günter Zöchbauer
Try to run the API in Postman or other API Client and validate whether the API is sending wrong data or not - Dhrumil Shah - dhuma1981

2 Answers

0
votes

This is just a logging issue when using print() with a lot of lines. Use debugPrint() from Flutter’s foundation library instead as recommended here.

import 'package:flutter/foundation.dart'; 

static Future<List<StockWeek>> fetchAll() async {
    // creates: https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=MSFT&apikey=demo
    var uri = Endpoint.uri('', queryParameters: { "function" : "TIME_SERIES_WEEKLY", "symbol" : "MSFT", "apikey" : "demo" });

    final resp = await http.get(uri.toString());

    if (resp.statusCode != 200) {
      throw (resp.body);
    }

    debugPrint(resp.body.toString());

    List<StockWeek> list = new List<StockWeek>();

    // parse JSON

    return list;   
}
0
votes

It is nothing to worry about. Its just that, if the output for the printing the data is too large, then only some part of the data will be shown in the console. I have tried finding out the reason, but still haven't found any. But when you try using it when building out your screen, you will get all the data that you intended.

So my bottom line: just build your widget(screen layout) and use the data as you wanted to, and it will work out.

For example, I used this https://jsonplaceholder.typicode.com/posts as my json data source

Create a class called Networking :

import 'dart:convert';
import 'package:http/http.dart' as http;

class Networking {
  final String url;

  Networking({this.url});

  Future getNewsData() async {
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      String data = response.body;
      return jsonDecode(data);
    } else {
      print(response.statusCode);
    }
  }
}

This is the screen used to display the contents that were fetched :

class NewsScreen extends StatefulWidget {
  static const String routeName = 'news_screen';

  @override
  _NewsScreenState createState() => _NewsScreenState();
}

class _NewsScreenState extends State<NewsScreen> {
  static const String newsSource = 'https://jsonplaceholder.typicode.com/posts';
  var newsData;
  bool isLoading = true;

  @override
  void initState() {
    getNewsContent();
    super.initState();
  }

  Future<dynamic> getNewsContent() async {
    Networking newsNetwork = Networking(url: newsSource);
    newsData = await newsNetwork.getNewsData();
    [enter image description here][1]print(newsData);
    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "News",
        ),
      ),
      body: isLoading
          ? Container(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            )
          : ListView.builder(
              itemCount: newsData == null ? 0 : newsData.length,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  margin: EdgeInsets.all(10),
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Column(
                      children: <Widget>[
                        Text('title:${newsData[index]['title']}'),
                        Text('id:${newsData[index]['id']}'),
                        Text('userId:${newsData[index]['userId']}'),
                        Text('body:${newsData[index]['body']}'),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
}

Snapshot of console output

Snapshot of display screen