Flutter Future<void> async无法更改外部变量
写猜歌游戏时,遇到的问题。
原代码如下:
class _HomeState extends State<Home> {
List<dynamic> playlists = [];
Future<void> getData() async {
final response = await http.post(
Uri.parse('https://example.com/api.php'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8'
}
);
if (response.statusCode == 200) {
// 重点部分
playlists = jsonDecode(response.body)['data'];
} else {
// 重点部分
setState((){
playlists = [{"id": 0, "title": "error"}];
});
print(response.body);
}
}
然后在Scaffold中使用时就会发现playlists仍然是空白(没有被更改)。错误出在async更改变量要setState(所以要extend StatefulWidget)。代码更改后如下
class _HomeState extends State<Home> {
List<dynamic> playlists = [];
Future<void> getData() async {
final response = await http.post(
Uri.parse('https://example.com/api.php'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8'
}
);
if (response.statusCode == 200) {
// 重点部分
setState((){
playlists = jsonDecode(response.body)['data'];
});
}else {
// 重点部分
setState((){
playlists = [{"id": 0, "title": "error"}];
});
}
}