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

时间:2019-08-22 04:23:07

标签: flutter flutter-layout flutter-dependencies

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中获取数据。所以我希望我可以更改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}'),
          ],
        ),
      ),
    ),
  ),
);
  }
}

1 个答案:

答案 0 :(得分:0)

演示

您需要这样的东西吗?

Demo

您可以使用此仓库Github

在本地构建它

该做什么

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

完整代码

INVOICE INVOICE