【问题标题】:_TypeError (type 'Null' is not a subtype of type 'String') in flutter_TypeError(类型'Null'不是'String'类型的子类型)在颤动
【发布时间】:2021-12-14 15:48:56
【问题描述】:

大家好,我有一个错误,我不知道如何解决,请尽快回复

这是一个数据文件:

import 'dart:convert';
import 'package:newspaper/models/article.dart';
import 'package:http/http.dart' as http;

class News {
  List<ArticleModel> news = [];
  Future<void> getNews() async {
    var url = Uri.parse(
        "https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=5c2be84a9b8548ab8dde4cfa1eaa1023");
    var response = await http.get(url);
    var jsonData = jsonDecode(response.body);
    if (jsonData['status'] == "ok") {
      jsonData["articles"].forEach((element) {
        if (element["urlToImage"] != null && element['description'] != null) {
          ArticleModel articleModel = ArticleModel(
            title: element["title"],
            author: element["author"],**--> facing error here the error is(Exception has occurred.
_TypeError (type 'Null' is not a subtype of type 'String'))**
            description: element["description"],
            url: element["url"],
            urlToImage: element["urlToImage"],
            content: element["context"],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

这个文件的模数如下:

class ArticleModel {
  String author;
  String title;
  String description;
  String url;
  String urlToImage;
  String content;

  ArticleModel({
    required this.author,
    required this.title,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.content,
  });
}

这些是数据处理的代码

在下面的代码中,我调用我收到的数据

// ignore_for_file: prefer_typing_uninitialized_variables
import 'package:flutter/material.dart';
import 'package:newspaper/helper/data.dart';
import 'package:newspaper/helper/news.dart';
import 'package:newspaper/models/article.dart';
import 'package:newspaper/models/categorymodel.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {
  List<CategoryModel> categories = <CategoryModel>[];
  List<ArticleModel> articles = <ArticleModel>[];

  // ignore: non_constant_identifier_names
  bool _Loading = true;

  @override
  void initState() {
    super.initState();
    categories = getCategories();
    getNews();
  }

  getNews() async {
    News newsClass = News();
    await newsClass.getNews();
    articles = newsClass.news;
    setState(() {
      _Loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text(
              "News",
              style: TextStyle(color: Colors.black),
            ),
            Text(
              "Paper",
              style: TextStyle(color: Colors.blue),
            ),
          ],
        ),
      ),
      // ignore: avoid_unnecessary_containers
      body: _Loading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              child: Column(
                children: [
                  ///categories
                  // ignore: sized_box_for_whitespace
                  Container(
                    height: 70,
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: ListView.builder(
                        itemCount: categories.length,
                        shrinkWrap: true,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (context, index) {
                          return CategoryTile(
                            imageUrl: categories[index].imageUrl,
                            categoryName: categories[index].categoryName,
                          );
                        }),
                  ),

                  ///blogs
                  // ignore: avoid_unnecessary_containers
                  Container(
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: articles.length,
                      itemBuilder: (context, index) {
                        return BlogTile(
                          imageUrl: articles[index].urlToImage,
                          title: articles[index].title,
                          desc: articles[index].description,
                        );
                      },
                    ),
                  )
                ],
              ),
            ),
    );
  }
}

class CategoryTile extends StatelessWidget {
  final imageUrl, categoryName;
  // ignore: use_key_in_widget_constructors
  const CategoryTile({this.imageUrl, this.categoryName});

  @override
  Widget build(BuildContext context) {
    // ignore: avoid_unnecessary_containers
    return GestureDetector(
      onTap: () {},
      child: Container(
        margin: const EdgeInsets.only(right: 16),
        child: Stack(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.network(imageUrl,
                  width: 120, height: 60, fit: BoxFit.cover),
            ),
            Container(
              alignment: Alignment.center,
              width: 120,
              height: 60,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Colors.black26,
              ),
              child: Text(
                categoryName,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class BlogTile extends StatelessWidget {
  final String imageUrl, title, desc;
  // ignore: use_key_in_widget_constructors
  const BlogTile(
      {required this.imageUrl, required this.title, required this.desc});

  @override
  Widget build(BuildContext context) {
    // ignore: avoid_unnecessary_containers
    return Container(
      child: Column(
        children: [
          Image.network(imageUrl),
          Text(title),
          Text(desc),
        ],
      ),
    );
  }
}

我正面临这个错误 _TypeError (type 'Null' is not a subtype of type 'String') 在第一个代码中,我用箭头提到了我面对的那一行,请尽快提供帮助,请

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    错误意味着element["author"] 可以是null,但是您的author 变量不能是null。尝试空检查:

    author: element["author"] ?? ''
    

    【讨论】:

    • 爱你,兄弟真的是你拯救了我的一天
    【解决方案2】:

    根据 api 响应,author 可以为空,但您的 ArticleModel 传递不可为空,即 String。要解决此问题,请将其设为可空并处理其为空的情况。

    import 'package:newspaper/models/article.dart';
    import 'package:http/http.dart' as http;
    
    class News {
      List<ArticleModel> news = [];
      Future<void> getNews() async {
        var url = Uri.parse(
            "https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=5c2be84a9b8548ab8dde4cfa1eaa1023");
        var response = await http.get(url);
        var jsonData = jsonDecode(response.body);
        if (jsonData['status'] == "ok") {
          jsonData["articles"].forEach((element) {
            if (element["urlToImage"] != null && element['description'] != null) {
              ArticleModel articleModel = ArticleModel(
                title: element["title"],
                author: element["author"] ?? 'unknown', **--> give default value when null where 
    `??` means value to assign is value on left is null
                description: element["description"],
                url: element["url"],
                urlToImage: element["urlToImage"],
                content: element["context"],
              );
              news.add(articleModel);
            }
          });
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2023-01-12
      • 2020-01-18
      • 2021-02-05
      • 2020-02-01
      • 1970-01-01
      • 2023-02-24
      • 2022-07-26
      • 2021-03-29
      相关资源
      最近更新 更多