无法使用抖动中的对象预先填充下拉列表

问题描述 投票:0回答:1

我有一个下拉列表,其中填充了从API接收的对象。问题是当用户进行编辑时,我无法使用对象预填充下拉列表。

这里是示例JSON:

[{“ _ id”:“ 435463”,“ userId”:“ 3423423”,“ username”:“ ma”,“ categoryId”:“ 5656756”,“ insurerId”:“ 567544”,“ packageId”:“ 5675 “,” categoryName“:”车辆保险“,” insurerName“:” lic“,” packageName“:”家庭“},{” _id“:” 4564644“,” userId“:” 2342344“,” username“:” ma“,” categoryId“:” 6575744“,” insurerId“:” 567567“,” packageId“:” 3455“,” categoryName“:”人寿保险“,” insurerName“:” lic“,” packageName“:”家庭“}]

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'dart:convert';

UserPackages selectedPckg;
class AddOrEditClaim extends StatefulWidget {
  @override
  AddOrEditClaimState createState() => AddOrEditClaimState();
}

class AddOrEditClaimState extends State<AddOrEditClaim> {
  List<UserPackages> packageList = List();
  final formKey = GlobalKey<FormState>();

  @override
  void initState() {
        fetchPackages();
        selectedPckg= UserPackages();
        UserPackages packgToEdit = new UserPackages();
        packgToEdit.packageId="123";
        packgToEdit.packageName="family";
        selectedPckg=packgToEdit;

         super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
        appBar: AppBar(
          title: Text('Add Claim'),
        ),
        body:
            Form(
              key:formKey,
              child:ListView(
                  children: <Widget>[
                    new DropdownButton(
                      items: packageList.map((item) {
                        return new DropdownMenuItem<UserPackages>(
                          child: new Text(item.packageName),
                          value: item,
                        );
                      }).toList(),
                      onChanged: (newVal) {
                        setState(() {
                          selectedPckg = newVal;
                        });
                      },
                      value: selectedPckg,
                    ),
                  ])
            )

    );;
  }
   fetchPackages() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var resp = await http.get('http://localhost:3000/userPackage/getUserPackages/'+userId);
    setState(() {
      packageList= parsePackages(resp.body);
    });
  }

  List<UserPackages> parsePackages(String responseBody) {
    final parsedj = json.decode(responseBody);
    final parsed = parsedj.cast<Map<String, dynamic>>();
    return parsed.map<UserPackages>((json) => UserPackages.fromJson(json)).toList();
  }
}

这里是Userpackages类:

class UserPackages{
   String packageName;
   String packageId;
  UserPackages({this.packageName,this.packageId});
  factory UserPackages.fromJson(Map<String, dynamic> json){
    return UserPackages(
      packageId:json['packageId'] as String,
      packageName: json['packageName'] as String,
    );
  }
}

正在抛出以下内容

'package:flutter/src/material/dropdown.dart': Failed assertion: line 560 pos 15: 'items == null ||items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==value).length == 1': is not true.
json flutter dropdown flutter-layout
1个回答
0
投票

添加null / empty检查packageList。因为解决了packageList网络调用后fetchPackages被更新,所以将DropdownButton包裹在if块中,如下所示

Form(
    key:formKey,
    child:ListView(
        children: <Widget>[
          if(packageList.isNotEmpty){
          new DropdownButton(
            items: packageList.map((item) {
              return new DropdownMenuItem<UserPackages>(
                child: new Text(item.packageName),
                value: item,
              );
            }).toList(),
            onChanged: (newVal) {
              setState(() {
                selectedPckg = newVal;
              });
            },
            value: selectedPckg ?? packageList[0],
          ),
          }
        ])
  )

© www.soinside.com 2019 - 2024. All rights reserved.