带开关的Flutter条件

3lxsmp7m  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(131)

你好,我是一个编码新手,现在尝试获取这个API,基于文章的类型来分离列表,

[{type: article, data: {post_id: 11530, thumbnail_image: https://www.beingtheparent.com/wp-content/uploads/2015/10/Home-Remedies-For-Swollen-Feet-During-Pregnancy.jpg, count: 15, Title: Home Remedies For Swollen Feet During Pregnancy, content: The word edema denotes swelling and during pregnancy, most women at any stage can suffer from swelling in ankles, hands,.., permalink: https://www.beingtheparent.com/top-10-home-remedies-for-swollen-feet-during-pregnancy/, slug: top-10-home-remedies-for-swollen-feet-during-pregnancy, categoryName: 2b. Health & Safety, categorySlug: health-and-safety, week_category_name: Pregnancy Week 30, week_category_slug: pregnancy-week-30, special_category_name: , special_category_slug: , child_safety_category_name: , child_safety_category_slug: , life_skills_category_name: , life_skills_category_slug: , post_tag_name: Week 29, post_tag_slug: week-29}},

 {type: article, data: {post_id: 11531, thumbnail_image: https://www.beingtheparent.com/wp-content/uploads/2015/10/Home

代码

enum HomeFeedProviderState { idle, loading, loaded, error }

class HomeFeedProvider extends ChangeNotifier {
  List<FeedDataModel2> feedDatacollection = [];

  List<Data22> userpostCollection = [];
  List<Data22> articlesPostcollection = [];
  List<Data22> momsLikeyoucollection = [];

  HomeFeedProviderState currenstState = HomeFeedProviderState.idle;

  static HomeFeedProvider instance = HomeFeedProvider();
  Future<void> fetchHomeFeedData() async {
    currenstState = HomeFeedProviderState.loading;
    notifyListeners();
    var url = 'https://auth.dev.beingtheparent.com/Btpmobileapi/get_feed';

    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      var feed = jsonDecode(response.body);

      var data = feed['data'];

      print("feedData$data");

      print("newones ${data['type'].runtimeType}");

      switch (data["type"]) {
        case "article":
          {
            print('kind');
            articlesPostcollection.clear();
            articlesPostcollection.add(data['article']);
            print("hold${articlesPostcollection.length}");
            print('nobody');
            break;
          }
        default:
          {
            print('Unhandleddata type: ${data["type"]}');
            break;
          }
      }

      print("articles$articlesPostcollection");

      FeedDataModel2 feedDataModel2 = FeedDataModel2.fromJson(feed);

      feedDatacollection.clear();

      feedDatacollection.add(feedDataModel2);

      currenstState = HomeFeedProviderState.loaded;

      notifyListeners();
    } else {
      currenstState = HomeFeedProviderState.error;

      print("iconlistdatas${response.statusCode}");
      notifyListeners();
    }
  }
}

有人能帮助我开关条件,在控制台前开关语句打印,但内部开关语句没有执行,也为默认情况下,我已经创建了模型

ma8fv8wu

ma8fv8wu1#

您可以使用模型从API请求获取响应数据。
创建一个模型类,如下所示,(可以随意命名,例如ArticleModel.dart)

// To parse this JSON data, do
//
//     final articleModel = articleModelFromJson(jsonString);

import 'dart:convert';

List<ArticleModel> articleModelFromJson(String str) => List<ArticleModel>.from(json.decode(str).map((x) => ArticleModel.fromJson(x)));

String articleModelToJson(List<ArticleModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ArticleModel {
    ArticleModel({
        this.type,
        this.data,
    });

    String? type;
    Data? data;

    factory ArticleModel.fromJson(Map<String, dynamic> json) => ArticleModel(
        type: json["type"],
        data: json["data"] == null ? null : Data.fromJson(json["data"]),
    );
}

class Data {
    Data({
        this.postId,
        this.thumbnailImage,
        this.count,
        this.title,
        this.content,
        this.permalink,
        this.slug,
        this.categoryName,
        this.categorySlug,
        this.weekCategoryName,
        this.weekCategorySlug,
        this.specialCategoryName,
        this.specialCategorySlug,
        this.childSafetyCategoryName,
        this.childSafetyCategorySlug,
        this.lifeSkillsCategoryName,
        this.lifeSkillsCategorySlug,
        this.postTagName,
        this.postTagSlug,
    });

    int? postId;
    String? thumbnailImage;
    int? count;
    String? title;
    String? content;
    String? permalink;
    String? slug;
    String? categoryName;
    String? categorySlug;
    String? weekCategoryName;
    String? weekCategorySlug;
    String? specialCategoryName;
    String? specialCategorySlug;
    String? childSafetyCategoryName;
    String? childSafetyCategorySlug;
    String? lifeSkillsCategoryName;
    String? lifeSkillsCategorySlug;
    String? postTagName;
    String? postTagSlug;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        postId: json["post_id"],
        thumbnailImage: json["thumbnail_image"],
        count: json["count"],
        title: json["Title"],
        content: json["content"],
        permalink: json["permalink"],
        slug: json["slug"],
        categoryName: json["categoryName"],
        categorySlug: json["categorySlug"],
        weekCategoryName: json["week_category_name"],
        weekCategorySlug: json["week_category_slug"],
        specialCategoryName: json["special_category_name"],
        specialCategorySlug: json["special_category_slug"],
        childSafetyCategoryName: json["child_safety_category_name"],
        childSafetyCategorySlug: json["child_safety_category_slug"],
        lifeSkillsCategoryName: json["life_skills_category_name"],
        lifeSkillsCategorySlug: json["life_skills_category_slug"],
        postTagName: json["post_tag_name"],
        postTagSlug: json["post_tag_slug"],
    );
}

现在创建一个变量,在其中存储所有响应。

var articleModel = ArticleModel();

现在使用此模型获取响应,如下所示,

final result = jsonDecode(data); // if you're using a RestAPI
articleModel = ArticleModel.fromJson(result);

现在使用articleModel.(这里的键名)获取您想要或喜欢对数据做的任何事情。
例如,在您的情况下,您希望访问类型文章。

print(articleModel[0].type); // prints the type of value at first first 
index which is "Article".

相关问题