简体   繁体   English

DropdownButton 中的选定项目不会在 showDialog 内更新

[英]Selected item in DropdownButton does not update inside showDialog

The item in the DropdownButton does not change when I click a value in the list of items.当我单击项目列表中的值时,DropdownButton 中的项目不会更改。 The DropdownButton is inside a showDialog() function. DropdownButton 位于 showDialog() function 内。

As you can see in the code below, the DropdownButton is inside the showDialog item which is called when a button is pressed.正如您在下面的代码中看到的,DropdownButton 位于按下按钮时调用的 showDialog 项目内。 I have seen a potential solution to my problem here but still cannot really figure out how to apply it to my case.我在这里看到了我的问题的潜在解决方案,但仍然无法真正弄清楚如何将其应用于我的案例。

import 'package:flutter/material.dart';
import 'package:project/textstyle.dart';

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  List<Coin> _coins = Coin.getCoins();
  List<DropdownMenuItem<Coin>> _dropdownMenuItems;
  Coin _selectedCoin;

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

  List<DropdownMenuItem<Coin>> buildDropdownMenuItems(List coins) {
    List<DropdownMenuItem<Coin>> items = List();
    for (Coin coin in coins) {
      items.add(
        DropdownMenuItem(
          value: coin,
          child:
          Text(
            coin.name,
            style: TextStyle(
                fontSize: 18.0,
                color: Colors.black87,
                fontWeight: FontWeight.bold
            ),
          ),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(Coin selectedCoin) {
    setState(() {
      _selectedCoin = selectedCoin;
    });
  }

  @override
  Widget build(BuildContext context) {

    double screenHeight;
    screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        title: Text('Overview'),
        backgroundColor: Color.fromRGBO(53, 73, 94, 0.9),
        elevation: 0.0,
        leading: Container(),
      ),
      floatingActionButton: new Container(
        width: 120.0,
        height: 120.0,
        padding: const EdgeInsets.only(bottom:40.0),
        child: FloatingActionButton(
          child: Icon(Icons.add,size: 50.0),
          elevation: 0.0,
          onPressed: () {
            showDialog(
              context: context,
              builder: (context) {
                // return object of type Dialog
                return Container(
                  margin: EdgeInsets.only(
                      top: screenHeight / 5,
                      bottom: screenHeight / 4
                  ),
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Card(
                    color: Color.fromRGBO(53, 73, 94, 0.9),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    elevation: 8,
                    child: Padding(
                      padding: const EdgeInsets.all(30.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Align(
                            alignment: Alignment.topCenter,
                            child: Text(
                                "Create",
                                style: Style.headerTextStyle
                            ),
                          ),
                          Divider(
                              color: Colors.white
                          ),
                          SizedBox(
                            height: 15,
                          ),
                          DropdownButton(
                            value: _selectedCoin,
                            items: _dropdownMenuItems,
                            onChanged: onChangeDropdownItem,
                          ),
                          SizedBox(
                            height: 15,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              Expanded(
                                child: Container(),
                              ),
                              ButtonTheme(
                                minWidth: 150.0,
                                child: RaisedButton(
                                  padding: EdgeInsets.all(8.0),
                                  child: Text('Share',
                                    style: TextStyle(
                                        fontSize: 24,
                                        color: Colors.black87,
                                        fontWeight: FontWeight.bold
                                    ),
                                  ),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(18.0)
                                  ),
                                  color: Colors.white,
                                  splashColor: Colors.blueGrey,
                                  onPressed: () {
                                    setState(() {
                                      planets.add(Planet(
                                        id: '1', // TODO need to adjust this
                                        name: purposeController.text,
                                        location: '€'+amountController.text,
                                        distance: 'date',
                                        gravity: 'date',
                                        image: _setImage(), // TODO might have to pass _selectedCoin as parameter
                                      )
                                      );
                                    });
                                  },
                                ),
                              ),

                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

The final output is that the item is sent to the HomePage which already happens.最后的 output 是项目被发送到已经发生的主页。 That is why you find some variables that aren't declared in the code above because they weren't necessary to include for the problem.这就是为什么你会发现一些变量没有在上面的代码中声明,因为它们不是问题所必需的。

However, the item that is selected in the dropdown menu is not displayed.但是,不会显示在下拉菜单中选择的项目。 It would also help me if the dialog would close once Share is pressed.如果按下“ Share ”后对话框会关闭,这也会对我有所帮助。 Any help will be greatly appreciated!任何帮助将不胜感激!

You need to use StatefulBuilder您需要使用StatefulBuilder
Click share button to close dialog you need Navigator.pop(context);单击共享按钮关闭您需要的对话框Navigator.pop(context);
You can copy paste run full code below您可以在下面复制粘贴运行完整代码
code snippet代码片段

    showDialog(
                  context: context,
                  builder: (context) {
                    return StatefulBuilder(
                      builder: (BuildContext context, StateSetter setState) {
                        return AlertDialog(
                            content: Container(
                          margin: EdgeInsets.only(
                              top: screenHeight / 5, bottom: screenHeight / 4),
                          padding: EdgeInsets.only(left: 10, right: 10),
                          child: Card(
                            color: Color.fromRGBO(53, 73, 94, 0.9),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                            ),
 ...
 DropdownButton(
                                    value: _selectedCoin,
                                    items: _dropdownMenuItems,
                                    onChanged: (selectedCoin) {
                                      setState(() {
                                        _selectedCoin = selectedCoin;
                                        print('${_selectedCoin.name}');
                                      });
                                    }, //onChangeDropdownItem(_selectedCoin, setState),
                                  ),

working demo工作演示

在此处输入图像描述

full code完整代码

    import 'package:flutter/material.dart';
//import 'package:project/textstyle.dart';

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

class Coin {
  String name;
  int value;

  Coin({
    this.name,
    this.value,
  });

  factory Coin.fromJson(Map<String, dynamic> json) => Coin(
        name: json["name"],
        value: json["value"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "value": value,
      };
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Coin> _coins = [
    Coin(name: "abc", value: 1),
    Coin(name: "def", value: 2)
  ]; //Coin.getCoins();
  List<DropdownMenuItem<Coin>> _dropdownMenuItems;
  Coin _selectedCoin;

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

  List<DropdownMenuItem<Coin>> buildDropdownMenuItems(List coins) {
    List<DropdownMenuItem<Coin>> items = List();
    for (Coin coin in coins) {
      items.add(
        DropdownMenuItem(
          value: coin,
          child: Text(
            coin.name,
            style: TextStyle(
                fontSize: 18.0,
                color: Colors.black87,
                fontWeight: FontWeight.bold),
          ),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(Coin selectedCoin, StateSetter setState) {
    setState(() {
      _selectedCoin = selectedCoin;
      print('${_selectedCoin.name}');
    });
  }

  @override
  Widget build(BuildContext context) {
    double screenHeight;
    screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
        appBar: AppBar(
          title: Text('Overview'),
          backgroundColor: Color.fromRGBO(53, 73, 94, 0.9),
          elevation: 0.0,
          leading: Container(),
        ),
        floatingActionButton: new Container(
          width: 120.0,
          height: 120.0,
          padding: const EdgeInsets.only(bottom: 40.0),
          child: FloatingActionButton(
              child: Icon(Icons.add, size: 50.0),
              elevation: 0.0,
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) {
                    return StatefulBuilder(
                      builder: (BuildContext context, StateSetter setState) {
                        return AlertDialog(
                            content: Container(
                          margin: EdgeInsets.only(
                              top: screenHeight / 5, bottom: screenHeight / 4),
                          padding: EdgeInsets.only(left: 10, right: 10),
                          child: Card(
                            color: Color.fromRGBO(53, 73, 94, 0.9),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            elevation: 8,
                            child: Padding(
                              padding: const EdgeInsets.all(30.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Align(
                                    alignment: Alignment.topCenter,
                                    child: Text(
                                      "Create",
                                      //style: Style.headerTextStyle
                                    ),
                                  ),
                                  Divider(color: Colors.white),
                                  SizedBox(
                                    height: 15,
                                  ),
                                  DropdownButton(
                                    value: _selectedCoin,
                                    items: _dropdownMenuItems,
                                    onChanged: (selectedCoin) {
                                      setState(() {
                                        _selectedCoin = selectedCoin;
                                        print('${_selectedCoin.name}');
                                      });
                                    }, //onChangeDropdownItem(_selectedCoin, setState),
                                  ),
                                  SizedBox(
                                    height: 15,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: <Widget>[
                                      Expanded(
                                        child: Container(),
                                      ),
                                      ButtonTheme(
                                        minWidth: 150.0,
                                        child: RaisedButton(
                                          padding: EdgeInsets.all(8.0),
                                          child: Text(
                                            'Share',
                                            style: TextStyle(
                                                fontSize: 24,
                                                color: Colors.black87,
                                                fontWeight: FontWeight.bold),
                                          ),
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(18.0)),
                                          color: Colors.white,
                                          splashColor: Colors.blueGrey,
                                          onPressed: () {
                                            Navigator.pop(context);
                                            setState(() {
                                              /*planets.add(Planet(
                                        id: '1', // TODO need to adjust this
                                        name: purposeController.text,
                                        location: '€'+amountController.text,
                                        distance: 'date',
                                        gravity: 'date',
                                        image: _setImage(), // TODO might have to pass _selectedCoin as parameter
                                      )
                                      );*/
                                            });
                                          },
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ));
                      },
                    );
                  },
                );
              }),
        ));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM