Flutter:如何从社会获取基本网址?

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

为了进行身份验证,我想从下拉列表中恢复所选公司的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(),
        ),
    );
  }
}
flutter dart base-url
1个回答
0
投票

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

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

注意-如果有重复项或找不到元素,则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(),
        ),
      )
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.