Flutter / Dart:多次重复使用小部件并返回setState值

时间:2020-08-22 18:37:07

标签: flutter dart

我在应用程序的一页上多次使用DropdownButton小部件。为了防止代码重写,我想只使用一次小部件并将值传递给它。我遇到的问题是我需要将setState设置为“值”,将参数传递给所提到的方法时不会发生这种情况。如何重用一种窗口小部件结构,并将其setState用于多个不同的值?我的示例如下:

String trial;

Widget build(BuildContext context) {
return SafeArea(
  child: Scaffold(
    body: Column(
      children: [
            //TRIAL
            dropDownLists(
              hint: "Trial",
              items: ["1", "2", "3", "4"],
              value: trial, //<---This value does not update when option chosen
            ),
      ],
    ),
  ),
);
}

//方法

Widget dropDownLists({String hint, List<String> items, String value}) {
    print(value); //<--- null, but giving a value throws errors because a value 
                  //doesn't match an item on the list
    return DropdownButton<String>(
      hint: Text(hint),
      value: value,
      onChanged: (selectedValue) {
        print(selectedValue);
        print(value);
        setState(() {
          value = selectedValue;
        });
      },
      items: items.map((String selection) {
        return DropdownMenuItem<String>(
          value: selection,
          child: Text(selection),
        );
      }).toList(),
    );
  }

问题:DropdownList起作用,直到需要选择一个值为止。选择一个值后,就不会显示为已选择

理论:我目前无法正确返回该值,但不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

String trial;

Widget build(BuildContext context) {
  return SafeArea(
    child: Scaffold(
      body: Column(
        children: [
          dropDownLists(
            hint: "Trial",
            items: ["1", "2", "3", "4"],
            value: trial,
            onChange: (value) => setState(() => trial = value),
          ),
        ],
      ),
    ),
  );
}

Widget dropDownLists({
  String hint,
  List<String> items,
  String value,
  Function(String) onChange,
}) {
  print(value);

  return DropdownButton<String>(
    hint: Text(hint),
    value: value,
    onChanged: onChange,
    items: items.map((String selection) {
      return DropdownMenuItem<String>(
        value: selection,
        child: Text(selection),
      );
    }).toList(),
  );
}