Flutter:如何从社团获取 baseurl?

Flutter: How to get the baseurl from the societies?

对于身份验证,我想恢复从下拉列表中选择的公司的 base_url,但我做不到,作为初学者,欢迎提供一些帮助。 这是下拉列表的代码:

class DropDown extends StatefulWidget {
  DropDown({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<DropDown> {
  String _mySelection;
  String _myBaseUrl;
  List<Map> _myJson = [{"id":2,"society":"test","baseUrl":"url.com"},{"id":1,"society":"planeef","baseUrl":"url.com"}];

  @override
  Widget build(BuildContext context) {
    return Container(
        child: new DropdownButton<String>(
          isDense: true,
          hint: new Text("Select"),
          value: _mySelection,
          onChanged: (String newValue) {
            setState(() {
              _mySelection = newValue;
            });
          },
          items: _myJson.map((Map map) {
            return new DropdownMenuItem<String>(
              value: map["id"].toString(),
              child: new Text(
                map["society"],
              ),
            );
          }).toList(),
        ),
    );
  }
}

检查下面的代码。您可以使用 singleWhere 函数从下拉列表中获取的 id 值中检索元素,然后从元素中读取 baseUrl

singleWhere 函数根据我们提供的条件匹配并 returns 列表中的单个元素。

注- 如果存在重复项或未找到元素,singleWhere 函数默认会抛出错误。您可能还需要将 orElse 参数传递给 singleWhere 或在这种情况下添加一些错误处理。

可以找到更多相关信息 here

class _MyHomePageState extends State<MyHomePage> {
  String _mySelection;

  List<Map> _myJson = [{"id":2,"society":"test","baseUrl":"url.com"},{"id":1,"society":"planeef","baseUrl":"url.com"}];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: new DropdownButton<String>(
          isDense: true,
          hint: new Text("Select"),
          value: _mySelection,
          onChanged: (String newValue) {
             Map<dynamic,dynamic> _myElement = _myJson.singleWhere((test) => test["id"] == int.parse(newValue));
            print(_myElement["baseUrl"]);
            //Add the above two lines

            setState(() {
              _mySelection = newValue;
            });
          },
          items: _myJson.map((Map map) {
            return new DropdownMenuItem<String>(
              value: map["id"].toString(),
              child: new Text(
                map["society"],
              ),
            );
          }).toList(),
        ),
      )
    );
  }
}