繁体   English   中英

如何在用户中进行特定搜索

[英]how to make specific search by user in flutter

 final String url = 'https://onobang.com/flutter'; // here is my backend code decrlareData.dart class UserDetails { final String id; final String firstName, proVinsi, link, profileUrl, ket, kab; UserDetails({ this.id, this.firstName, this.proVinsi, this.link, this.profileUrl, this.ket, this.kab, }); factory UserDetails.fromJson(Map<String, dynamic> json) { return new UserDetails( id: json['id'], firstName: json['name'], proVinsi: json['provinsi'], profileUrl: "https://onobang.com/daiku/ajaximageupload/manajemen/uploads/" + json['file_name'], ket: json['ket'], link: json['link'], kab: json['kabupaten'], ); } } 

 import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; import 'declareData.dart'; import 'detail.dart'; // here is my fetch data and view with search result, class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); @override _HomePageState createState() => new _HomePageState(); } class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin { List<UserDetails> _searchResult = []; List<UserDetails> _userDetails = []; TextEditingController controller = new TextEditingController(); // Get json result and convert it to model. Then add Future<Null> getUserDetails() async { final response = await http.get(url); final responseJson = json.decode(response.body); setState(() { for (Map user in responseJson) { _userDetails.add(UserDetails.fromJson(user)); } }); } @override void initState() { super.initState(); getUserDetails(); } Widget _buildUsersList() { return new ListView.builder( itemCount: _userDetails.length, itemBuilder: (context, index) { return new Card( child: new ListTile( leading: new CircleAvatar( backgroundImage: new NetworkImage( _userDetails[index].profileUrl, ), ), title: new Text(' Nama : ' + _userDetails[index].firstName + ' ' + _userDetails[index].kab), subtitle: new Text('Provinsi : ' + _userDetails[index].proVinsi ), isThreeLine: true, trailing: (IconButton( icon: Icon(Icons.expand_more), ) ), onTap: () { var route = new MaterialPageRoute( builder: (BuildContext context) => new SecondScreen(value: _userDetails[index]), ); Navigator.of(context).push(route); }, ), margin: const EdgeInsets.all(0.0), ); }, ); } //Widget futureBuilder() { //future: Widget _buildSearchResults() { return new ListView.builder( itemCount: _searchResult.length, itemBuilder: (context, i) { return new Card( child: new ListTile( leading: new CircleAvatar( backgroundImage: new NetworkImage( _searchResult[i].profileUrl, ), ), title: new Text(_searchResult[i].firstName + ' || Kab ' + _searchResult[i].kab), subtitle: new Text('Prov : ' + _searchResult[i].proVinsi), onTap: () { var route = new MaterialPageRoute( builder: (BuildContext context) => new SecondScreen(value: _searchResult[i]), ); Navigator.of(context).push(route); }, ), margin: const EdgeInsets.all(0.0), ); }, ); } Widget _buildSearchBox() { return new Padding( padding: const EdgeInsets.all(8.0), child: new Card( child: new ListTile( leading: new Icon(Icons.search), title: new TextField( controller: controller, decoration: new InputDecoration( hintText: 'Search', border: InputBorder.none), onChanged: onSearchTextChanged, ), trailing: new IconButton( icon: new Icon(Icons.cancel), onPressed: () { controller.clear(); onSearchTextChanged(''); }, ), ), ), ); } Widget _buildBody() { return new Column( children: <Widget>[ FlatButton.icon( color: Colors.white, icon: Icon(FontAwesomeIcons.whatsapp), //`Icon` to display label: Text('089xxxx465'), //`Text` to display onPressed: () { launch('https://www.instagram.com/?hl=id'); }, ), new Container( color: Theme.of(context).primaryColor, child: _buildSearchBox()), new Expanded( child: _searchResult.length != 0 || controller.text.isNotEmpty ? _buildSearchResults() : _buildUsersList()), ], ); } @override Widget build(BuildContext context) { return new Scaffold( body: _buildBody(), // body: new RefreshIndicator(child: null, onRefresh: null), resizeToAvoidBottomPadding: true, ); } onSearchTextChanged(String text) async { _searchResult.clear(); if (text.isEmpty) { setState(() {}); return; } _userDetails.forEach((userDetail) { if (userDetail.firstName.toUpperCase().contains(text.toUpperCase()) || userDetail.proVinsi.toUpperCase().contains(text.toUpperCase())|| userDetail.kab.toUpperCase().contains(text.toUpperCase())) _searchResult.add(userDetail); }); setState(() {}); } } 

 import 'package:flutter/material.dart'; import 'declareData.dart'; import 'package:flutube/flutube.dart'; import 'package:flutter/services.dart'; // here is the single post class SecondScreen extends StatefulWidget { final UserDetails value; SecondScreen({Key key, this.value}) : super(key: key); @override _SecondScreenState createState() => _SecondScreenState(); } //detail start class _SecondScreenState extends State<SecondScreen> { int currentPos; String stateText; @override void initState() { currentPos = 0; stateText = "Video not started"; super.initState(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(title: new Text('Profil Ustad')), body: new Container( child: new Center( child: Column( children: <Widget>[ Padding( child: new Text( '${widget.value.firstName}', style: new TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0, ), textAlign: TextAlign.center, ), padding: EdgeInsets.only(top: 20.0), ), /* Padding( //`widget` is the current configuration. A State object's configuration //is the corresponding StatefulWidget instance. child: Image.network('${widget.value.profileUrl}'), padding: EdgeInsets.all(12.0), ),*/ Padding( child: new Text( 'Nama : ${widget.value.firstName}', style: new TextStyle(fontWeight: FontWeight.bold), textAlign: TextAlign.left, ), padding: EdgeInsets.all(10.0), ), Padding( child: new Text( 'PROVINSI : ${widget.value.proVinsi}', style: new TextStyle(fontWeight: FontWeight.bold), textAlign: TextAlign.left, ), padding: EdgeInsets.all(0.0), ), Padding( child: new Text( 'Ket : ${widget.value.ket}', style: new TextStyle(fontWeight: FontWeight.bold), textAlign: TextAlign.justify, ), padding: EdgeInsets.all(10.0), ), ], ), ), ), ); } } 

我试图在扑扑中进行特定的搜索,情况是,我希望用户可以选择为省和地区的选项,而不是在用户选择所需的特定位置之后,单击按钮,然后从中获取数据mysql json.so我希望我可以更改url变量中的值,而不是从json中获取特定数据。

final String url = 'https://onobang.com/flutter/index.php?'+'province='

 import 'package:flutter/material.dart'; void main() { runApp(new MaterialApp( title: "Para Dai", home: new DropDown(), )); } import 'package:flutter/material.dart'; class DropDown extends StatefulWidget { DropDown() : super(); final String title = "DropDown Demo"; @override DropDownState createState() => DropDownState(); } class Provinces { int id; String name; Provinces(this.id, this.name); static List<Provinces> getCompanies() { return <Provinces>[ Provinces(1, 'Central Java'), Provinces(2, 'East kalimantan'), Provinces(3, 'East java'), Provinces(4, 'Bali'), Provinces(5, 'Borneo'), ]; } } class DropDownState extends State<DropDown> { // List<Provinces> _provinceses = Provinces.getCompanies(); List<DropdownMenuItem<Provinces>> _dropdownMenuItems; Provinces _selectedProvinces; @override void initState() { _dropdownMenuItems = buildDropdownMenuItems(_provinceses); _selectedProvinces = _dropdownMenuItems[0].value; super.initState(); } // here the url i wish can dynamicly edit by user input final String url = 'https://onobang.com/flutter/index.php?'+'province='_selectedProvinsi.name+'district'some.district; List<DropdownMenuItem<Provinces>> buildDropdownMenuItems(List provinceses) { List<DropdownMenuItem<Provinces>> items = List(); for (Provinces province in provinceses) { items.add( DropdownMenuItem( value: province, child: Text(province.name), ), ); } return items; } onChangeDropdownItem(Provinces selectedProvinces) { setState(() { _selectedProvinces = selectedProvinces; }); } @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( child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("Select a province"), SizedBox( height: 20.0, ), DropdownButton( value: _selectedProvinces, items: _dropdownMenuItems, onChanged: onChangeDropdownItem, ), SizedBox( height: 20.0, ), Text('Selected: ${_selectedProvinces.name}'), ], ), ), ), ), ); } } 

演示版

你需要这样的东西吗?

演示版

您可以使用此仓库Github在本地构建它

该怎么办

  1. 使地区课程与省相似
  2. 启动区域下拉菜单
  3. 设置selectedDistrict的初始值
  4. 最后,在调用setState之前修改URL

完整代码

import 'package:flutter/material.dart';

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

  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(
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("Select a province"),
                SizedBox(
                  height: 20.0,
                ),
                DropdownButton(
                  value: _selectedProvince,
                  items: _dropdownMenuItems,
                  onChanged: onChangeDropdownItem,
                ),
                SizedBox(
                  height: 20.0,
                ),
                Text('Selected: ${_selectedProvince.name}'),

                SizedBox(
                  height: 20.0,
                ),
                Text("Select a district"),
                SizedBox(
                  height: 20.0,
                ),
                // Add this
                DropdownButton(
                  value: _selectedDistrict,
                  items: _dropdownMenuDistricts,
                  onChanged: onChangeDistrict,
                ),
                SizedBox(
                  height: 20.0,
                ),
                Text('Selected: ${_selectedDistrict.name}'),
                SizedBox(
                  height: 30.0,
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('$finalUrl'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM