Home > front end >  How can I achive DropDownMenu data as dynamic for my Flutter App?
How can I achive DropDownMenu data as dynamic for my Flutter App?

Time:03-02

I want to achive DropDownMenu as dynamic as Flutter Appbar widget.

here is my previous static dropdown :

  DropdownButton<int>(
            value: allCategoryProductC.selectedValue,
            icon: KText(text: ' '),
            dropdownColor: orange,
            focusColor: white,
            items: <DropdownMenuItem<int>>[
              DropdownMenuItem(
                child: KText(
                  text: 'Rajshahi',
                  color: black,
                  fontFamily: segoeBoldFonts,
                  maxLines: 1,
                  fontSize: 16,
                ),
                value: 1,
              ),
              DropdownMenuItem(
                child: KText(
                  text: 'Dhaka',
                  color: black,
                  fontFamily: segoeBoldFonts,
                  maxLines: 1,
                  fontSize: 16,
                ),
                value: 2,
              ),
              DropdownMenuItem(
                child: KText(
                  text: 'Rangpur',
                  color: black,
                  fontFamily: segoeBoldFonts,
                  maxLines: 1,
                  fontSize: 16,
                ),
                value: 3,
              ),
            ],
            onChanged: (int? value) {
              setState(() {
                RestartWidget.restartApp(context);
                allCategoryProductC.selectedValue = value;
                print(value);
                RestartWidget.restartApp(context);
              });
            },
          ),

I've a Api data, I want to show my data as a List in this dropdown menu widget....

How can I show data ???

This is my Api json data :

{
    "locations": [
        {
            "id": 2,
            "location": "Rajshahi",
            "slug": "rajshahi",
            "status": 1,
            "created_at": "2022-01-26T07:25:18.000000Z",
            "updated_at": "2022-02-18T13:47:01.000000Z"
        }
    ]
}

This is my Controller:

class CustomerLocationController extends GetxController {

  final customerLocationList = RxList<Locations>();

  final dio = Dio();

  getCustomerLocation() async {
    try {
      final res = await dio.get(baseUrl   'customer/location');
      final List<Locations> customerLocationData = res.data['locations']
          .map((json) => Locations.fromJson(json))
          .toList()
          .cast<Locations>();
      // print(res.data);

      customerLocationList.addAll(customerLocationData);
    } catch (e) {
      print(e);
    }
  }

How can I fetch data by using this controller....

CodePudding user response:

First you need to parse json to Model/Class:

// To parse this JSON data, do
//
//     final locations = locationsFromJson(jsonString);

import 'dart:convert';

Locations locationsFromJson(String str) => Locations.fromJson(json.decode(str));

String locationsToJson(Locations data) => json.encode(data.toJson());

class Locations {
    Locations({
        this.locations,
    });

    List<Location> locations;

    factory Locations.fromJson(Map<String, dynamic> json) => Locations(
        locations: List<Location>.from(json["locations"].map((x) => Location.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "locations": List<dynamic>.from(locations.map((x) => x.toJson())),
    };
}

class Location {
    Location({
        this.id,
        this.location,
        this.slug,
        this.status,
        this.createdAt,
        this.updatedAt,
    });

    int id;
    String location;
    String slug;
    int status;
    DateTime createdAt;
    DateTime updatedAt;

    factory Location.fromJson(Map<String, dynamic> json) => Location(
        id: json["id"],
        location: json["location"],
        slug: json["slug"],
        status: json["status"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "location": location,
        "slug": slug,
        "status": status,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
    };
}

And then add your data list to dropdown with a method to convert it to dropdownmenuitem:

Locations data; // -> your data parsed from json
DropdownButton<int>(
            value: allCategoryProductC.selectedValue,
            icon: KText(text: ' '),
            dropdownColor: orange,
            focusColor: white,
            items: data.locations.map((e) => _dataToMenuItem(e)).toList())

The method in cuestion:

DropdownMenuItem<int> _dataToMenuItem(dynamic item){
   return DropdownMenuItem(
                child: KText(
                  text: item.location,
                  color: black,
                  fontFamily: segoeBoldFonts,
                  maxLines: 1,
                  fontSize: 16,
                ),
                value: item.id,
              );
}

CodePudding user response:

first of all convert you json response to dart model class with factory methods with from json to convert your json to dart class then make a list of all the elements from class objects and then use that list in your dropdown. Hope, it will work.

CodePudding user response:

Something like this would work:

items: jsonList.map((e) => DropdownMenuItem<int>(
  child: KText(
    text: e.name,
    color: black,
    fontFamily: segoeBoldFonts,
    maxLines: 1,
    fontSize: 16,
  ),
  value: e.id,
)).toList(),

So you need to get your data in a list (jsonList here) and create a DropdownMenuItem for each element of the list.

  • Related