_TypeError (type 'Null' is not a subtype of type 'String') - flutter 中发生的错误

_TypeError (type 'Null' is not a subtype of type 'String') - error happening in flutter

我正在尝试将 API 连接到我的应用程序并遇到错误:_TypeError(类型 'Null' 不是类型 'String' 的子类型)

错误发生在以下行:title: Text(snapshot.data?[i].hourly),

我以为我已经实现了空安全来避免这个错误,但它似乎没有用。如果有任何帮助,我将不胜感激!

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(
      home: HomePage(),
      debugShowCheckedModeBanner: false,
    ));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future getUserData() async {
    var response = await http.get(Uri.parse(
         'https://api.open-meteo.com/v1/forecast?  latitude=52.52&longitude=13.41&hourly=temperature_2m'));

var jsonData = jsonDecode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Rangers Tool'),
      ),
      body: Center(
          child: Card(
              child: FutureBuilder(
        future: getUserData(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data?.length,
                itemBuilder: (context, i) {
                  return ListTile(
                    title: Text(snapshot.data?[i].hourly),
                    subtitle: Text(snapshot.data[i]?.latitude),
                  );
                });
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ))),
    );
   }
}

getUserData() {}

class User {
  final String? hourly,
      time,
      temperature_2m,
      longitude,
      generationtime_m,
      hourly_units,
      latitude;

  User(this.longitude, this.latitude, this.hourly, this.time,
      this.temperature_2m, this.generationtime_m, this.hourly_units);
}

根据 api response (response data link),你的 response data 不是 array of json 但你正在尝试渲染 json object as array 并且也在尝试将 json 字段解析为错误的方式,这就是错误发生的原因。

您可以按照下面的代码 spinet 来查看我如何解析 json 然后可以根据您的要求进行修改。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(
      MaterialApp(
        home: HomePage(),
        debugShowCheckedModeBanner: false,
      ),
    );

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<dynamic> getUserData() async {
    var response = await http.get(Uri.parse(
        'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m'));

    var jsonData = jsonDecode(response.body);
    return jsonData;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Rangers Tool'),
      ),
      body: Center(
        child: Card(
          child: FutureBuilder(
            future: getUserData(),
            builder: (context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                var hourly = snapshot.data['hourly'];

                return ListTile(
                  title: Text(
                    "time: ${hourly['time'][0]} - temperature_2m: ${hourly['temperature_2m'][0]}",
                  ),
                  subtitle: Text(
                    "latitude: ${snapshot.data['latitude']}",
                  ),
                );
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          ),
        ),
      ),
    );
  }
}

getUserData() {}

class User {
  final String? hourly,
      time,
      temperature_2m,
      longitude,
      generationtime_m,
      hourly_units,
      latitude;

  User(this.longitude, this.latitude, this.hourly, this.time,
      this.temperature_2m, this.generationtime_m, this.hourly_units);
}

改变两件事

之前

 Future getUserData() async {
    var response = await http.get(Uri.parse(
         'https://api.open-meteo.com/v1/forecast?  latitude=52.52&longitude=13.41&hourly=temperature_2m'));

var jsonData = jsonDecode(response.body);
  }

下一个

 Future getUserData() async {
        var response = await http.get(Uri.parse(
             'https://api.open-meteo.com/v1/forecast?  latitude=52.52&longitude=13.41&hourly=temperature_2m'));     
    return jsonDecode(response.body);
      }

之前

if (!snapshot.hasData)

下一个

if (snapshot.hasData)