gegentierversuche
gegentierversuche

Reputation: 178

cannot access JSON datas

I cannot access categories.id and name. But code should be work. Unfortunately I cannot find the reason.

here is 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;

and finally 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,
      };
}

I am newbie and more than one week I am trying many things to do fix it but unfortunately I could not find the problem. The section of my apps news, images, an all other stuff works but I cannot get categories.

Any help?

Upvotes: 0

Views: 46

Answers (1)

Caffo17
Caffo17

Reputation: 543

final categories = snapshot.data?.data;

You have defined the parameter data as a List<Category> inside the Categories class. That's why you can't access to name or id parameters doing categories.name. You need first to access to a certain position like categories[0].name.

I suggest you to return a ListView.builder from the FutureBuilder.

Upvotes: 1

Related Questions