gpt4 book ai didi

android - FutureBuilder 无法正常工作

转载 作者:IT王子 更新时间:2023-10-29 06:36:52 27 4
gpt4 key购买 nike

我正在从这里获取 json:https://api.myjson.com/bins/1g3xpe ,在我的 flutter 应用程序中。

这是代码(我已经删除了不相关的部分)。问题是,FutureBuilder 的构建器部分永远不会被调用。此行 debugPrint(snapshot.hasData.toString()); 永远不会被调用。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:nirmithi/objects/project.dart';
import 'dart:convert';

class Projects extends StatefulWidget {
@override
ProjectsState createState() => new ProjectsState();
}

class ProjectsState extends State<Projects> {
@override
Widget build(BuildContext context) {
return Scaffold(
primary: true,
appBar: EmptyAppBar(),
body: Column(
children: <Widget>[
headerWidget(),
Container(
child: futureBuilder(),
)
],
),
);
}

@override
void setState(fn) {
super.setState(fn);
}
}

Future<List<Project>> getData() async {
String getProjects = "https://api.myjson.com/bins/1g3xpe";

final response = await http.get(getProjects);

if (response.statusCode == 200) {
List responseJson = json.decode(response.body);
return responseJson.map((m) => Project.fromJson(m)).toList();
} else
throw Exception(response.toString());
}

Widget futureBuilder() {
FutureBuilder<List<Project>>(
future: getData(),
builder: (context, snapshot) {
debugPrint(snapshot.hasData.toString());
},
);

return Center(
child: CircularProgressIndicator(),
);
}


Widget listWidget(List<Project> data) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
listItem(data.elementAt(index));
},
);
}

Widget listItem(Project project) {

return Card(
elevation: 6.0,
child: Column(
children: <Widget>[Text(project.projectId), Text(project.projectName)],
),
);
}

class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
return Container();
}

@override
Size get preferredSize => Size(0.0, 0.0);
}

更新:这是我删除以进行调试的构建器部分中的代码。

switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return listWidget(snapshot.data);
}

最佳答案

您需要返回您的 FutureBuilder,以便它成为小部件树的一部分:

Widget futureBuilder() {
return FutureBuilder<List<Project>>(
future: getData(),
builder: (context, snapshot) {
// ...
},
);
}

简单地创建它的一个实例并不能解决 future 的问题。

关于android - FutureBuilder 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235378/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com