by @kodeazy

flutter How to set the default value for dropdown in dart file?

Home » flutter » flutter How to set the default value for dropdown in dart file?
  • Below is the syntax for setting the default value for the dropdown.

    String dropdownvalue="ford";
    DropdownButton(
            value: dropdownvalue,// here we will be giving the default value
            icon: const Icon(Icons.keyboard_arrow_down),
            items: items1.map((String items1) {
              return DropdownMenuItem(
                value: items1,
                child: Text(items1),
              );
            }).toList(),
            onChanged: (String? selectedValue) {
              setState(() {
                dropdownvalue = selectedValue!;
              });
            })
  • Below is the Example program for setting default value for dropdown in flutter.

    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    void main() {
    runApp(MyApp());
    }
    class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'Flutter DropDown Example',
      theme: ThemeData(primarySwatch: Colors.green),
      home: DropDownExample(),
    );
    }
    }
    class DropDownExample extends StatefulWidget {
    @override
    State<DropDownExample> createState() => SampleDropDown();
    }
    class SampleDropDown extends State<DropDownExample> {
    String dropdownvalue = 'Ford';
    var items1 = [
    'Audi',
    'BMW',
    'Ford',
    'Ferrari',
    ];
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDown Default Value Example"),
      ),
      body: Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        DropdownButton(
            value: dropdownvalue,
            icon: const Icon(Icons.keyboard_arrow_down),
            items: items1.map((String items1) {
              return DropdownMenuItem(
                value: items1,
                child: Text(items1),
              );
            }).toList(),
            onChanged: (String? selectedValue) {
              setState(() {
                dropdownvalue = selectedValue!;
              });
            })
      ])),
    );
    }
    }

    Output: flutter dropdown default value example Image