Flutter HTTP请求有时显示错误 [英] Flutter http request sometimes shows error

查看:143
本文介绍了Flutter HTTP请求有时显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习在Flutter中进行api调用,并制作一个至少对我有用的应用程序!

I'm trying to learn making api calls in Flutter and make an app that'll be useful to me at least!

为此,我正在致电Nifty(印度证券交易所)的API: https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY

For this, I'm making a call to Nifty's(Stock Exchange in India) API: https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY

我正在使用以下代码实现我的目标

I'm using the following code to achieve my goal

import 'dart:convert';

import 'package:http/http.dart';

final url = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY';

Future<Map<String, dynamic>> fetchNiftyData() async {
  final response = await get(
    Uri.parse(url),
  );

  Map<String, dynamic> responseBody = jsonDecode(response.body);
  return responseBody;
}

有效.它直接从api返回数据!

It works. It returns data from the api as it is!!

有时却没有.重新启动应用程序后,它可能会再次运行,也可能无法正常运行.我不希望我的应用在调用api时如此不一致.

BUT SOMETIMES IT DOESN'T. On restarting the app it might work again and might not work too. I don't want my app to be so inconsistent in calling the api.

这是我得到的错误堆栈:

This is the error stack I'm getting:

Restarted application in 3,418ms.
E/flutter ( 3901): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter ( 3901): <!DOCTYPE html>
E/flutter ( 3901): ^
E/flutter ( 3901):
E/flutter ( 3901): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5)
E/flutter ( 3901): #1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1271:9)
E/flutter ( 3901): #2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:936:22)
E/flutter ( 3901): #3      _parseJson (dart:convert-patch/convert_patch.dart:40:10)
E/flutter ( 3901): #4      JsonDecoder.convert (dart:convert/json.dart:506:36)
E/flutter ( 3901): #5      JsonCodec.decode (dart:convert/json.dart:157:41)
E/flutter ( 3901): #6      jsonDecode (dart:convert/json.dart:96:10)
E/flutter ( 3901): #7      fetchBankNiftyData
package:options_trader/Services/fetch_bank_nifty_data.dart:12
E/flutter ( 3901): <asynchronous suspension>
E/flutter ( 3901): #8      _BankNiftyScreenState.getBankNiftyData
package:options_trader/Screens/bank_nifty_screen.dart:21
E/flutter ( 3901): <asynchronous suspension>
E/flutter ( 3901):

最后,这就是我调用/使用获取的数据的方式...

Finally, this is the way I'm calling/using the fetched data...

import 'package:flutter/material.dart';

import '../Services/fetch_nifty_data.dart';

class NiftyScreen extends StatefulWidget {
  @override
  _NiftyScreenState createState() => _NiftyScreenState();
}

class _NiftyScreenState extends State<NiftyScreen> {
  Map<String, dynamic>? niftyDetails = {};

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

  getNiftyDetails() async {
    this.niftyDetails = await fetchNiftyData();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: niftyDetails!.isNotEmpty
          ? ListView.builder(
              itemCount: niftyDetails!["filtered"]["data"].length,
              itemBuilder: (_, index) {
                return ListTile(
                  title: Text(
                      '${niftyDetails!["filtered"]["data"][index]["strikePrice"]}'),
                );
              },
            )
          : LinearProgressIndicator(),
    );
  }
}

我做错了什么?最佳实践是什么?TIA

What am I doing wrong? And what's the best practice? TIA

推荐答案

API不以所需格式返回所需数据时,会导致<!DOCTYPE html> 错误预期为json,但会返回错误页面,最有可能是404,该页面以<!DOCTYPE html> 开头,而不是 {"records":{"expiryDates"; ... etc] ,可以使用jsonDecode进行解析.

The <!DOCTYPE html> error is caused when the API doesn't return the data you wanted in the format you are expecting, which is json, but it returns an error page, most likely a 404, which starts with <!DOCTYPE html>, and not {"records":{"expiryDates"...etc] which can be parsed using jsonDecode.

如果它可以工作几次,而其他人却不能,那么这很可能不是您的问题,这可能是受API本身的速率限制所致,这解释了为什么以后无需重新更改代码即可再次使用它.

If it's working a few times, and others not, It's not your problem most likely, and it's perhaps caused by being rate limited by the API itself, which explains why it works again later, without you changing your code.

这篇关于Flutter HTTP请求有时显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆