Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter DropdownButton dont show value, when using hint

Tags:

flutter

i have an AlertDialog and want to use a DropdownButton for changing a value. At first there should be the hint visible. After choosing a value, the value should be visible. But when i use the hint, it never shows the value and vice versa.

DropdownButton(
     items: <String>['team1','team2'].map((String val) => DropdownMenuItem<String>(
    value: val,
    child: Text(val),
   )).toList(),
  //value: 'team1',
    hint: Text('Enter team'),
    
    onChanged: (value) {
      teteam.text = value;
    }
                ),

It has the correct function, but visibility isnt quite like i expect.

like image 489
Thomas B Avatar asked Oct 28 '25 15:10

Thomas B


1 Answers

I'm posting a fully working code at the bottom

For future projects in order to 'activate the hint' ability you have to meet two conditions:

Set the initial value to null and the dropdown is enabled( list of strings and onChanged are non-null. Or so the official documentation says so.

Code below:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String? theTeam = null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: DropdownButton(
          value: theTeam,
          items: <String>['team1', 'team2']
              .map((String val) => DropdownMenuItem<String>(
                    value: val,
                    child: Text(val),
                  ))
              .toList(),
          hint: Text('Enter team'),
          onChanged: (String? value) {
            setState(() {
              theTeam = value!;
            });
          },
        ),
      ),
    );
  }
}

enter image description here

enter image description here

like image 150
petras J Avatar answered Oct 30 '25 05:10

petras J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!