dart 在下拉按钮表单字段中列出数据

4ktjp1zp  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(74)

我无法在DropdownButtonFormField中列出数据。我的列表类型为ScheduleModel,而DropdownButtonFormField需要String类型,我不知道如何执行此转换。我收到的错误是“状态错误:没有元素”。
产品_屏幕.dart

GetBuilder<ProductController>(builder: (controller) {

  return DropdownButtonFormField<String>(
    isDense: true,
    decoration: InputDecoration(
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(width: 1, color: Colors.grey),
        )
    ),
    value: controller.allSchedule.first.date.toString(),
    items: controller.allSchedule.map((item) => DropdownMenuItem<String>(
      value: item.date.toString(),
      child: Text(item.date.toString()),
    )).toList(),
    onChanged: (value) => setState(() => this.value = value!,
    ),
  );

}),

产品_存储库.dart

Future<ProductResult<ScheduleModel>> getSchedule(Map<String, dynamic> body) async {

final result = await _httpManager.restRequest(
  url: Endpoints.getSchedule,
  method: HttpMethods.post,
  body: body,
);

if(result['result'] != null){
  
  List<ScheduleModel> data = List<Map<String, dynamic>>.from(result['result']).map( ScheduleModel.fromJson ).toList();

  return ProductResult<ScheduleModel>.success(data);

}else{
  return ProductResult.error('An unexpected error occurred.');
}

}
产品控制器dart

List<ScheduleModel> allSchedule = [];

Future<void> getSchedule() async{

Map<String, dynamic> body = {
  'productId': 'V59bhQz5ph',
};

ProductResult<ScheduleModel> result = await productRepository.getSchedule(body);

result.when(
  success: (data){

    print(data);
    allSchedule.addAll(data);

  },
  error: (message){
    utilsServices.showToast(message: message, isError: true);
  },
);

计划_模型.dart

import 'package:freezed_annotation/freezed_annotation.dart';
part 'schedule_model.g.dart';

@JsonSerializable()
class ScheduleModel{
  
  String id;
  DateTime date;
  
  ScheduleModel({
    required this.id,
    required this.date,
  });

  factory ScheduleModel.fromJson(Map<String, dynamic> json)=> _$ScheduleModelFromJson(json);

  Map<String, dynamic> toJson() => _$ScheduleModelToJson(this);

  @override
  String toString() {
    return 'ScheduleModel{id: $id, date: $date}';
  }

}
xlpyo6sf

xlpyo6sf1#

在解析服务器中,我不得不将date列的类型从Date改为String,这样就可以了,代码如下所示:

ValueListenableBuilder(
    valueListenable: dropValue,
    builder: (BuildContext context, String value, _) {

      return DropdownButton(
        hint: const Text('choose an option'),
        value: (value.isEmpty) ? null : value,
        onChanged: (choose) => dropValue.value = choose.toString(),
        items: productController.allSchedule.map((option) => DropdownMenuItem(
          value: option.date,
          child: Text( option.date ),
        ),).toList(),
      );

    },
  ),

相关问题