Home > front end >  There should be exactly one item with [DropdownButton]'s
There should be exactly one item with [DropdownButton]'s

Time:05-22

I think I want a thing so simple, flutter tell me there is just one item or there is no item. But I am sure there are more item than one,IDK, how I should ask question for this problem. I just want to take a list and make a dropdownMenu with CustomClass's items.I did copy paste from enter image description here

import 'package:flutter/material.dart';

class BreedJson {
  final String breed;
  final String img;

  BreedJson(this.breed, this.img);
}

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  String dropdownValue = 'default ';

  final List<BreedJson> myBreedJson = [
    BreedJson("Cavalier King Charles Spaniel",
        'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'),
    BreedJson('Curly-Coated Retriever',
        'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSLqpKzfZ6L0TSvUKBhXwJQOnqfWzoaQWoIjCZu1s0evNhfSFWeNVMYWJYt0MqInbznRgE&usqp=CAU')
  ];

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        elevation: 16,
        style: const TextStyle(color: Colors.deepPurple),
        underline: Container(
          height: 2,
          color: Colors.deepPurpleAccent,
        ),
        onChanged: (String? newValue) {
          setState(() {
            dropdownValue = newValue!;
          });
        },
        items: myBreedJson
            .map<DropdownMenuItem<String>>((BreedJson value) => DropdownMenuItem<String>(
                  value: value.breed,
                  child: Text(value.img),
                ))
            .toList());
  }
}

CodePudding user response:

Try this:

String dropdownValue = "Cavalier King Charles Spaniel";

CodePudding user response:

myBreedJson list doesn't contain default that's why it is trowing this error.

You can pass initially null on value, for this make dropdownValue nullable

 String? dropdownValue;
  • Related