Home > other >  Flutter - dropdown_search - Display items read from JSON array via API Endpoint
Flutter - dropdown_search - Display items read from JSON array via API Endpoint

Time:01-20

I am trying to create a drop-down searchable widget using the dropdown_search: ^2.0.1 package.

I am referring to their example code where by I hit an API endpoint to populate the items in drop-down searchable widget. Link

I created model taking their UserModel as reference. Link

I am getting the following error :

The return type 'List<ProductCodeModel>' isn't a 'Future<List<String>>', as required by the closure's context.

I get that it is expecting List<String> but I am unsure how to convert List<ProductCodeModel> to List<String>

Code :

DropdownSearch<String>(
    mode: Mode.MENU,
    showSelectedItems: true,
    showSearchBox: true,
    dropdownSearchDecoration: const InputDecoration(
      label: Text('Product Code'),
      focusColor: Colors.blue,
      border: OutlineInputBorder(
        borderSide: BorderSide(
          style: BorderStyle.solid,
        ),
      ),
    ),
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Please select Product Code';
      }
      return null;
    },
    onFind: (text) async {
      var response = await Dio()
          .get('"http://5d85ccfb1e61af001471bf60.mockapi.io/user');
      var models = ProductCodeModel.fromJsonList(response.data);
      return models;
    },
),

User Model :

class ProductCodeModel {
  final String id;
  final DateTime createdAt;
  final String name;
  final String avatar;

  ProductCodeModel({
    required this.id,
    required this.createdAt,
    required this.name,
    required this.avatar,
  });

  factory ProductCodeModel.fromJson(Map<String, dynamic> json) {
    return ProductCodeModel(
      id: json["id"],
      createdAt: json["createdAt"] = DateTime.parse(json["createdAt"]),
      name: json["name"],
      avatar: json["avatar"],
    );
  }

  static List<ProductCodeModel> fromJsonList(List list) {
    return list.map((item) => ProductCodeModel.fromJson(item)).toList();
  }

  ///this method will prevent the override of toString
  String userAsString() {
    return '#$id $name';
  }

  ///this method will prevent the override of toString
  bool userFilterByCreationDate(String filter) {
    return createdAt.toString().contains(filter);
  }

  ///custom comparing function to check if two users are equal
  bool isEqual(ProductCodeModel model) {
    return id == model.id;
  }

  @override
  String toString() => name;
}

CodePudding user response:

I get that it is expecting List<String> but I am unsure how to convert List<ProductCodeModel> to List<String>

Here's how.

final List<String> productNames = products.map((product) => product.name).toList();
  •  Tags:  
  • Related