如何从实例访问有状态窗口小部件内的变量

时间:2019-07-12 23:20:39

标签: flutter statefulwidget

我使用一个stateful class为我返回DropdownButton小部件,我需要访问其中的一个变量,该变量不是最终变量,可以通过其object访问。 这是我的代码:

    class ListItemHelper extends StatefulWidget {
  String name = '';

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

class _ListItemHelperState extends State<ListItemHelper> {
  List<ListItem> _nloc = <ListItem>[
    const ListItem(1, 'Kabul'),
    const ListItem(2, 'Mazar')
  ];
  ListItem _nlocSelectedItem;

  ListItem get listI => _nlocSelectedItem;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<ListItem>(
      value: _nlocSelectedItem,
      onChanged: (ListItem newValue) {
        setState(() {
          _nlocSelectedItem = newValue;
          widget.name = newValue.name;
          print(
              'this is the menu idxx: ${newValue.id} and the title is ${newValue.name}');
        });
      },
      items: _nloc.map((ListItem listItem) {
        return new DropdownMenuItem<ListItem>(
          value: listItem,
          child: new Text(
            listItem.name,
            style: new TextStyle(color: Colors.black),
          ),
        );
      }).toList(),
    );
  }
}

class ListItem {
  const ListItem(this.id, this.name);

  final String name;
  final int id;
}

为了清楚起见,我需要通过类的对象访问变量名。

0 个答案:

没有答案