如何在Flutter中建立相关的下拉菜单?

问题描述 投票:0回答:2

我有三个下拉菜单,如果满足某些条件(ONLY),我希望显示第四个菜单Favourite Animal = Cat。我也希望只要条件不再成立,第四个下拉菜单就会消失。现在,如果我手动保存文件并执行热重装,则会显示更改。因此,我猜测它与setState()有关,但我没有将其包含在filter.dart文件中。

文件1-filter.dart:

import 'package:flutter/material.dart';
import './dropdown.dart';

class Filter extends StatefulWidget {
  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {  
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster']),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

文件2-dropdown.dart:

import 'package:flutter/material.dart';

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;

  Dropdown(this._key, this._values);

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

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String> (
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        },
      ),
    );
  }
}

bool cat = false; //Feels wrong to have this bool out in the open

filter.dart-文件是通过main从Filter()调用的。

奖励问题:我也想提取所选的值,然后将它们返回到filter.dart文件,然后在onPressedRaisedButton函数中使用它们,不太确定如何做到这一点。

flutter dart state dropdown
2个回答
0
投票

在您的DropdownButton上有onChanged回调:

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        }

此对setState()的调用将通过Dropdown小部件而不是到较高的“过滤器”小部件。

解决此问题的一种方法是在您的自定义Dropdown类中添加一个Function回调:

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function callback;

  Dropdown(this._key, this._values, this.callback);

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

并且,在onChanged属性中:

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          callback();
        },

这将调用您在创建Dropdown时定义的回调:

children: <Widget>[
                Dropdown('Gender', ['Female', 'Male'], callbackFunc),
                Dropdown('Age', ['<15', '15-20', '>20'], callbackFunc),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'], callbackFunc) : Text('')
              ],

其中callbackFunc可能很简单:

void callbackFunc(){
    setState((){});
}

当然,这不是最优雅的解决方案。由于您正在使用回调,因此可以撤消使用的所有全局变量,而只需将回调与参数一起使用:

void callbackFunc(String value){
    if (value=='cat')
        choseCat=true;
    else
        choseCat=false;
    setState((){});
}

而且,您不必检查小部件键即可确认正在调用哪个下拉菜单。您可以在调用之前检查回调是否为null,并且仅将回调函数提供给适当的函数:

children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],

[...]

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          if (callback)
              callback();
        },

在这种情况下,请不要忘记将回调设为可选:

Dropdown({@required this._key, @required this._values, this.callback});

我确信使用此方法可以完成许多其他优化。对于更大的应用程序,应该选择其他State management approaches以使您的生活更轻松。


0
投票

修复6个地方。怎么样?

class _FilterState extends State<Filter> {
  bool cat = false; // Move here.

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], update: _update), // Fix this line.
                (cat)
                    ? Dropdown(
                        'Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'])
                    : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }

  // Add this function.
  void _update(bool b) {
    setState(() {
      cat = b;
    });
  }

}

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function update; // Add this line.

  Dropdown(this._key, this._values, {this.update = null}); // Fix this line.

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

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String>(
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          // Fix start.
          setState(() {
            _chosenValue = value;
          });
          if (widget.update != null) {
            (widget._key == 'Favourite Animal' && _chosenValue == 'Cat')
                ? widget.update(true)
                : widget.update(false);
          }
          // Fix end.
        },
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.