1

the following code displays a list in a dropdown after loading it with the function called in the FutureBuilder. However, the following exception is displayed when the dropdown is selected. How can I resolve it, and what is causing it?

Exception:

There should be exactly one item with [DropdownButton]'s value: 172.16.54.22:8100. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 892 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

Flutter Code:

class LoginPage extends KFDrawerContent {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _email =
      TextEditingController(text: "http://207.154.221.255:8100");
  final TextStyle textStyle = TextStyle(color: Colors.white);
  List<String> hostIpList = ["Seleziona IP"];
  String dropdownValue = "Seleziona IP";

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
        future: scanNetwork(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasError) {
            return Container();
          } else {
            return Scaffold(
              backgroundColor: primary,
              body: getBody(),
            );
          }
        });
  }

  Future<bool> scanNetwork() async {
    await (NetworkInfo().getWifiIP()).then(
      (ip) async {
        final String subnet = ip.substring(0, ip.lastIndexOf('.'));
        const port = 22;
        for (var i = 0; i < 256; i++) {
          String ip = '$subnet.$i';
          await Socket.connect(ip, port, timeout: Duration(milliseconds: 50))
              .then((socket) async {
            await InternetAddress(socket.address.address)
                .reverse()
                .then((value) {
              setState(() {
                hostIpList.add(value.address);
                hostIpList = Verifica.uniqueArray(hostIpList);
              });
            }).catchError((error) {
              setState(() {
                var ip = socket.address.host.toString().replaceAll(
                    ", IPv4)", "");
                hostIpList.add(socket.address.address);
                hostIpList = Verifica.uniqueArray(hostIpList);
              });
            });
            socket.destroy();
          }).catchError((error) => null);
        }
      },
    );

    return true;
  }

  Future<String> alert(BuildContext context, String testo) {
    return showDialog<String>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text(
          'ATTENZIONE',
          style: TextStyle(color: Colors.red),
        ),
        content: Text(testo),
        actions: <Widget>[
          Center(
            child: TextButton(
              style: TextButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.red, // Background Color
              ),
              onPressed: () => Navigator.pop(context, 'Cancel'),
              child: const Text('OK'),
            ),
          ),
        ],
      ),
    );
  }

  void login(BuildContext context) async {
    if (_email.text.length > 0) {
      Storage.salva("URL", _email.text);
      Macchina mc = await Macchina.getModel();
      if (mc.model.length > 0) {
        Storage.salva("Model", mc.model);
        Storage.salva("Serial", mc.serial);
        Storage.salva("Time", mc.time);
        await Cloud.getToken();
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage(),
            ));
      } else {
        alert(context,
            "Connessione non riuscita, verifica l'indirizzo ip e di essere connesso al raspberry pi ");
      }
    } else {
      alert(context, "URL non valido");
    }
  }

  Widget getBody() {
    return SafeArea(
        child: Center(
      child: Column(
        children: [
          const SizedBox(
            height: 50,
          ),
          Container(
            width: 70,
            height: 70,
            decoration: const BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                    image: NetworkImage(
                        "https://yt3.googleusercontent.com/ytc/AL5GRJUCIV0j7t9jSOt5Mq87622YCHl_hqs7dMlgh4MY=s900-c-k-c0x00ffffff-no-rj"),
                    fit: BoxFit.cover)),
          ),
          const SizedBox(
            height: 30,
          ),
          const Text("Roboqbo S.R.L"),
          const SizedBox(
            height: 30,
          ),
          FittedBox(
            fit: BoxFit.contain,
            child:  Center(
            child: DropdownButton<String>(
              value: dropdownValue,
              onChanged: (String newValue) {
                setState(() {
                  _email.text = newValue + ":8100";
                  dropdownValue = newValue + ":8100";
                });
              },
              items: hostIpList.map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            ),
          ),
          ),
riki
  • 1,502
  • 5
  • 17
  • 45
  • Hello, are you sure there are not multiple items with the same IP address value? before adding the IP `hostIpList.add(value.address);` ? – mlodhi Aug 21 '23 at 06:34
  • when you're updating the value of ``dropdownValue`` make sure that value exists in your ``hostIpList``. You're changing the value of ``dropdownValue`` here ``dropdownValue = newValue + ":8100";`` but this value doens't exist in your ``hostIpList`` list since you're not updating or atleast ``port`` is'nt appended with the available IP in the ``hostIpList`` – OMi Shah Aug 21 '23 at 06:48
  • give me an example of code – riki Aug 21 '23 at 07:02
  • I think it is a dupolicated post with this one : https://stackoverflow.com/questions/60510150/flutter-there-should-be-exactly-one-item-with-dropdownbuttons-value – drino Aug 21 '23 at 07:46

0 Answers0