我是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(),
);
}),
1条答案
按热度按时间kwvwclae1#
型号变更
提供者变更
UI变更