【问题标题】:FromJson return null , flutterFromJson 返回 null ,颤动
【发布时间】:2021-04-28 17:14:45
【问题描述】:

我有这个模型

class Meal {
  Meal({
    this.strMeal,
    this.strMealThumb,
    this.idMeal,
  });

  String strMeal;
  String strMealThumb;
  String idMeal;

  factory Meal.fromJson(Map<String, dynamic> json) => Meal(
    strMeal: json["strMeal"],
    strMealThumb: json["strMealThumb"],
    idMeal: json["idMeal"],
  );

}

在 Flutter 上的 HTTP 包的帮助下,我提出了这个请求:

class RemoteServices {
  static var client = http.Client();

  static Future<Meal> fetchMealById(String id) async {
    var response = await client
        .get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
    if (response.statusCode == 200) {
        var jasonStr = response.body;
        print("f" + jasonStr);
        Meal  meal = Meal.fromJson(json.decode(response.body));

        print(meal.idMeal);
    
    } else {
      throw Exception("Unable to  Load");
    }
  }
} 

解码响应后我得到一个 Null 值,尽管解码前的响应正文不是 null 并且包含一个保存我的数据的对象

【问题讨论】:

    标签: json flutter http dart


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    从您的网址返回的数据是 List&lt;Meal&gt; 而不是 Meal
    您可以参考完整代码中的模型详细信息
    代码sn-p

    Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
    
    class Payload {
      Payload({
        this.meals,
      });
    
      List<Meal> meals;
    ...
    static Future<List<Meal>> fetchMealById(String id) async {
        print(id);
        var response = await client
            .get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
        if (response.statusCode == 200) {
          var jasonStr = response.body;
          print("f" + jasonStr);
          Payload payload = payloadFromJson(response.body);      
          return payload.meals;
    ...   
     FutureBuilder(
                future: _future("yourId"),
                builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                      return Text('none');
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator());
                    case ConnectionState.active:
                      return Text('');
                    case ConnectionState.done:
                      if (snapshot.hasError) {
                        return Text(
                          '${snapshot.error}',
                          style: TextStyle(color: Colors.red),
                        );
                      } else {
                        print(snapshot.data.runtimeType);
                        return ListView.builder(
                            itemCount: snapshot.data.length,
                            itemBuilder: (context, index) {
                              return Card(
                                  elevation: 6.0,
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        top: 6.0,
                                        bottom: 6.0,
                                        left: 8.0,
                                        right: 8.0),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                            snapshot.data[index].idMeal.toString()),      
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
    
    String payloadToJson(Payload data) => json.encode(data.toJson());
    
    class Payload {
      Payload({
        this.meals,
      });
    
      List<Meal> meals;
    
      factory Payload.fromJson(Map<String, dynamic> json) => Payload(
            meals: json["meals"] == null
                ? null
                : List<Meal>.from(json["meals"].map((x) => Meal.fromJson(x))),
          );
    
      Map<String, dynamic> toJson() => {
            "meals": meals == null
                ? null
                : List<dynamic>.from(meals.map((x) => x.toJson())),
          };
    }
    
    class Meal {
      Meal({
        this.idMeal,
        this.strMeal,
        this.strDrinkAlternate,
        this.strCategory,
        this.strArea,
        this.strInstructions,
        this.strMealThumb,
        this.strTags,
        this.strYoutube,
        this.strIngredient1,
        this.strIngredient2,
        this.strIngredient3,
        this.strIngredient4,
        this.strIngredient5,
        this.strIngredient6,
        this.strIngredient7,
        this.strIngredient8,
        this.strIngredient9,
        this.strIngredient10,
        this.strIngredient11,
        this.strIngredient12,
        this.strIngredient13,
        this.strIngredient14,
        this.strIngredient15,
        this.strIngredient16,
        this.strIngredient17,
        this.strIngredient18,
        this.strIngredient19,
        this.strIngredient20,
        this.strMeasure1,
        this.strMeasure2,
        this.strMeasure3,
        this.strMeasure4,
        this.strMeasure5,
        this.strMeasure6,
        this.strMeasure7,
        this.strMeasure8,
        this.strMeasure9,
        this.strMeasure10,
        this.strMeasure11,
        this.strMeasure12,
        this.strMeasure13,
        this.strMeasure14,
        this.strMeasure15,
        this.strMeasure16,
        this.strMeasure17,
        this.strMeasure18,
        this.strMeasure19,
        this.strMeasure20,
        this.strSource,
        this.dateModified,
      });
    
      String idMeal;
      String strMeal;
      dynamic strDrinkAlternate;
      String strCategory;
      String strArea;
      String strInstructions;
      String strMealThumb;
      String strTags;
      String strYoutube;
      String strIngredient1;
      String strIngredient2;
      String strIngredient3;
      String strIngredient4;
      String strIngredient5;
      String strIngredient6;
      String strIngredient7;
      String strIngredient8;
      String strIngredient9;
      String strIngredient10;
      String strIngredient11;
      String strIngredient12;
      String strIngredient13;
      String strIngredient14;
      String strIngredient15;
      dynamic strIngredient16;
      dynamic strIngredient17;
      dynamic strIngredient18;
      dynamic strIngredient19;
      dynamic strIngredient20;
      String strMeasure1;
      String strMeasure2;
      String strMeasure3;
      String strMeasure4;
      String strMeasure5;
      String strMeasure6;
      String strMeasure7;
      String strMeasure8;
      String strMeasure9;
      String strMeasure10;
      String strMeasure11;
      String strMeasure12;
      String strMeasure13;
      String strMeasure14;
      String strMeasure15;
      dynamic strMeasure16;
      dynamic strMeasure17;
      dynamic strMeasure18;
      dynamic strMeasure19;
      dynamic strMeasure20;
      dynamic strSource;
      dynamic dateModified;
    
      factory Meal.fromJson(Map<String, dynamic> json) => Meal(
            idMeal: json["idMeal"] == null ? null : json["idMeal"],
            strMeal: json["strMeal"] == null ? null : json["strMeal"],
            strDrinkAlternate: json["strDrinkAlternate"],
            strCategory: json["strCategory"] == null ? null : json["strCategory"],
            strArea: json["strArea"] == null ? null : json["strArea"],
            strInstructions:
                json["strInstructions"] == null ? null : json["strInstructions"],
            strMealThumb:
                json["strMealThumb"] == null ? null : json["strMealThumb"],
            strTags: json["strTags"] == null ? null : json["strTags"],
            strYoutube: json["strYoutube"] == null ? null : json["strYoutube"],
            strIngredient1:
                json["strIngredient1"] == null ? null : json["strIngredient1"],
            strIngredient2:
                json["strIngredient2"] == null ? null : json["strIngredient2"],
            strIngredient3:
                json["strIngredient3"] == null ? null : json["strIngredient3"],
            strIngredient4:
                json["strIngredient4"] == null ? null : json["strIngredient4"],
            strIngredient5:
                json["strIngredient5"] == null ? null : json["strIngredient5"],
            strIngredient6:
                json["strIngredient6"] == null ? null : json["strIngredient6"],
            strIngredient7:
                json["strIngredient7"] == null ? null : json["strIngredient7"],
            strIngredient8:
                json["strIngredient8"] == null ? null : json["strIngredient8"],
            strIngredient9:
                json["strIngredient9"] == null ? null : json["strIngredient9"],
            strIngredient10:
                json["strIngredient10"] == null ? null : json["strIngredient10"],
            strIngredient11:
                json["strIngredient11"] == null ? null : json["strIngredient11"],
            strIngredient12:
                json["strIngredient12"] == null ? null : json["strIngredient12"],
            strIngredient13:
                json["strIngredient13"] == null ? null : json["strIngredient13"],
            strIngredient14:
                json["strIngredient14"] == null ? null : json["strIngredient14"],
            strIngredient15:
                json["strIngredient15"] == null ? null : json["strIngredient15"],
            strIngredient16: json["strIngredient16"],
            strIngredient17: json["strIngredient17"],
            strIngredient18: json["strIngredient18"],
            strIngredient19: json["strIngredient19"],
            strIngredient20: json["strIngredient20"],
            strMeasure1: json["strMeasure1"] == null ? null : json["strMeasure1"],
            strMeasure2: json["strMeasure2"] == null ? null : json["strMeasure2"],
            strMeasure3: json["strMeasure3"] == null ? null : json["strMeasure3"],
            strMeasure4: json["strMeasure4"] == null ? null : json["strMeasure4"],
            strMeasure5: json["strMeasure5"] == null ? null : json["strMeasure5"],
            strMeasure6: json["strMeasure6"] == null ? null : json["strMeasure6"],
            strMeasure7: json["strMeasure7"] == null ? null : json["strMeasure7"],
            strMeasure8: json["strMeasure8"] == null ? null : json["strMeasure8"],
            strMeasure9: json["strMeasure9"] == null ? null : json["strMeasure9"],
            strMeasure10:
                json["strMeasure10"] == null ? null : json["strMeasure10"],
            strMeasure11:
                json["strMeasure11"] == null ? null : json["strMeasure11"],
            strMeasure12:
                json["strMeasure12"] == null ? null : json["strMeasure12"],
            strMeasure13:
                json["strMeasure13"] == null ? null : json["strMeasure13"],
            strMeasure14:
                json["strMeasure14"] == null ? null : json["strMeasure14"],
            strMeasure15:
                json["strMeasure15"] == null ? null : json["strMeasure15"],
            strMeasure16: json["strMeasure16"],
            strMeasure17: json["strMeasure17"],
            strMeasure18: json["strMeasure18"],
            strMeasure19: json["strMeasure19"],
            strMeasure20: json["strMeasure20"],
            strSource: json["strSource"],
            dateModified: json["dateModified"],
          );
    
      Map<String, dynamic> toJson() => {
            "idMeal": idMeal == null ? null : idMeal,
            "strMeal": strMeal == null ? null : strMeal,
            "strDrinkAlternate": strDrinkAlternate,
            "strCategory": strCategory == null ? null : strCategory,
            "strArea": strArea == null ? null : strArea,
            "strInstructions": strInstructions == null ? null : strInstructions,
            "strMealThumb": strMealThumb == null ? null : strMealThumb,
            "strTags": strTags == null ? null : strTags,
            "strYoutube": strYoutube == null ? null : strYoutube,
            "strIngredient1": strIngredient1 == null ? null : strIngredient1,
            "strIngredient2": strIngredient2 == null ? null : strIngredient2,
            "strIngredient3": strIngredient3 == null ? null : strIngredient3,
            "strIngredient4": strIngredient4 == null ? null : strIngredient4,
            "strIngredient5": strIngredient5 == null ? null : strIngredient5,
            "strIngredient6": strIngredient6 == null ? null : strIngredient6,
            "strIngredient7": strIngredient7 == null ? null : strIngredient7,
            "strIngredient8": strIngredient8 == null ? null : strIngredient8,
            "strIngredient9": strIngredient9 == null ? null : strIngredient9,
            "strIngredient10": strIngredient10 == null ? null : strIngredient10,
            "strIngredient11": strIngredient11 == null ? null : strIngredient11,
            "strIngredient12": strIngredient12 == null ? null : strIngredient12,
            "strIngredient13": strIngredient13 == null ? null : strIngredient13,
            "strIngredient14": strIngredient14 == null ? null : strIngredient14,
            "strIngredient15": strIngredient15 == null ? null : strIngredient15,
            "strIngredient16": strIngredient16,
            "strIngredient17": strIngredient17,
            "strIngredient18": strIngredient18,
            "strIngredient19": strIngredient19,
            "strIngredient20": strIngredient20,
            "strMeasure1": strMeasure1 == null ? null : strMeasure1,
            "strMeasure2": strMeasure2 == null ? null : strMeasure2,
            "strMeasure3": strMeasure3 == null ? null : strMeasure3,
            "strMeasure4": strMeasure4 == null ? null : strMeasure4,
            "strMeasure5": strMeasure5 == null ? null : strMeasure5,
            "strMeasure6": strMeasure6 == null ? null : strMeasure6,
            "strMeasure7": strMeasure7 == null ? null : strMeasure7,
            "strMeasure8": strMeasure8 == null ? null : strMeasure8,
            "strMeasure9": strMeasure9 == null ? null : strMeasure9,
            "strMeasure10": strMeasure10 == null ? null : strMeasure10,
            "strMeasure11": strMeasure11 == null ? null : strMeasure11,
            "strMeasure12": strMeasure12 == null ? null : strMeasure12,
            "strMeasure13": strMeasure13 == null ? null : strMeasure13,
            "strMeasure14": strMeasure14 == null ? null : strMeasure14,
            "strMeasure15": strMeasure15 == null ? null : strMeasure15,
            "strMeasure16": strMeasure16,
            "strMeasure17": strMeasure17,
            "strMeasure18": strMeasure18,
            "strMeasure19": strMeasure19,
            "strMeasure20": strMeasure20,
            "strSource": strSource,
            "dateModified": dateModified,
          };
    }
    
    class RemoteServices {
      static var client = http.Client();
    
      static Future<List<Meal>> fetchMealById(String id) async {
        print(id);
        var response = await client
            .get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
        if (response.statusCode == 200) {
          var jasonStr = response.body;
          print("f" + jasonStr);
          Payload payload = payloadFromJson(response.body);
          //Meal  meal = Meal.fromJson(json.decode(response.body));
          print(payload.meals.length);
          print(payload.meals);
          return payload.meals;
        } else {
          throw Exception("Unable to  Load");
        }
      }
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          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> {
      Function _future;
    
      @override
      void initState() {
        _future = RemoteServices.fetchMealById;
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: FutureBuilder(
                future: _future("yourId"),
                builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                      return Text('none');
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator());
                    case ConnectionState.active:
                      return Text('');
                    case ConnectionState.done:
                      if (snapshot.hasError) {
                        return Text(
                          '${snapshot.error}',
                          style: TextStyle(color: Colors.red),
                        );
                      } else {
                        print(snapshot.data.runtimeType);
                        return ListView.builder(
                            itemCount: snapshot.data.length,
                            itemBuilder: (context, index) {
                              return Card(
                                  elevation: 6.0,
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        top: 6.0,
                                        bottom: 6.0,
                                        left: 8.0,
                                        right: 8.0),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                            snapshot.data[index].idMeal.toString()),
                                        Spacer(),
                                        Text(
                                          snapshot.data[index].strCategory,
                                        ),
                                      ],
                                    ),
                                  ));
                            });
                      }
                  }
                }));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      相关资源
      最近更新 更多