简体   繁体   English

使用 Json 列表在 Flutter 中创建下拉列表

[英]Creating a dropdown in Flutter using a Json list

I am getting a Json list from an API and trying to put it into a dropdown for the users to select their customer.我从 API 获取 Json 列表并尝试将其放入下拉列表中,供用户选择他们的客户。

Json File json文件

 import 'dart:convert'; CustomerJson welcomeFromJson(String str) => CustomerJson.fromJson(json.decode(str)); String welcomeToJson(CustomerJson data) => json.encode(data.toJson()); class CustomerJson { CustomerJson({ this.customer, this.salesRep, this.userValues, this.terms, this.type, this.shipVia, this.salesCode, this.taxCode, this.name, this.emailAddress, this.url, this.status, this.shipLeadDays, this.printStatement, this.creditLimit, this.currBalance, // this.customerSince, this.acceptBo, this.pricingLevel, this.partner, this.currencyDef, this.noteText, this.lastUpdated, this.taxId, this.acctMgr, this.rating, this.qBId, this.psTId, this.sendReportByEmail, this.creditApproved, this.creditApprovedBy, this.creditApprovedDate, }); String? customer; String? salesRep; int? userValues; String? terms; String? type; String? shipVia; dynamic salesCode; dynamic taxCode; String? name; dynamic emailAddress; dynamic url; String? status; int? shipLeadDays; bool? printStatement; int? creditLimit; double? currBalance; // DateTime? customerSince; bool? acceptBo; dynamic pricingLevel; dynamic partner; int? currencyDef; dynamic noteText; DateTime? lastUpdated; dynamic taxId; String? acctMgr; int? rating; dynamic qBId; dynamic psTId; bool? sendReportByEmail; bool? creditApproved; dynamic creditApprovedBy; dynamic creditApprovedDate; factory CustomerJson.fromJson(Map<String, dynamic> json) => CustomerJson( customer: json["customer"], salesRep: json["sales_Rep"], userValues: json["user_Values"], terms: json["terms"], type: json["type"], shipVia: json["ship_Via"], salesCode: json["sales_Code"], taxCode: json["tax_Code"], name: json["name"], emailAddress: json["email_Address"], url: json["url"], status: json["status"], shipLeadDays: json["ship_Lead_Days"], printStatement: json["print_Statement"], creditLimit: json["credit_Limit"], currBalance: json["curr_Balance"], // customerSince: DateTime.parse(json["customer_Since"]), acceptBo: json["accept_BO"], pricingLevel: json["pricing_Level"], partner: json["partner"], currencyDef: json["currency_Def"], noteText: json["note_Text"], lastUpdated: DateTime.parse(json["last_Updated"]), taxId: json["tax_ID"], acctMgr: json["acct_Mgr"], rating: json["rating"], qBId: json["qB_ID"], psTId: json["psT_ID"], sendReportByEmail: json["send_Report_By_Email"], creditApproved: json["credit_Approved"], creditApprovedBy: json["credit_Approved_By"], creditApprovedDate: json["credit_Approved_Date"], ); Map<String, dynamic> toJson() => { "customer": customer, "sales_Rep": salesRep, "user_Values": userValues, "terms": terms, "type": type, "ship_Via": shipVia, "sales_Code": salesCode, "tax_Code": taxCode, "name": name, "email_Address": emailAddress, "url": url, "status": status, "ship_Lead_Days": shipLeadDays, "print_Statement": printStatement, "credit_Limit": creditLimit, "curr_Balance": currBalance, // "customer_Since": customerSince?.toIso8601String(), "accept_BO": acceptBo, "pricing_Level": pricingLevel, "partner": partner, "currency_Def": currencyDef, "note_Text": noteText, "last_Updated": lastUpdated?.toIso8601String(), "tax_ID": taxId, "acct_Mgr": acctMgr, "rating": rating, "qB_ID": qBId, "psT_ID": psTId, "send_Report_By_Email": sendReportByEmail, "credit_Approved": creditApproved, "credit_Approved_By": creditApprovedBy, "credit_Approved_Date": creditApprovedDate, }; }

API Call API 调用

 Future<List<CustomerJson>?> GetCustomerIDsCall(String APIKey) async { var headers = {'APIKey': APIKey}; var request = http.Request( 'GET', Uri.parse( 'http://65.254.144.50:5114/Customers')); request.headers.addAll(headers); final response = await request.send(); final String respStr = await response.stream.bytesToString(); final responseList = json.decode(respStr) as List; if (response.statusCode == 200) { CustomerIDs = responseList.map((Customer) => CustomerJson.fromJson(Customer)).toList(); return (CustomerIDs); } else { print(response.reasonPhrase); } }

DropdownButton Call下拉按钮调用

 Center( child: Container( width: 200, padding: const EdgeInsets.symmetric(vertical: 16), child: DropdownButtonHideUnderline( child: DropdownButton<dynamic>( value: CustomerID_value ?? CustomerIDs[0], hint: Text('Customer ID'), items: CustomerIDs.map<DropdownMenuItem<dynamic>>((value) => DropdownMenuItem(value: value,child: Text('${value["customer"]}'),)).toList(), onChanged: (value) => setState(() => CustomerID_value = value), ), ), ), ),

The Json file and API works as I am getting the information from it in another part of the program. Json 文件和 API 的工作原理是我在程序的另一部分从中获取信息。 I am just not sure as to what I am supposed to do with the Json List(CustomerIDs) to allow the dropdownbutton to read what I need to then display it.我只是不确定我应该如何处理 Json List(CustomerIDs) 以允许下拉按钮读取我需要然后显示它的内容。 I need to display CustomerIDs.customer within the dropdownbutton for users to select what customer they with to use within the form.我需要在下拉按钮中显示 CustomerIDs.customer,以便用户选择他们在表单中使用的客户。

CustomerID_value Initialization CustomerID_value 初始化

 class CreateUser extends StatefulWidget { const CreateUser({Key? key}) : super(key: key); @override State<CreateUser> createState() => _CreateUserState(); } class _CreateUserState extends State<CreateUser> { final emailController = TextEditingController(); final passwordController = TextEditingController(); final customerIDController = TextEditingController(); final roleController = TextEditingController(); final activityController = TextEditingController(); String? status_value; ***String? CustomerID_value;*** String? role_value; @override void dispose() { emailController.dispose(); passwordController.dispose(); customerIDController.dispose(); roleController.dispose(); activityController.dispose(); super.dispose(); }

CustomerIDs Initialization客户 ID 初始化

 late var CustomerIDs;

you can customize with items property of dropdown.您可以使用下拉菜单的 items 属性进行自定义。

DropdownButtonHideUnderline(
    child: DropdownButton<dynamic>(
        value: CustomerID_value ?? CustomerIDs[0],
        hint: Text('Customer ID'),
        items: CustomerIDs.map<DropdownMenuItem<dynamic>>(
            (value) => DropdownMenuItem(
                value: value,
                child: Text('${value["customer"]}'),
                      )).toList(),
        onChanged: (value) => setState(() => CustomerID_value = value)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM