Flutter下拉菜单与API结合使用时会在Future中导致错误 [英] Flutter drop down causes error in Future while using it with API
问题描述
我对扑扑很陌生.我正在使用将数据作为JSON发送到的API.JSON的格式在这里.
I'm very new to flutter. I'm using an API to which sends the data as an JSON. The format of the JSON is here.
[
{
"store": "AMAZON"
},
{
"store": "FLIPKART"
},
{
"store": "WALMART"
},
{
"store": "ALIBABA"
},
]
我需要在下拉按钮中使用此存储值.一共有三个文件dataRetrieve.dart,homePage.dart,main.dart.main.dart指向homePage.dart
I need to use this store values in a drop down button. There are three files dataRetrieve.dart, homePage.dart, main.dart. main.dart Points to homePage.dart
homePage.dart的初始化状态调用dataRetrieve.dart进行发布请求以获取数据.homePage.dart的代码在这里.
homePage.dart's init state call dataRetrieve.dart to make a post request to get the data. The code of homePage.dart is here.
var markets;
String _mySelection;
@override
void initState() {
super.initState();
setState(() {
markets = retrievedata.getMarket();
});
}
在homePage.dart中,我有一个下拉按钮,代码在这里.
In homePage.dart I have dropdown button and the code is here.
child: DropdownButton(
items: stores,
onChanged: (sto) {
setState(() {
_mySelection = sto;
});
},
value: _mySelection,
hint: Text('Please select the store: '),
),
data.Retrieve.dart代码在这里.
The data.Retrieve.dart code is here.
import 'dart:convert';
import 'package:http/http.dart';
class retrieveData {
getMarket() async {
String url;
Response response = await post(url);
var resp = json.decode(response.body);
List stores = List();
for (int i = 0; i < json.decode(response.body).length; i++) {
stores.add(resp[i]['store']);
}
return stores;
}
}
final retrieveData retrievedata = retrieveData();
main.dart文件在这里.
The main.dart file is here.
import 'package:agrimarket/homePage.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter App',
debugShowCheckedModeBanner: false,
home: homePage(),
);
}
}
尽管此代码会产生一些错误.错误在这里
While this code produces some error. The error is here
═╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following _TypeError was thrown building homePage(dirty, state: homePageState#8914c):
type 'Future<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>'
The relevant error-causing widget was:
homePage
lib\main.dart:14
When the exception was thrown, this was the stack:
我已经声明并分配了网址.
I have declared and assigned the URL.
如何使用下拉菜单中检索到的值.
How to use the retrieved value in dropdown.
推荐答案
完成费迪南德的回答在API未完成加载数据之前,请确保 stores
不剩余 null
.
To complete the Ferdinand's answer you to make sure that stores
is not remaining null
before API do not complete to load data.
为避免空异常,初始化 stores = [];
或检查此答案 https://stackoverflow.com/a/64894117/10663537
To avoid null exception initialize stores = [];
or check this answer https://stackoverflow.com/a/64894117/10663537
这篇关于Flutter下拉菜单与API结合使用时会在Future中导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!