如何从flutter的下拉列表中过滤json

时间:2019-08-27 10:01:33

标签: flutter flutter-dependencies

enter code here您好,主人,我在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);
              }),
        ],)
    );
  }
}

在我成为扑扑初学者之前非常感谢,而且很难学会扑扑

1 个答案:

答案 0 :(得分:0)

修改
如果您是指单击菜单项并更改_buildSearchResults的内容, 您的_buildSearchResults基于List _searchResult,像在onSearchTextChanged中所做的那样修改内容即可。在RaisedButton中,您可以使用onPressed
完成此操作     加高按钮(                     填充:const EdgeInsets.all(8.0),                     textColor:Colors.white,                     颜色:Colors.blue,                     onPressed:(newDistrict){                                  setState((){                                 _myDistrict = newDistrict;                                 _searchResult.clear();                                  //再次重新创建_searchResult。                               });                     },                     子级:new Text(“ Submit”),                   )

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

如果我明白您的意思,您正在尝试通过JSON字符串(从API获取)创建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(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

enter image description here