FutureBuilder未填充值



在我的main.dart中,我有一个异步函数来从URL获取数据。

getShopLength() async {
final queryParameters = {
'api_key': '123',
'user_id': '123',
'lat': '123',
'long': '123',
'km': '123',
};
var response = await http.get(Uri.https('google.de','getSth', queryParameters));
var jsonData = jsonDecode(response.body);
List<Shops> shops = [];
for(var x in jsonData) {
Shops shop = Shops(x['name'], x['slogan']);
shops.add(shop);
}
return shops.length;
}

在我的home.dart中,我想从getShopLength()中获得值,但我总是得到错误:type 'Future<dynamic> is not a subtype of type 'Future<String>?'

我尝试将返回值保存到valueShop中,并将其传递给buildRestaurantRow('Top Angebote', context, valueShop)

home.dart

@override
Widget build(BuildContext context) {
var valueShop = "0";
FutureBuilder<String>(
future: getShopLength(),
builder: (context, snapshot) {
if (snapshot.hasData) {
valueShop = snapshot.data;
}
return CircularProgressIndicator();
}
);

return Scaffold(
appBar: buildSearchBar(context),
body: Padding(
padding: const EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: ListView(
children: <Widget>[
SizedBox(height: 20.0),
buildRestaurantRow('Top Angebote', context, valueShop),
SizedBox(height: 10.0),
buildRestaurantList(context),
SizedBox(height: 10.0),
buildCategoryRow('Nach Kategorie', context),
SizedBox(height: 10.0),
buildCategoryList(context),
SizedBox(height: 20.0),
buildCategoryRow('Deine Favoriten', context),
SizedBox(height: 10.0),
buildFriendsList(),
SizedBox(height: 30.0),
],
),
),
);
}

我错过了什么?

所以问题就在这里:

FutureBuilder<String>(
future: getShopLength(),

您的future生成器有一个字符串类型,这意味着future的类型应该是Future<String>,但当您声明函数getShopLength时,您执行了以下操作:

getShopLength() async {

您没有给它一个返回类型,因此,默认的返回类型是Future<dynamic>

显而易见的解决方案是给函数一个返回类型,但您还有另一个问题:

futurebuilder需要一个字符串值,但函数返回一个数字,那么它是哪个呢?

若你们想返回一个长度的字符串,你们可以这样做:

Future<String> getShopLength() async  {
...
return shops.length.toString();
}

或者,您也可以将futurebuilder的值更改为int:

Future<int> getShopLength() async  {
...
return shops.length;
}
...
int valueShop = 0;
FutureBuilder<int>(
future: getShopLength(),
builder: (context, snapshot) {
if (snapshot.hasData) {
valueShop = snapshot.data;
}
return CircularProgressIndicator();
},
);

旁注:

好吧,关于你的代码,我有几件事要提:首先,在你的getShopsLength函数上,你有两个列表,jsonDatashops,你实际上并不需要两者,你只需要使用一个:

var jsonData = jsonDecode(response.body);
return jsonData.length // no need for the shops list.

其次,你的构建器代码怎么了??您首先声明了一个FutureBuilder,但随后完全忽略它并转到Scaffold小部件?我相信脚手架代码应该在未来的构建器中,因为目前,你永远不会看到循环进度指示器:

发件人:

var valueShop = '0';
FutureBuilder<String>(
future: getShopLength(),
builder: (context, snapshot) {
if (snapshot.hasData) {
valueShop = snapshot.data;
}
return CircularProgressIndicator();
}
);
return Scaffold(...);

收件人:

return FutureBuilder<String>(
future: getShopLength(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var valueShop = snapshot.data;
return Scaffold(...);
}
return CircularProgressIndicator();
}
);

最新更新