【问题标题】:how to filter json from dropdown in flutter如何从flutter的下拉列表中过滤json
【发布时间】:2019-08-27 10:01:33
【问题描述】:

enter code herehey 各位大师,我有用于过滤 api json 数据的代码,我希望我的用户可以通过下拉菜单中的特定位置选择特定教师。按名称搜索已经可以使用,但下拉列表我不知道如何实现它,以对我的 json api 选择生效。

这是我的代码

import 'package:flutter/material.dart';


void main() {
  runApp(new MaterialApp(
    title: "Para Dai",
    home: new DropDown(),
  ));
}

class DropDown extends StatefulWidget {
  DropDown() : super();


// end
  final String title = "DropDown Demo";

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

class Province {
  int id;
  String name;

  Province(this.id, this.name);

  static List<Province> getProvinceList() {
    return <Province>[
      Province(1, 'Central Java'),
      Province(2, 'East kalimantan'),
      Province(3, 'East java'),
      Province(4, 'Bali'),
      Province(5, 'Borneo'),
    ];
  }
}

// ADD THIS
class District {
  int id;
  String name;

  District(this.id, this.name);

  static List<District> getDistrictList() {
    return <District>[
      District(1, 'Demak'),
      District(2, 'Solo'),
      District(3, 'Sidoarjo'),
      District(4, 'Bandung'),
    ];
  }
}

class DropDownState extends State<DropDown> {
  String finalUrl = '';

  List<Province> _provinces = Province.getProvinceList();
  List<DropdownMenuItem<Province>> _dropdownMenuItems;
  Province _selectedProvince;

  // ADD THIS
  List<District> _disctricts = District.getDistrictList();
  List<DropdownMenuItem<District>> _dropdownMenuDistricts;
  District _selectedDistrict;

  @override
  void initState() {
    _dropdownMenuItems = buildDropdownMenuItems(_provinces);
    _dropdownMenuDistricts = buildDropdownDistricts(_disctricts); // Add this
    _selectedProvince = _dropdownMenuItems[0].value;
    _selectedDistrict = _dropdownMenuDistricts[0].value; // Add this
    super.initState();
  }

  List<DropdownMenuItem<Province>> buildDropdownMenuItems(List provinceses) {
    List<DropdownMenuItem<Province>> items = List();
    for (var province in provinceses) {
      items.add(
        DropdownMenuItem(
          value: province,
          child: Text(province.name),
        ),
      );
    }
    return items;
  }

  // ADD THIS
  List<DropdownMenuItem<District>> buildDropdownDistricts(
      List<District> districts) {
    List<DropdownMenuItem<District>> items = List();
    for (var district in districts) {
      items.add(
        DropdownMenuItem(
          value: district,
          child: Text(district.name),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(Province newProvince) {
    // Add this
    final String url =
        'https://onobang.com/flutter/index.php?province=${newProvince.name}&district=${_selectedDistrict.name}';
    setState(() {
      _selectedProvince = newProvince;
      finalUrl = url; // Add this
    });
  }

  onChangeDistrict(District newDistrict) {
    // Add this
    final String url =
        'https://onobang.com/flutter/index.php?province=${_selectedProvince.name}&district=${newDistrict.name}';
    setState(() {
      _selectedDistrict = newDistrict;
      finalUrl = url; // Add this
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("DropDown Button Example"),
        ),
        body: new Container(
          margin: const EdgeInsets.all(0.0),
          padding: const EdgeInsets.all(13.0),
          child: new Column(
            children: <Widget>[
              new Container(
                margin: const EdgeInsets.all(0.0),
                padding: const EdgeInsets.all(13.0),
                decoration: new BoxDecoration(
                    border: new Border.all(color: Colors.blueGrey)),
                child: new Text(
                    "Welcome to teacher list app, please select teacher by province / district and name"),
              ),
              new Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("Prov : "),
                  SizedBox(
                    height: 20.0,
                  ),
                  DropdownButton(
                    value: _selectedProvince,
                    items: _dropdownMenuItems,
                    onChanged: onChangeDropdownItem,
                  ),
                  SizedBox(
                    height: 20.0,
                  ),
                  // Text('Selected: ${_selectedProvince.name}'),
                  //  SizedBox(
                  //   height: 20.0,
                  // ),

                  Text(" Dist : "),
                  SizedBox(
                    height: 20.0,
                  ),
                  DropdownButton(
                    value: _selectedDistrict,
                    items: _dropdownMenuDistricts,
                    onChanged: onChangeDistrict,
                  ),
                  SizedBox(
                    height: 20.0,
                  ),
                  // Text('Selected: ${_selectedDistrict.name}'),
                  // SizedBox(
                  //   height: 20.0,
                  //  ),
                  // Padding(
                  // padding: const EdgeInsets.all(8.0),
                  // child: Text('$finalUrl'),
                  // ),
                ],
              ),
              new Card(
                  child: new Center(
                      child: TextFormField(
                decoration: InputDecoration(labelText: 'Teacher Name'),
              ))),
              new FlatButton(
                color: Colors.blue,
                textColor: Colors.white,
                disabledColor: Colors.grey,
                disabledTextColor: Colors.black,
                padding: EdgeInsets.all(8.0),
                splashColor: Colors.blueAccent,
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondWidget(value:"$finalUrl"))
                  );
                  // what action to show next screen
                },
                child: Text(
                  "Show List",
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
// ignore: must_be_immutable
class SecondWidget extends StatelessWidget
{
  String value;


  SecondWidget({Key key, @required this.value}):super(key:key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(title: Text("Page 2"),),
        body: Column(children: <Widget>[
          Text("I wish Show JSON Mysql listview with this URL : "+this.value),
          RaisedButton(child: Text("Go Back"),
              onPressed: () {
                Navigator.pop(context);
              }),
        ],)
    );
  }
}

在我是颤振初学者之前非常感谢任何帮助,并且非常难以学习颤振

【问题讨论】:

    标签: flutter flutter-dependencies


    【解决方案1】:

    编辑
    如果您的意思是单击菜单项并更改 _buildSearchResults 的内容, 您的 _buildSearchResults 是基于 List _searchResult 的,您可以像在 onSearchTextChanged 中那样修改内容。在 RaisedButton 中,您可以使用 onPressed
    凸起按钮( 填充:常量 EdgeInsets.all(8.0), 文本颜色:颜色.白色, 颜色:颜色.蓝色, onPressed: (newDistrict) { 设置状态((){ _myDistrict = newDistrict; _searchResult.clear(); //再次重新创建你的_searchResult。 }); }, 孩子:新文本(“提交”), )

    onChanged: (newDistrict) {
                  setState(() {
                    _myDistrict = newDistrict;
                    _searchResult.clear();
                    //recreate your _searchResult again.
                  });
                },
    

    如果我明白您的意思,您正在尝试通过从 API 获取的 JSON 字符串创建 DropdownMenuItem。

    来自不同API的JSON,你可以加入他们

    List<Map> _jsonApi1 = [
      {"id": 0, "name": "default 1"}
    ];
    List<Map> _jsonApi2 = [
      {"id": 1, "name": "second 2"},
      {"id": 2, "name": "third 3"}
    ];
    List<Map> _myJson = new List.from(_jsonApi1)..addAll(_jsonApi2);
    

    生成菜单项

    new DropdownButton<String>(
                      isDense: true,
                      hint: new Text("${_jsonApi1[0]["name"]}"),
                      value: _mySelection,
                      onChanged: (String newValue) {
                        setState(() {
                          _mySelection = newValue;
                        });
    
                        print(_mySelection);
                      },
                      items: _myJson.map((Map map) {
                        return new DropdownMenuItem<String>(
                          value: map["id"].toString(),
                            child: new Text(
                              map["name"],
                            ),
                        );
                      }).toList(),
    

    完整代码

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    List<Map> _jsonApi1 = [
      {"id": 0, "name": "default 1"}
    ];
    List<Map> _jsonApi2 = [
      {"id": 1, "name": "second 2"},
      {"id": 2, "name": "third 3"}
    ];
    List<Map> _myJson = new List.from(_jsonApi1)..addAll(_jsonApi2);
    
    class _MyHomePageState extends State<MyHomePage> {
      String _mySelection;
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          body: SafeArea(
            child: Column(
              children: <Widget>[
                Container(
                  height: 500.0,
                  child: new Center(
                    child: new DropdownButton<String>(
                      isDense: true,
                      hint: new Text("${_jsonApi1[0]["name"]}"),
                      value: _mySelection,
                      onChanged: (String newValue) {
                        setState(() {
                          _mySelection = newValue;
                        });
    
                        print(_mySelection);
                      },
                      items: _myJson.map((Map map) {
                        return new DropdownMenuItem<String>(
                          value: map["id"].toString(),
                            child: new Text(
                              map["name"],
                            ),
                        );
                      }).toList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 不,兄弟,我的代码,下拉菜单已经来自 api。我的问题是,当我的下拉菜单点击时,它对搜索结果生效。
    • 你的意思是点击菜单项后,再次调用api还是点击菜单项更改列表_searchResult?您的 _buildSearchResults 是基于 List _searchResult 的,您可以像在 onSearchTextChanged 中那样修改内容。
    • 我可以使用提交按钮吗?我选择下拉菜单,而不是在文本框中填写名称,而不是单击提交按钮,有没有这样的示例代码?
    • 在 RaisedButton 中,您可以在 onPressed 中执行相同的操作,我已经编辑了答案并添加了 RaisedButton 代码示例。
    • 对不起,我是初学者,可能是因为它无法实现你的示例代码,我更新了我的示例代码,也许我的意思很容易表达。
    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多