Home > front end >  How to show REST API data based on DropdownMenuItem selected value in flutter?
How to show REST API data based on DropdownMenuItem selected value in flutter?

Time:10-17

I'm trying to show data of only one object from the list below based on the value of its selected id, using the flutter DropdownMenuItem widget

The list received from the REST API looks like this:

[ {
   "id" : "123",
   "name" : "firstItem",
   "description" : "firstDescription",
  }, {
   "id" : "321",
   "name" : "secondItem",
   "description" : "secondDescription",
} ]

And the code I use to handle the response looks like this:

  Future<List<ObjectName>>? getData() async {
    const String url = 'urlOfAPI';

    var response = await http.get(
      Uri.parse(url),
      headers: {
        "content-type": "application/json",
        "accept": "application/json",
      },
    );

    if (response.statusCode == 200) {
      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
      return parsed.map<ObjectName>((json) => ObjectName.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load');
    }
  }

I'd like to know how to access the objects from inside flutter DropdownButton widget and show each object's "name" and "description" values based on the selected "id" value inside DropdownMenuItem e.g.

if selected value == "321"

return secondItem & secondDescription

CodePudding user response:

Here is the example to check the selected value inside onChange

    import 'package:flutter/material.dart';
    import 'dart:convert';
    import 'package:http/http.dart' as http;

    final jsonString =
        '[{"id":"123","name":"firstItem","description":"firstDescription"},{"id":"321","name":"secondItem","description":"secondDescription"}]';
    void main() {
      runApp(MyApp());
    }

    //Create it as Global key
    final myListKey = GlobalKey<AnimatedListState>();

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }

    class MyHomePage extends StatefulWidget {
      MyHomePage({
        Key? key,
      }) : super(key: key);

      @override
      _MyHomePageState createState() => _MyHomePageState();
    }

    class _MyHomePageState extends State<MyHomePage> {
      List<User> users = [];
      User? selected;
      @override
      void initState() {
        super.initState();
        fetchAndShow();
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(
            child: DropdownButton<User>(
              value: selected,
              onChanged: (User? newValue) {
                // here you'll get selected value
                setState(() {
                  selected = newValue!;
                });
              },
              items: users
                  .map(
                    (e) => DropdownMenuItem(
                      child: Text(e.name),
                      value: e,
                    ),
                  )
                  .toList(),
            ),
          ),
        );
      }

      Future<List<User>>? getData() async {
        //API call here and return users
        return userFromJson(jsonString);
      }

      Future<void> fetchAndShow() async {
        final users = await getData();
        setState(() {
          this.users = users ?? [];
        });
      }
    }

    List<User> userFromJson(String str) =>
        List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

    String userToJson(List<User> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

    class User {
      User({
        required this.id,
        required this.name,
        required this.description,
      });

      String id;
      String name;
      String description;

      factory User.fromJson(Map<String, dynamic> json) => User(
            id: json["id"],
            name: json["name"],
            description: json["description"],
          );

      Map<String, dynamic> toJson() => {
            "id": id,
            "name": name,
            "description": description,
          };
    }
  • Related