0

我正在使用 Flutter,并计划制作一个下拉按钮供用户选择。选择其中一个选项后,它仍会显示提示而不是用户选择的选项。

这是代码:

DropdownButton<String>(
              isExpanded: true,
              items: <String>['student', 'driver'].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: new Text(value),
                );
              }).toList(),
              hint: new Text ("Select a Role"),
              onChanged: (value) => _role = value,
            ),

预先感谢您的帮助。

4

2 回答 2

1

您需要setStateonChanged. 您必须分配_rolevalue.DropdownButton

这是我创建的DartPad 。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  
  String? _role = 'student';
  
  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      isExpanded: true,
      items: <String>['student', 'driver'].map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: new Text(value),
        );
      }).toList(),
      value: _role,
      hint: new Text("Select a Role"),
      onChanged: (value) => setState(() => _role = value),
    );
  }
}
于 2021-06-21T09:38:31.053 回答
1

你应该喜欢这个

DropdownButton<String>(
              isExpanded: true,
              items: <String>['student', 'driver'].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: new Text(value),
                );
              }).toList(),
              value:_role,
              hint: new Text ("Select a Role"),
              onChanged:  (value) => setState((){
                       _role = value
                   }),
            ),

于 2021-06-21T09:39:07.403 回答