Home > Software design >  How to fetch huge data from API to dropdownlist?
How to fetch huge data from API to dropdownlist?

Time:11-02

When I fetch the data from database it is giving an error , the error is not correct but it means that you are getting huge data .

here is the data that want to fecth it ;

enter image description here

here is the model of this data :

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;
  }
}

I tried to fetch it but cause of the huge data it gives renderflex error.

enter image description here

The code 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());
                          });
                        },
                      )

Custom 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,
  ),
);

} }

CodePudding user response:

I'm inferring that it's your widgets that are too big, causing a render overflow horizontally. If you're displaying this data directly in a Text widget, try instead doing this (order of widgets in your tree leading up to the Text widget):

Row -> Expanded -> Text

This may make the text wrap.

It's hard to answer without more details.

CodePudding user response:

I think the problem is that the size of the icon is too big. Try changing the size of the icon to a smaller number.

CodePudding user response:

Try below code:

Your JSON String, id and List declaration

 String jsonString =
      '[ { "Id": 1787, "Name": "Zanesville"},{ "Id": 1788, "Name": "Carrasco International Airport"},{ "Id": 1789, "Name": "San Felipe"},{ "Id": 1790, "Name": "Valencia"},{ "Id": 1791, "Name": "Carvajal"},{ "Id": 1792, "Name": "Mansa"}]';
  String? id;
  List data = [];

API function:

 Future fetchJSONData() async {
    var jsonData = json.decode(jsonString);
    setState(() {
      data = jsonData;
    });
    return jsonData;
  }

Call your API fetchJSONData() inside initState()

  @override
  void initState() {
    super.initState();
    fetchJSONData();
  }

Your Widget:

Padding(
          padding: const EdgeInsets.all(8.0),
          child: InputDecorator(
            decoration: const InputDecoration(
              border: OutlineInputBorder(),
            ),
            child: DropdownButtonHideUnderline(
              child: ButtonTheme(
                alignedDropdown: true,
                child: DropdownButton(
                  isDense: true,
                  isExpanded: true,
                  value: id,
                  hint: const Text(
                    "Choose Airport",
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                  items: data.map((list) {
                    return DropdownMenuItem(
                      child: Text(
                        list['Name'],
                        overflow: TextOverflow.visible,
                      ),
                      value: list['Id'].toString(),
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      id = value as String;
                    });
                  },
                ),
              ),
            ),
          ),
        ),

Result Screen->

1-> Initial Dropdown

2- >Dropdown Data

3->Selected Value

  • Related