_TypeError(类型“Null”不是类型“String”的子类型)-flutter 中发生错误

发布于 2025-01-18 00:50:59 字数 1933 浏览 1 评论 0原文

我正在尝试将API连接到我的应用程序,并遇到了错误:_typeerror(type'null'不是类型'string'的子类型)

错误出现在行上:title:titter:text:snapshot.data?[i? ]。小时),

我认为我已经实施了无效的安全性来避免此错误,但似乎没有起作用。感谢任何帮助!

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

I am trying to connect an API to my application and have come across the error: _TypeError (type 'Null' is not a subtype of type 'String')

The error occurs on the line: title: Text(snapshot.data?[i].hourly),

I thought that I had implemented null safety to avoid this error but it doesn't seem to have worked. I would appreciate any help!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一梦等七年七年为一梦 2025-01-25 00:50:59

根据 api 响应响应数据链接),您的响应数据 不是 json 数组,但您尝试将 json 对象呈现为数组 并且还尝试以错误的方式解析 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);
}

According to the api response (response data link), your response data is not an array of json but you are trying to render the json object as array and also trying to parse the json field as wrong way thats why the error occurred.

You can follow the bellow code spinet and can see that how I can parse the json then can modify based on your requirement.

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);
}
樱娆 2025-01-25 00:50:59

更改两

在下

 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)

Change two things

Before

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

Next

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

before

if (!snapshot.hasData)

next

if (snapshot.hasData)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文