我想从https://jsonplaceholder.typicode.com/posts调用json api,但是我的输出是“未来的实例”。
我显然希望正确的输出为1。检查链接以了解为什么应为1
getJson()与输出位于不同的.dart文件(但相同的项目)中。 我相信它工作正常(因为有输出)
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List> getJson() async {
String apiURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(apiURL);
return json.decode(response.body);
}
Future getData(int i, String place) async {
List _data = await getJson();
return _data[i][place];
}
那么输出是
Text("This is the output ${getData(0, "id")}"
这导致
"Instance of 'Future<dynamic>'"
答案 0 :(得分:0)
您需要等待回复 所以代替:
<div class="product_quantity_container">
<div class="product_quantity clearfix">
<span>Qty</span>
<input id="quantity_input" type="text" pattern="[0-9]*" value="1" name="quantity">
<div class="quantity_buttons">
<div id="quantity_inc_button" class="quantity_inc quantity_control"><i class="fa fa-chevron-up" aria-hidden="true"></i></div>
<div id="quantity_dec_button" class="quantity_dec quantity_control"><i class="fa fa-chevron-down" aria-hidden="true"></i></div>
</div>
</div>
<div class="button cart_button"><a type="submit" href="{% url 'online:cartitemcreate' pk=prod.pk %}">Add to cart</a></div>
</div
您需要这样做:
Text("This is the output ${getData(0, "id")}"
答案 1 :(得分:0)
您可以将Text
包裹在FutureBuilder
内-这样:
FutureBuilder(builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) return Text("This is the output ${snapshot.data}");
else return Text("There is no output yet");
}, future: getData(0, 'id'),);