【问题标题】:check if value exists inside Json response flutter检查 Json 响应颤动中是否存在值
【发布时间】:2020-02-22 05:08:23
【问题描述】:

我提出了一个Json 发布请求并得到如下回复:

[{id: 13, mentor_id: 5, mentee_id: 184, status: null, session_count: 0, current_job: null, email: null, phone_call: null, video_call: null, face_to_face: null, created_at: 2020-02-20 20:37:50, updated_at: 2020-02-20 20:37:50}, {id: 14, mentor_id: 8, mentee_id: 184, status: null, session_count: 0, current_job: null, email: null, phone_call: null, video_call: null, face_to_face: null, created_at: 2020-02-21 22:39:31, updated_at: 2020-02-21 22:39:31}]

现在,我想检查id 键是否等于某个数字,以便设置按钮的状态。例如:

if(id contains 5){
....
}

我如何在颤振中实现这一点?

【问题讨论】:

    标签: json flutter arraylist


    【解决方案1】:

    我看过你的json并写了一些代码,只是为了让你知道我已经在本地加载了你的json。

    [
        {
            "id": 13,
            "mentor_id": 5,
            "mentee_id": 184,
            "status": null,
            "session_count": 0,
            "current_job": null,
            "email": null,
            "phone_call": null,
            "video_call": null,
            "face_to_face": null,
            "created_at": "2020- 02 - 20 20: 37: 50",
            "updated_at": "2020- 02 - 20 20: 37: 50"
        },
        {
            "id": 14,
            "mentor_id": 8,
            "mentee_id": 184,
            "status": null,
            "session_count": 0,
            "current_job": null,
            "email": null,
            "phone_call": null,
            "video_call": null,
            "face_to_face": null,
            "created_at": "2020- 02 - 21 22: 39: 31",
            "updated_at": "2020- 02 - 21 22: 39: 31"
        }
    ]
    

    上面是你的 JSON 文件

    // To parse this JSON data, do
    //
    //     final yourDataModel = yourDataModelFromJson(jsonString);
    
    import 'dart:convert';
    
    List<YourDataModel> yourDataModelFromJson(String str) => List<YourDataModel>.from(json.decode(str).map((x) => YourDataModel.fromJson(x)));
    
    String yourDataModelToJson(List<YourDataModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class YourDataModel {
        int id;
        int mentorId;
        int menteeId;
        dynamic status;
        int sessionCount;
        dynamic currentJob;
        dynamic email;
        dynamic phoneCall;
        dynamic videoCall;
        dynamic faceToFace;
        String createdAt;
        String updatedAt;
    
        YourDataModel({
            this.id,
            this.mentorId,
            this.menteeId,
            this.status,
            this.sessionCount,
            this.currentJob,
            this.email,
            this.phoneCall,
            this.videoCall,
            this.faceToFace,
            this.createdAt,
            this.updatedAt,
        });
    
        factory YourDataModel.fromJson(Map<String, dynamic> json) => YourDataModel(
            id: json["id"],
            mentorId: json["mentor_id"],
            menteeId: json["mentee_id"],
            status: json["status"],
            sessionCount: json["session_count"],
            currentJob: json["current_job"],
            email: json["email"],
            phoneCall: json["phone_call"],
            videoCall: json["video_call"],
            faceToFace: json["face_to_face"],
            createdAt: json["created_at"],
            updatedAt: json["updated_at"],
        );
    
        Map<String, dynamic> toJson() => {
            "id": id,
            "mentor_id": mentorId,
            "mentee_id": menteeId,
            "status": status,
            "session_count": sessionCount,
            "current_job": currentJob,
            "email": email,
            "phone_call": phoneCall,
            "video_call": videoCall,
            "face_to_face": faceToFace,
            "created_at": createdAt,
            "updated_at": updatedAt,
        };
    }
    
    

    这是我为你的 json 制作的模型类

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:sample_project_for_api/model.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      bool _isLoading = false;
    
      @override
      void initState() {
        super.initState();
        loadYourData();
      }
    
      Future<String> loadFromAssets() async {
        return await rootBundle.loadString('json/parse.json');
      }
    
      loadYourData() async {
        String jsonString = await loadFromAssets();
        final yourDataModel = yourDataModelFromJson(jsonString);
    
        for (int i = 0; i < yourDataModel.length; i++) {
          if (yourDataModel[i].id == 13) {
            print('you got your id');
            // Do your stuff
          }
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(),
        );
      }
    }
    
    

    这是 loadYourData 方法执行核心部分的主文件。

    让我知道它是否有效。

    【讨论】:

      【解决方案2】:

      你需要了解更多关于 Dart 语言中的Maps。 Flutter 只是一个制作跨平台应用的框架,它背后的语言和你写的逻辑都是 Dart 语言。

      
      
      
      //You have a list of data, so first put it in a List variable.
      //You need to first convert the list of raw json objects text response into a list of Maps.
      List<Map> data = jsonDecode(httpResponse.body);
      
      //Here we loop through the elements of the list
      for (Map jsonObject in data) {
      
         //This is how you get a value from a Map.
         int id = jsonObject["id"];
      
         if (jsonObject["id"] == 5){
            print("ID is 5.");
         } else {
            print("ID is NOT 5.");
         }
      
      }
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2022-07-12
        • 1970-01-01
        • 2012-06-23
        相关资源
        最近更新 更多