本文介绍了如何使用Flutter FutureBuilder构建Dropdownmenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Flutter中使用FutureBuilder构建下拉菜单,因为我正在从API获取json,我是flutter中的新手,所以我尝试了但我做不到这是我的代码
hi i want to build dropdown menu using FutureBuilder in Flutter because i'm fetching json from API, I'm new in flutter so i tried and i could not do ithere is my code
Future<Album> fetchAlbum() async {
final response = await http.get(
'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
class Album {
int count;
String message;
String searchCriteria;
List<Results> results;
Album({this.count, this.message, this.searchCriteria, this.results});
Album.fromJson(Map<String, dynamic> json) {
count = json['Count'];
message = json['Message'];
searchCriteria = json['SearchCriteria'];
if (json['Results'] != null) {
results = new List<Results>();
json['Results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
}
class Results {
int makeID;
String makeName;
int modelID;
String modelName;
Results({this.makeID, this.makeName, this.modelID, this.modelName});
Results.fromJson(Map<String, dynamic> json) {
makeID = json['Make_ID'];
makeName = json['Make_Name'];
modelID = json['Model_ID'];
modelName = json['Model_Name'];
}
}
我想为所有modelID建立一个DropDownMenuList
i want to build a DropDownMenuList for all modelID
谢谢
推荐答案
您可以在
下复制粘贴运行完整代码代码段
You can copy paste run full code below
code snippet
FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<Album> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return DropdownButton<Results>(
isExpanded: true,
items:
snapshot.data.results.map((Results dropDownStringItem) {
return DropdownMenuItem<Results>(
value: dropDownStringItem,
child: Text(dropDownStringItem.modelID.toString()),
);
}).toList(),
onChanged: (value) {
setState(() {
_selected = value;
});
},
value: _selected,
);
}
}
})
工作演示
完整代码
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Album {
int count;
String message;
String searchCriteria;
List<Results> results;
Album({this.count, this.message, this.searchCriteria, this.results});
Album.fromJson(Map<String, dynamic> json) {
count = json['Count'];
message = json['Message'];
searchCriteria = json['SearchCriteria'];
if (json['Results'] != null) {
results = [];
json['Results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
}
class Results {
int makeID;
String makeName;
int modelID;
String modelName;
Results({this.makeID, this.makeName, this.modelID, this.modelName});
Results.fromJson(Map<String, dynamic> json) {
makeID = json['Make_ID'];
makeName = json['Make_Name'];
modelID = json['Model_ID'];
modelName = json['Model_Name'];
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<Album> _future;
Results _selected;
Future<Album> fetchAlbum() async {
final response = await http.get(
'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
@override
void initState() {
_future = fetchAlbum();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<Album> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return DropdownButton<Results>(
isExpanded: true,
items:
snapshot.data.results.map((Results dropDownStringItem) {
return DropdownMenuItem<Results>(
value: dropDownStringItem,
child: Text(dropDownStringItem.modelID.toString()),
);
}).toList(),
onChanged: (value) {
setState(() {
_selected = value;
});
},
value: _selected,
);
}
}
}),
);
}
}
这篇关于如何使用Flutter FutureBuilder构建Dropdownmenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!