从openweathermap获取位置API时,类型'String'不是'index'的'int'类型的子类型

时间:2020-11-04 09:11:15

标签: json flutter dart

我正在尝试关于Flutter课程(https://www.udemy.com/share/101WB6/)的教程,其中从API调用检索位置数据,并且在解码数据时显示错误, 我尝试更改变量的数据类型,但错误仍然存​​在。 错误消息是:

The following _TypeError was thrown building Builder:
type 'String' is not a subtype of type 'int' of 'index'

The relevant error-causing widget was: 
  MaterialApp file:///C:/Users/saleem/StudioProjects/Clima/lib/main.dart:9:12
When the exception was thrown, this was the stack: 
#0      _LocationScreenState.updateUI (package:clima/screens/location_screen.dart:25:30)
#1      _LocationScreenState.initState (package:clima/screens/location_screen.dart:21:5)
#2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
#3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
...     Normal element mounting (132 frames)

我尝试将变量的数据类型全部更改为String和var,IAM实际上是针对编程领域的 我将在下面附加飞镖代码:

import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';

class LocationScreen extends StatefulWidget {
  LocationScreen({this.locationWeather});
  final locationWeather;

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

class _LocationScreenState extends State<LocationScreen> {
  double temperature;
  int condition;
  String cityName;

  @override
  void initState() {
    super.initState();
    print(widget.locationWeather);
    updateUI(widget.locationWeather);
  }

  void updateUI(dynamic weatherData) {
    temperature = weatherData['main']['temp'];
    condition = weatherData['weather'][0]['id'];
    cityName = weatherData['name'];
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
      ...
    );
  }
}

这是API输出

I/flutter (14299): "{\"coord\":{\"lon\":139.01,\"lat\":35.02},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}],\"base\":\"stations\",\"main\":{\"temp\":285.514,\"pressure\":1013.75,\"humidity\":100,\"temp_min\":285.514,\"temp_max\":285.514,\"sea_level\":1023.22,\"grnd_level\":1013.75},\"wind\":{\"speed\":5.52,\"deg\":311},\"clouds\":{\"all\":0},\"dt\":1485792967,\"sys\":{\"message\":0.0025,\"country\":\"JP\",\"sunrise\":1485726240,\"sunset\":1485763863},\"id\":1907296,\"name\":\"Tawarano\",\"cod\":200}"

问题已解决,我使用了jsonEncode而不是jsonDecode

3 个答案:

答案 0 :(得分:0)

本教程的链接会很不错。我想是

condition = weatherData['weather'][0]['id'];

应该是

condition = weatherData['weather']['0']['id'];

答案 1 :(得分:0)

int condition =>字符串条件; 或将第30行解析为int

答案 2 :(得分:0)

API输出是一个字符串。

首先导入'dart:convert';

并将您的API输出包装在 jsonDecode(API_OUTPUT)中。

这将使它成为一个json对象,然后您可以按照自己的方式访问其内容。