您好,我尝试根据我的flutter网站项目的API数据创建一个元素的listView。每次尝试时,页面上都没有显示任何结果。我本应显示法国部门的ListView;我拼命尝试在页面上使用更基本的代码。因此,我尝试使用比我的代码更简单的代码来查看其工作原理,但仍然没有结果(appBar下的空白页面)。我认为我不太了解该如何工作,但是我找到了一个教程,其中包含一个来自API数据的元素的随机ListView示例代码;但这还是行不通的,我有点紧张...此代码是否有问题?我可以进一步说明如何从API获取数据并将其显示在Flutter的ListView上吗?谢谢大家的帮助
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
const baseUrl = "https://jsonplaceholder.typicode.com";
class API {
static Future getUsers() {
var url = baseUrl + "/users";
return http.get(url);
}
}
class User {
int id;
String name;
String email;
User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
User.fromJson(Map json)
: id = json['id'],
name = json['name'],
email = json['email'];
Map toJson() {
return {'id': id, 'name': name, 'email': email};
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Http App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}
class MyListScreen extends StatefulWidget {
@override
createState() => _MyListScreenState();
}
class _MyListScreenState extends State {
var users = new List<User>();
_getUsers() {
API.getUsers().then((response) {
setState(() {
Iterable list = json.decode(response.body);
users = list.map((model) => User.fromJson(model)).toList();
});
});
}
initState() {
super.initState();
_getUsers();
}
dispose() {
super.dispose();
}
@override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("User List"),
),
body: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(title: Text(users[index].name));
},
));
}
}
答案 0 :(得分:0)
尝试使用异步并在getUsers上等待:
static Future getUsers() async {
var url = baseUrl + "/users";
return await http.get(url);
}
答案 1 :(得分:0)
我已经测试了您的代码,一切正常,您只需要添加一个ProgressIndicator。 注意事项:
对于当前的实现,请进行以下修改:
初始化加载
class _MyListScreenState扩展了状态{ var users = new List(); bool _isLoading = true;
2。加载完成后更新状态
wwwroot
3。在您的构建方法中添加小部件
[HttpGet]
[Route("~/FutureFills")]
[Produces("text/csv")]
public IActionResult ExportFile()
{
var futurefills = _context.Prescriptions
.Where(f => f.FolderStatusId == 9)
.Where(d => d.DeliveryDate == DateTime.Today.AddDays(1))
.ToList();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.IO.StreamWriter write = new System.IO.StreamWriter(Stream);
CsvFileDescription file = new CsvFileDescription
{
SeparatorChar = ',', FirstLineHasColumnNames = true
};
return File(System.Text.Encoding.ASCII.GetBytes(futurefills.ToString()), "text/csv", "FutureFills.csv");
}