flutter - 无法访问 JSON 数据
问题描述
我无法访问 categories.id 和名称。但是代码应该可以工作。不幸的是我找不到原因。
这是category.view:
import 'package:flutter/material.dart';
import '/data/models/models.dart';
import '/data/services/services.dart';
import '/data/models/category.dart';
class CategoryViewDetail extends StatefulWidget {
const CategoryViewDetail({Key? key}) : super(key: key);
@override
_CategoryViewDetailState createState() => _CategoryViewDetailState();
}
class _CategoryViewDetailState extends State<CategoryViewDetail> {
final _categoryService = NewsService();
late Future<Categories> _futureCategories;
@override
void initState() {
_futureCategories = _categoryService.getAllCategories();
super.initState();
}
...
...
...
...
child: FutureBuilder<Categories>(
future: _futureCategories,
builder: (BuildContext context, AsyncSnapshot<Categories> snapshot) {
if (snapshot.hasData) {
final categories = snapshot.data?.data;
return Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: ListTile(
title: Text(
'Title: ${categories?.name}',
),
subtitle: Text(
'Content: ${categories?.id}',
),
),
);
news_service.dart
Future<Categories> getAllCategories() async {
final _queryParametersCategoryId = {
"route": "services/news/getAllCategories",
};
///
final _url = Uri.https(
_authority,
_unencodedPath,
_queryParametersCategoryId,
);
///
final _headers = <String, String>{
'content-type': 'application/json',
};
///
final _response = await http.get(
_url,
headers: _headers,
);
/// JSON Object To String
final _jsonBody = _response.body;
/// String To Map
final Map<String, dynamic> _decodedBody = jsonDecode(_jsonBody);
/// JSON (Map) To Dart (Object)
final _articleIdResponse = Categories.fromJson(_decodedBody);
switch (_response.statusCode) {
case 200:
/// Response: Dart Object
return _articleIdResponse;
最后是 category.dart
class Categories {
const Categories({
this.success,
this.message,
this.errorCode,
this.data,
});
final bool? success;
final String? message;
final int? errorCode;
final List<Category>? data;
factory Categories.fromJson(Map<String, dynamic> json) => Categories(
success: json["success"],
message: json["message"],
errorCode: json["error_code"],
data:
List<Category>.from(json["data"].map((x) => Category.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"message": message,
"error_code": errorCode,
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Category {
const Category({
this.id,
this.name,
});
final String? id;
final String? name;
factory Category.fromJson(Map<String, dynamic> json) => Category(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
我是新手,一个多星期以来我正在尝试很多事情来解决它,但不幸的是我找不到问题。我的应用程序新闻、图像和所有其他内容的部分有效,但我无法获得类别。
有什么帮助吗?
解决方案
final categories = snapshot.data?.data;
您已将参数定义data
为类List<Category>
内部的a Categories
。这就是为什么您无法访问 name 或 id 参数的原因categories.name
。您需要首先访问某个位置,例如categories[0].name
.
ListView.builder
我建议你从 FutureBuilder返回一个。
推荐阅读
- java - 如何将代理对象传递给另一个类?
- bash - Get occurrence of string, containing single or double citation marks using grep
- jsf - JSF 应用程序前端的全局日期/布尔格式
- python - 如何将 Pycharm 和 git 与 azure machile 学习服务(工作区)集成
- r - Function to group continuous variable in data.table
- ios - Xamarin 发布构建架构
- ruby-on-rails - 文件字段在更新时具有空值
- java - How to add correlation ID to the java program?
- vb.net - 如何防止函数完成
- hyperledger-fabric - Hyperledger Fabric : Impact on transaction when we migrate Orderer