json 服务器API的数据未使用flutter显示

lb3vh1jj  于 2022-12-01  发布在  Flutter
关注(0)|答案(1)|浏览(147)

我是flutter的新手,我正在尝试在屏幕上显示服务器的响应。我正在尝试从服务器API获取数据,数据正在从服务器成功获取,但问题是数据无法显示。
我没有显示API的数据和服务器请求的经验,所以我不知道如何显示它。
这是我的模特

class Food {
  late int id;
  late String title;
  late String img_id;
  late int user_id;
  late int views;
  late String bahan;
  late String create;
  late String update;
  late String user;

  Food(
      {required this.id,
      required this.title,
      required this.img_id,
      required this.user_id,
      required this.views,
      required this.bahan,
      required this.create,
      required this.update,
      required this.user});

  factory Food.fromJson(Map<String, dynamic> json) {
    return Food(
        id: json['id'],
        title: json['title'],
        img_id: json['img_id'],
        user_id: json['user_id'],
        views: json['views'],
        bahan: json['bahan'],
        create: json['create'],
        update: json['update'],
        user: json['user']);
  }
}

这是我用来调用api的类

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'package:project/model/food.dart';

class FoodProvider extends ChangeNotifier {
  Future<Food> getFood() async {
    var result = await http.get(
      Uri.parse('http://sweetreats.herokuapp.com/api/recipe'),
    );

    print(result.statusCode);

    if (result.statusCode == 200) {
      // List data = json.decode(result.body);
      // List<Food> foods = data.map((item) => Food.fromJson(item)) as List<Food>;
      // return foods;
      return Food.fromJson(jsonDecode(result.body));
    } else {
      throw Exception();
    }
  }
}

这是我显示数据的方式

FutureBuilder<Food>(
                      future: foodProvider.getFood(),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          List? data = snapshot.data as List?;

                          int index = 0;

                          return Column(
                              children: data!.map((item) {
                            index++;
                            return Container(
                              margin: EdgeInsets.only(
                                top: index == 1 ? 0 : 30,
                              ),
                              child: FoodItem(food: item),
                            );
                          }).toList());
                        }
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      }),
kwvwclae

kwvwclae1#

型号变更

class Food {
  final int? id;
  final String? title;
  final String? img_id;
  final int? user_id;
  final String? views;
  final String? bahan;
  final String? create;
  final String? update;
  final String? user;

  Food({
    required this.id,
    required this.title,
    required this.img_id,
    required this.user_id,
    required this.views,
    required this.bahan,
    required this.create,
    required this.update,
    required this.user,
  });

  factory Food.fromJson(Map<String, dynamic> json) {
    return Food(
      id: json['id'],
      title: json['title'],
      img_id: json['img_id'],
      user_id: json['user_id'],
      views: json['views'],
      bahan: json['bahan'],
      create: json['create'],
      update: json['update'],
      user: json['user'],
    );
  }
}

提供者变更

class FoodProvider extends ChangeNotifier {
  Future<List<Food>> getFood() async {
    try {
      var result = await http.get(
        Uri.parse('http://sweetreats.herokuapp.com/api/recipe'),
      );

      if (result.statusCode != 200) {
        throw result.body;
      }
      final data = json.decode(result.body);
      return List<Food>.from(
        data['recipes'].map((e) => Food.fromJson(e)).toList(),
      );
    } catch (_) {
      rethrow;
    }
  }
}

UI变更

FutureBuilder<List<Food>>(
          future: FoodProvider().getFood(),
          builder: (context, AsyncSnapshot<List<Food>> snapshot) {
            if (snapshot.hasError) {
              return Center(
                child: Text('Something went wrong ${snapshot.error}'),
              );
            } else if (snapshot.hasData) {
              // return ListView.builder(itemBuilder: (_, i) {}, itemCount: snapshot.data.,)
              List? data = snapshot.data;

              int index = 0;

              return Column(
                  children: data!.map((item) {
                index++;
                return Container(
                  margin: EdgeInsets.only(top: index == 1 ? 0 : 30),
                  child: Text(item.title ?? ''),
                );
              }).toList());
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ),

相关问题