Flutter DorpDownMenu所选项目保持不变

时间:2019-07-23 08:03:01

标签: flutter

在下面的这段代码中,当我尝试更改DropDownMenu上的项目时,所选项目没有更改,并且所选项目是列表的第一项

例如,在选择bbbbbbb后,我有aaaaaaa或选择ccccccc后,我有aaaaaaa

import 'package:flutter/material.dart';

void main()=>runApp(
  MaterialApp(
    home: _MyApp(),
  ),
);

class _MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState()=>_MyAppState();
}

class _MyAppState extends State<_MyApp> {
  SessionsEntity sessionData;
  @override
  Widget build(BuildContext context) {
    List<DropdownMenuItem<SessionsEntity>> _dropdownMenuItems;
    _dropdownMenuItems = buildDropdownMenuItems();
    sessionData = _dropdownMenuItems[0].value;

    return Scaffold(
      body: DropdownButtonHideUnderline(
        child: Theme(
          data: Theme.of(context).copyWith(
            canvasColor: Colors.white,
          ),
          child: Container(
            child: Center(
              child: DropdownButton(
                items: _dropdownMenuItems,
                isDense: true,
                value: sessionData,
                onChanged: onChangeDropdownItem,
                isExpanded: true,
                hint: Text('please select item'),
              ),
            ),
          ),
        ),
      ),
    );
  }

  List<DropdownMenuItem<SessionsEntity>> buildDropdownMenuItems() {
    List<SessionsEntity> sessions = [
      SessionsEntity(1, 'aaaaaaa', 1, 'a-a-a-a-a'),
      SessionsEntity(2, 'bbbbbbb', 2, 'b-b-b-b-b'),
      SessionsEntity(3, 'ccccccc', 2, 'c-c-c-c-c'),
    ];
    List<DropdownMenuItem<SessionsEntity>> items = List();
    for (SessionsEntity session in sessions) {
      items.add(
        DropdownMenuItem(
          value: session,
          child: Text(session.sessionName),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(SessionsEntity selectedSession) {
    setState(() {
      sessionData = selectedSession;
    });
  }
}

class SessionsEntity {
  final int id;
  String sessionName;
  int sessionType;
  String dateTime;
  SessionsEntity(this.id, this.sessionName,this.sessionType, this.dateTime);
}

3 个答案:

答案 0 :(得分:1)

问题出在下面一行。

sessionData = _dropdownMenuItems[0].value;

由于您每次都在sessionData方法中初始化build()变量,因此对setState()的调用无效。

基本上,setState()再次使用新数据调用build()方法,但是当您初始化sessionData内部build()时,每次build()它将被相同的值覆盖被称为。

您应该声明将_dropdownMenuItems列表用作类变量,而不是在build()内部声明,并使用initState()方法初始化_dropdownMenuItemssessionData变量仅一次。这是一个示例-

class _MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState()=>_MyAppState();
}

class _MyAppState extends State<_MyApp> {

  //Remove below line from build method
  List<DropdownMenuItem<SessionsEntity>> _dropdownMenuItems;
  SessionsEntity sessionData;

   @override
         void initState() {
         super.initState();
         _dropdownMenuItems = buildDropdownMenuItems();
         sessionData = _dropdownMenuItems[0].value;
  }

  @override
  Widget build(BuildContext context) {

    //Rest of the code remains same
  }
}

答案 1 :(得分:0)

关注将为您提供帮助。该示例窗口小部件用于选择原因。

示例小部件代码:

Widget dropdownReasons() {    
      return new DropdownButton<String>(
          value: _currentReason,
          items: _dropDownMenuItems,
          onChanged: changedDropDownItem);
    }
  }

下面的函数处理更改下拉值时的操作:

void changedDropDownItem(String selectedReason) {
    setState(() => _currentReason = selectedReason; // <-- This is the most important line
  }

答案 2 :(得分:0)

尝试下面的代码,它将正常工作

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: new MyApp(),),
  );
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  SessionsEntity sessionData;
  List<DropdownMenuItem<SessionsEntity>> _dropdownMenuItems;

// Build method is called whenever there is change in the state or ui, so instead of initializing the dropdown menu items and initial selected value of dropdown menu in build method you should initialize it in initState method which is called only once.

  @override
  void initState() {
    // TODO: implement initState
    _dropdownMenuItems = buildDropdownMenuItems();
    sessionData = _dropdownMenuItems[0].value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: DropdownButtonHideUnderline(
        child: Theme(
          data: Theme.of(context).copyWith(
            canvasColor: Colors.white,
          ),
          child: Container(
            child: Center(
              child: DropdownButton(
                items: _dropdownMenuItems,
                isDense: true,
                value: sessionData,
                onChanged: onChangeDropdownItem,
                isExpanded: true,
                hint: Text('please select item'),
              ),
            ),
          ),
        ),
      ),
    );
  }


  List<DropdownMenuItem<SessionsEntity>> buildDropdownMenuItems() {
    List<SessionsEntity> sessions = [
      SessionsEntity(1, 'aaaaaaa', 1, 'a-a-a-a-a'),
      SessionsEntity(2, 'bbbbbbb', 2, 'b-b-b-b-b'),
      SessionsEntity(3, 'ccccccc', 2, 'c-c-c-c-c'),
    ];
    List<DropdownMenuItem<SessionsEntity>> items = List();
    for (SessionsEntity session in sessions) {
      items.add(
        DropdownMenuItem(
          value: session,
          child: Text(session.sessionName),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(SessionsEntity selectedSession) {
    setState(() {
      sessionData = selectedSession;
    });
  }
}


class SessionsEntity {
  final int id;
  String sessionName;
  int sessionType;
  String dateTime;
  SessionsEntity(this.id, this.sessionName,this.sessionType, this.dateTime);
}