它实际上是我之前的question的延续,在这里,我已经成功地使用从Get方法检索到的Json填充了列表。作为建议,我使用了futurebuilder小部件来构建我的Dropdownbutton。但我的问题是:我选择了下拉列表后,它无法显示任何内容。它崩溃了。
我还有其他事与我有关。我的项目是通过esp8266通过http GET方法接收附近的wifi扫描(然后使用POST方法通过应用发送密码)。我的问题是: 我在使用此Futurebuilder小部件时,此应用实际在哪个“时间”发出了HTTP请求?它会一直刷新吗?
我可以只在一种情况下填充dropdownmenuitem(也许处于初始化状态),然后仅在需要时才进行刷新(即使用按钮)。我一直在尝试这样做,但是一直失败。
这是我的代码
Future<List<Post>> getAllPosts(String url) async {
final response = await http.get(url);
return allPostsFromJson(response.body);
}
List<Post> allPostsFromJson(String str) {
final jsonData = json.decode(str);
return new List<Post>.from(jsonData.map((x) => Post.fromJson(x)));
}
class Post {
String name;
String perc;
String pass;
Post({
this.name,
this.perc,
this.pass,
});
factory Post.fromJson(Map<String, dynamic> json) => new Post(
name: json["SSID"],
perc: json["RSSI"],
pass: json["PASS"],
);
Map<String, dynamic> toJson() => {
"SSID": name,
"RSSI": perc,
"PASS": pass,
};
}
class LoginPhaseState extends State<LoginPhase>{
Post selected;
final String uri = 'http://10.0.2.2/data/connection.json';
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Post>>(
future: getAllPosts(uri),
builder: (BuildContext context,
AsyncSnapshot<List<Post>> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return DropdownButton<Post>(
items: snapshot.data
.map((ssid) => DropdownMenuItem<Post>(
child: Text(ssid.name),
value: ssid,
))
.toList(),
onChanged: (Post value) {
setState(() {
selected = value;
});
},
isExpanded: false,
// value: selected,
hint: Text('Select User'),
);
});
}
}
答案 0 :(得分:0)
尝试一下
Future<List<Post>> getAllPosts(String url) async {
final response = await http.get(url);
return allPostsFromJson(response.body);
}
List<Post> allPostsFromJson(String str) {
final jsonData = json.decode(str);
return new List<Post>.from(jsonData.map((x) => Post.fromJson(x)));
}
class Post {
String name;
String perc;
String pass;
Post({
this.name,
this.perc,
this.pass,
});
factory Post.fromJson(Map<String, dynamic> json) => new Post(
name: json["SSID"],
perc: json["RSSI"],
pass: json["PASS"],
);
Map<String, dynamic> toJson() => {
"SSID": name,
"RSSI": perc,
"PASS": pass,
};
}
class LoginPhaseState extends State<LoginPhase>{
Post selected;
final String uri = 'http://10.0.2.2/data/connection.json';
String _selectedChild= "";
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Post>>(
future: getAllPosts(uri),
builder: (BuildContext context,
AsyncSnapshot<List<Post>> snapshot) {
if (!snapshot.hasData)
return CircularProgressIndicator();
return DropdownButton<Post>(
value: _selectedChild == "" ? null : _selectedChild,
items: snapshot.data
.map((ssid) => DropdownMenuItem<Post>(
child: Text(ssid.name),
value: ssid,
))
.toList(),
onChanged: (Post value) {
setState(() {
_selectedChild = value.name;
selected = value;
});
},
isExpanded: false,
// value: selected,
hint: Text('Select User'),
);
});
}
}