大家好,我有一個錯誤,我不知道如何解決,請盡快回復
這是一個資料檔案:
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')
在第一個代碼中遇到了這個錯誤
,我用箭頭提到了它,我面對的那一行請盡快幫助,拜托
uj5u.com熱心網友回復:
錯誤意味著element["author"]可以是null,但是您的author變數不能是null。嘗試空檢查它:
author: element["author"] ?? ''
uj5u.com熱心網友回復:
根據 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);
}
});
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342562.html
上一篇:創建流觀看串列?
