首页 > 解决方案 > 如何在颤动中按用户进行特定搜索

问题描述

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 中获取特定数据。

最终字符串 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}'),
          ],
        ),
      ),
    ),
  ),
);
  }
}

标签: flutterflutter-layoutflutter-dependencies

解决方案


演示

你需要这样的东西吗?

演示

你可以使用这个 repo 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'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


推荐阅读