如何从API获取大量数据到Dropdown并解决RenderFlex报错?
问题:数据量过大导致下拉选择框出现RenderFlex错误
从数据库获取数据时出现错误,错误提示并不准确,实际原因是获取的数据量过大,导致下拉选择框触发RenderFlex布局溢出错误。
涉及的数据与模型
待获取的数据
数据为包含大量机场信息的列表,每条数据包含Id和Name两个字段。
数据模型代码
class DropdownListModel { int? id; String? name; DropdownListModel({this.id, this.name}); DropdownListModel.fromJson(Map<String, dynamic> json) { id = json['Id']; name = json['Name']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['Id'] = id; data['Name'] = name; return data; } }
错误表现
触发RenderFlex错误,布局无法容纳过多的下拉选项,出现溢出提示。
相关代码
UI层使用代码
CustomDropDown( width: 375, focusNode: FocusNode(), icon: const Icon( Icons.keyboard_arrow_down_outlined, size: 30, ), hintText: "Choose Airport", items: airports!.map<DropdownMenuItem<String>>((e) { return DropdownMenuItem<String>( value: e.name, child: Text( e.name!, textAlign: TextAlign.left, ), ); }).toList(), onChanged: (value) { setState(() { int index = airports! .indexWhere((e) => e.name == value); destinationAirportId = int.parse(airports![index].id.toString()); debugPrint( "destinationAirportId : " + destinationAirportId.toString()); }); }, )
自定义Dropdown组件代码
import 'package:hrsm/core/app_export.dart'; import 'package:flutter/material.dart'; class CustomDropDown extends StatelessWidget { CustomDropDown({ super.key, this.alignment, this.width, this.margin, this.focusNode, this.icon, this.hintText, this.prefix, this.prefixConstraints, this.items, this.onChanged, }); Alignment? alignment; double? width; EdgeInsetsGeometry? margin; FocusNode? focusNode; Widget? icon; String? hintText; Widget? prefix; BoxConstraints? prefixConstraints; List<DropdownMenuItem<dynamic>>? items; Function(dynamic)? onChanged; @override Widget build(BuildContext context) { return _buildDropDownWidget(); } _buildDropDownWidget() { return Container( width: width, margin: margin, child: DropdownButtonFormField( focusNode: focusNode, icon: icon, style: TextStyle( color: ColorConstant.black900, fontSize: getFontSize( 14, ), fontFamily: 'Poppins', fontWeight: FontWeight.w400, height: 1.00, ), decoration: InputDecoration( hintText: hintText, hintStyle: TextStyle( fontSize: getFontSize( 14.0, ), color: ColorConstant.black900, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( getHorizontalSize( 12.00, ), ), borderSide: BorderSide( color: ColorConstant.bluegray50, width: 1, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( getHorizontalSize( 12.00, ), ), borderSide: BorderSide( color: ColorConstant.bluegray50, width: 1, ), ), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( getHorizontalSize( 12.00, ), ), borderSide: BorderSide( color: ColorConstant.bluegray50, width: 1, ), ), ), items: items, onChanged: onChanged, ), ); } }
内容的提问来源于stack exchange,提问作者Samet Demirtop
相关产品推荐
相关产品推荐

