Alex Childs
Alex Childs

Reputation: 85

Creating a dropdown from get data

I'm just learning flutter, and I'm trying to create a dropdown from post data. Right now I'm just using the public jsonplaceholder api, but will move this over to a private api once I can figure out how it works. When I run my code it is giving this error:

"There should be exactly one item with [DropdownButton]'s value: . \nEither zero or 2 or more [DropdownMenuItem]s were detected with the same value"

I've tried a couple of different ways of passing the data into the DropdownMenuItem field with no luck.

here is the code I'm running, it is pretty simple:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(
  title: "Hospital Management",
  home: MyApp(),
));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _mySelection = "";

  final String url = "https://jsonplaceholder.typicode.com/users";

  List data = []; //edited line

  Future<String> getSWData() async {
    var res = await http
        .get(Uri.parse(url), headers: {"Accept": "application/json"});
    var resBody = json.decode(res.body);

    setState(() {
      data = resBody;
    });

    print(resBody);

    return "Sucess";
  }

  @override
  void initState() {
    super.initState();
    this.getSWData();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("Hospital Management"),
      ),
      body: new Center(
        child: new DropdownButton(
          items: data.map((item) {
            return new DropdownMenuItem(
              child: new Text(item['name']),
              value: item['id'].toString(),
            );
          }).toList(),
          onChanged: (String? newVal) {
            setState(() {
              _mySelection = newVal!;
            });
          },
          value: _mySelection,
        ),
      ),
    );
  }
}```

Feel free to critique any part of my code, like I said, I'm brand new to flutter and still learning the ropes.

Upvotes: 1

Views: 2071

Answers (2)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14775

Try below code hope it help to you.

Create your API Call function and variable declaration and check your selected name of Id on console

  String userId;
  List data = List();
  String url = "https://jsonplaceholder.typicode.com/users";

  //your all api call
  Future fetchData() async {
    var result = await http.get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    var jsonData = json.decode(result.body);
    print(jsonData);
    setState(() {
      data = jsonData;
    });
    return jsonData;
  }
  //call your API fetchData() inside initState()
  @override
  void initState() {
    super.initState();
    fetchData();
  }

Create your Dropdown Widget

    DropdownButtonHideUnderline(
        child: DropdownButton(
          value: userId,
          hint: Text("Select Name",
              style: TextStyle(color: Colors.black)),
          items: data.map((list) {
            return DropdownMenuItem(
              child: Text(list['name']),
              value: list['id'].toString(),
            );
          }).toList(),
          onChanged: (value) {
            setState(() {
              userId = value;
              print(userId);
            });
          },
        ),
      ),

Your Dropdown look like -> enter image description here

Upvotes: 2

Alex Childs
Alex Childs

Reputation: 85

I just found why my code wasn't working. so for anyone looking in the future, I have null safety enabled, so I tried to initialize my select holder, called _mySelection above, to an empty string, but that wasn't found in the database. By using String? _mySelection I could allow the value to be null, and so there was no error when the list was first loaded, and then you can pick an option from the list.

Upvotes: 0

Related Questions