Flutter:无法获取数据

发布于 2025-01-11 02:06:49 字数 2852 浏览 0 评论 0原文

我能够成功获取 JSON 数据,但无法获取 JSON 数据的字段并在 flutter 中构建列表。如果 json 以 [] 开头,它可以正常工作,但这种类型的 json 无法正常工作。我可以看到响应,但我认为我在用列表映射数据方面是错误的。我对 flutter 和 JSON 学习很陌生,我认为我只是在这一点上错了

main.dart

import 'package:myapp/screens/character_list.dart';
import 'package:flutter/material.dart';

void main() 
{
    runApp(MyApp());
}

class MyApp extends StatelessWidget 
{
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            debugShowCheckedModeBanner: false,
            title: "Breaking Bad App",
            theme: ThemeData(primarySwatch: Colors.blue),
            home: CharacterList(),
       );
   }
}

character.dart

class Character 
{
  String category;
  Character.fromJson(Map json) : category = json['category'];
  Map toJson() {
      return {'category': category};
  }
}

character_list.dart

import 'dart:convert';
import 'package:myapp/data/character_api.dart';
import 'package:myapp/model/character.dart';
import 'package:flutter/material.dart';

class CharacterList extends StatefulWidget 
{
    CharacterList({Key key}) : super(key: key);
    @override
    _CharacterListState createState() => _CharacterListState();
}

class _CharacterListState extends State<CharacterList> 
{
    List<Character> characterList = new List<Character>();

    void getCharactersfromApi() async 
    {
        CharacterApi.getCharacters().then((response) 
        {
            setState(() 
            {
               Iterable list = json.decode(response.body);
               characterList = list.map((model) => Character.fromJson(model)).toList();
           });
        });
    }

  @override
  void initState() 
  {
     super.initState();
     getCharactersfromApi();
  }

  @override
  Widget build(BuildContext context) 
  {
      return Scaffold(
          appBar: AppBar(
          title: Text("Breaking Bad Characters"),
      ),
        body: Container(
          child: ListView.builder(
              itemCount: characterList.length,
              itemBuilder: (context, index) {
                return ListTile(
                 
                  title: Text(characterList[index].category),
                  
                );
              }),
        ));
  }
}

character_api.dart

import 'dart:async';
import 'package:http/http.dart' as http;

class CharacterApi {
  static Future getCharacters() {
    
    return http
        .get(Uri.parse('API URL'));
  }
}


json structure is as follows:

{
    "urlset": {
        "item": [{
                "category": ""
            }, {
                "category": "All-in-One PC"
            }, {
                "category": "Apparels & Accessories"
            }, {
                "category": "Art & Craft"
            }, {
                "category": "Audio Speaker & Accessories"
            }
]
    }
}

I am able to fetch the JSON data successfully, but not able to fetch the fields of JSON data and build a list in flutter. If json starts with [] it works fine but this type of json is not working properly. I can see response but I think I am wrong at Mapping data with list. I am new to this flutter and JSON learning, I think I am wrong at this point only

main.dart

import 'package:myapp/screens/character_list.dart';
import 'package:flutter/material.dart';

void main() 
{
    runApp(MyApp());
}

class MyApp extends StatelessWidget 
{
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            debugShowCheckedModeBanner: false,
            title: "Breaking Bad App",
            theme: ThemeData(primarySwatch: Colors.blue),
            home: CharacterList(),
       );
   }
}

character.dart

class Character 
{
  String category;
  Character.fromJson(Map json) : category = json['category'];
  Map toJson() {
      return {'category': category};
  }
}

character_list.dart

import 'dart:convert';
import 'package:myapp/data/character_api.dart';
import 'package:myapp/model/character.dart';
import 'package:flutter/material.dart';

class CharacterList extends StatefulWidget 
{
    CharacterList({Key key}) : super(key: key);
    @override
    _CharacterListState createState() => _CharacterListState();
}

class _CharacterListState extends State<CharacterList> 
{
    List<Character> characterList = new List<Character>();

    void getCharactersfromApi() async 
    {
        CharacterApi.getCharacters().then((response) 
        {
            setState(() 
            {
               Iterable list = json.decode(response.body);
               characterList = list.map((model) => Character.fromJson(model)).toList();
           });
        });
    }

  @override
  void initState() 
  {
     super.initState();
     getCharactersfromApi();
  }

  @override
  Widget build(BuildContext context) 
  {
      return Scaffold(
          appBar: AppBar(
          title: Text("Breaking Bad Characters"),
      ),
        body: Container(
          child: ListView.builder(
              itemCount: characterList.length,
              itemBuilder: (context, index) {
                return ListTile(
                 
                  title: Text(characterList[index].category),
                  
                );
              }),
        ));
  }
}

character_api.dart

import 'dart:async';
import 'package:http/http.dart' as http;

class CharacterApi {
  static Future getCharacters() {
    
    return http
        .get(Uri.parse('API URL'));
  }
}


json structure is as follows:

{
    "urlset": {
        "item": [{
                "category": ""
            }, {
                "category": "All-in-One PC"
            }, {
                "category": "Apparels & Accessories"
            }, {
                "category": "Art & Craft"
            }, {
                "category": "Audio Speaker & Accessories"
            }
]
    }
}

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

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

发布评论

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

评论(2

旧街凉风 2025-01-18 02:06:49

如果您的 JSON 以 [](方括号)开头,则意味着您的 JSON 有一个对象列表,但如果它周围有这些 {} 大括号,则意味着数据是对象而不是列表,或者您可以说它是不能用作列表的单个对象。

If your JSON starts with [] (square brackets), it means your JSON has a list of objects, but if it has these {} curly brackets around it, that means the data is an object not a list or you can say it is a single object which can not be used as a list.

你的往事 2025-01-18 02:06:49

我认为您缺少的是进入正确的 json 属性。类似于: characterList = json.decode(response.body)["urlset"]["item"];

I think what you are missing is stepping into your correct json property. Something like: characterList = json.decode(response.body)["urlset"]["item"];

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