带有搜索过滤器的 Flutter 应用网格视图?

Posted

技术标签:

【中文标题】带有搜索过滤器的 Flutter 应用网格视图?【英文标题】:Flutter app grid view with search filter? 【发布时间】:2020-07-02 23:07:40 【问题描述】:

在这个颤振代码中,我在 AppBar 中实现了一个带有搜索过滤器的 Gridview。 目前只显示建筑物名称,但我也想显示建筑物地名? 有什么方法可以同时过滤建筑物名称和地名?

    我还想在网格视图中显示建筑地名-值

    当点击一个grid item时如何获取item id?

    import 'package:flutter/material.dart';
    import 'package:realpro/SizeConfig.dart';
    import 'package:realpro/root/dashscreen.dart';
    
    class SearchList extends StatefulWidget 
      SearchList( Key key ) : super(key: key);
      @override
      _SearchListState createState() => new _SearchListState();
       
      class _SearchListState extends State<SearchList>
      
      Widget appBarTitle = new Text("My Properties", style: new TextStyle(color: 
      Colors.white),);
      Icon actionIcon = new Icon(Icons.search, color: Colors.orange,);
      final key = new GlobalKey<ScaffoldState>();
      final TextEditingController _searchQuery = new TextEditingController();
      List<String>  _list;
      bool _IsSearching;
      String _searchText = "";
      _SearchListState() 
      _searchQuery.addListener(() 
      if (_searchQuery.text.isEmpty) 
      setState(() 
       _IsSearching = false;
       _searchText = "";
       );
       
     else 
    setState(() 
      _IsSearching = true;
      _searchText = _searchQuery.text;
       );
      
     );
     
    @override
    void initState() 
    super.initState();
    _IsSearching = false;
    init();
    
    void init() 
    _list = List();
    _list.add("building 1",);
    _list.add("building 2");
    _list.add("building 3");
    _list.add("building 4");
    _list.add("building 5");
    _list.add("building 6");
    _list.add("building 7");
    _list.add("building 8");
    _list.add("building 9");
    _list.add("building 10");
      
    @override
    Widget build(BuildContext context) 
    SizeConfig().init(context);
    return new Scaffold(
     key: key,
     appBar: buildBar(context),
     body: new GridView.count(
      crossAxisCount: 3,
      padding: EdgeInsets.fromLTRB(10,10,10,10),
      childAspectRatio: 8.0 / 9.0,
      children: _IsSearching ? _buildSearchList() : _buildList(),
       ),
       drawer: Navigationdrawer(),
       );
        
        List<Uiitem> _buildList() 
        return _list.map((contact) => new Uiitem(contact)).toList();
        
        List<Uiitem> _buildSearchList() 
        if (_searchText.isEmpty) 
        return _list.map((contact) => new Uiitem(contact))
        .toList();
         
        else 
        List<String> _searchList = List();
         for (int i = 0; i < _list.length; i++) 
         String  name = _list.elementAt(i);
         if (name.toLowerCase().contains(_searchText.toLowerCase())) 
          _searchList.add(name);
          
         
        return _searchList.map((contact) => new Uiitem(contact))
        .toList();
        
      
      Widget buildBar(BuildContext context) 
       return new AppBar(
        centerTitle: true,
        title: appBarTitle,
        iconTheme: new IconThemeData(color:Colors.orange),
        backgroundColor: Colors.black,
        actions: <Widget>[
      new IconButton(icon: actionIcon, onPressed: () 
        setState(() 
          if (this.actionIcon.icon == Icons.search) 
            this.actionIcon = new Icon(Icons.close, color: Colors.orange,);
            this.appBarTitle = new TextField(
              controller: _searchQuery,
              style: new TextStyle(
                color: Colors.orange,
              ),
              decoration: new InputDecoration(
                  hintText: "Search here..",
                  hintStyle: new TextStyle(color: Colors.white)
              ),
            );
            _handleSearchStart();
          
          else 
            _handleSearchEnd();
             
            );
          ,),
         ]
       );
      
       void _handleSearchStart() 
       setState(() 
       _IsSearching = true;
        );
       
       void _handleSearchEnd() 
       setState(() 
       this.actionIcon = new Icon(Icons.search, color: Colors.orange,);
       this.appBarTitle =
       new Text("My Properties", style: new TextStyle(color: Colors.white),);
       _IsSearching = false;
       _searchQuery.clear();
        );
       
      
     class Uiitem extends StatelessWidget
     final String name;
     Uiitem(this.name);
     Widget build(BuildContext context)
     return new Card(
      margin: EdgeInsets.fromLTRB(5,5,5,7),
      elevation: 10.0,
      child: InkWell(
      splashColor: Colors.orange,
      onTap: ()
      ,
     child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
      AspectRatio(
        aspectRatio: 18.0 / 11.0,
        child: Image.asset('assets/images/build.jpeg',fit: BoxFit.scaleDown,),
      ),
      Padding(
        padding: EdgeInsets.fromLTRB(10.0, 15.0, 0.0,0.0),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(this.name,style: new TextStyle(fontFamily: 'Raleway',fontWeight: 
       FontWeight.bold,fontSize: 14.0),
                maxLines: 1,
                ),
            SizedBox(height: 0.0),
            Text('Place',style: new TextStyle(fontFamily: 'Roboto'),),
          ],
           ),
          ),
        ],
       ),
       ),   
      );
      
     
    

【问题讨论】:

【参考方案1】:

您可以在下面复制粘贴运行完整代码 第 1 步:您可以定义一个 Building 类具有属性 id, name, place 第二步:返回搜索列表不返回List&lt;Uiitem&gt; 第 3 步:使用 GridView.builder 并返回 Uiitem(_searchList[index]); 第 4 步:Uiitem 接受 Building 以便您的 InkWell 可以得到 id

工作演示

完整代码

import 'package:flutter/material.dart';

class Building 
  String id;
  String name;
  String place;

  Building(this.id, this.name, this.place);


class SearchList extends StatefulWidget 
  SearchList(Key key) : super(key: key);
  @override
  _SearchListState createState() => _SearchListState();


class _SearchListState extends State<SearchList> 
  Widget appBarTitle = Text(
    "My Properties",
    style: TextStyle(color: Colors.white),
  );
  Icon actionIcon = Icon(
    Icons.search,
    color: Colors.orange,
  );
  final key = GlobalKey<ScaffoldState>();
  final TextEditingController _searchQuery = TextEditingController();
  List<Building> _list;
  List<Building> _searchList = List();

  bool _IsSearching;
  String _searchText = "";
  _SearchListState() 
    _searchQuery.addListener(() 
      if (_searchQuery.text.isEmpty) 
        setState(() 
          _IsSearching = false;
          _searchText = "";
          _buildSearchList();
        );
       else 
        setState(() 
          _IsSearching = true;
          _searchText = _searchQuery.text;
          _buildSearchList();
        );
      
    );
  
  @override
  void initState() 
    super.initState();
    _IsSearching = false;
    init();
  

  void init() 
    _list = List();
    _list.add(
      Building(id:"1", name: "A 1", place: "google"),
    );
    _list.add(
      Building(id:"2", name: "A 2", place: "google"),
    );
    _list.add(
      Building(id:"3",name: "B 3", place: "facebook"),
    );
    _list.add(
      Building(id:"4",name: "B 4", place: "facebook"),
    );
    _list.add(
      Building(id:"5",name: "C 5", place: "flutter"),
    );
    _searchList = _list;
  

  @override
  Widget build(BuildContext context) 
    //SizeConfig().init(context);
    return Scaffold(
        key: key,
        appBar: buildBar(context),
        body: GridView.builder(
            itemCount: _searchList.length,
            itemBuilder: (context, index) 
              return Uiitem(_searchList[index]);
            ,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
            )

            /* GridView.count(
        crossAxisCount: 3,
        padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
        childAspectRatio: 8.0 / 9.0,
        children: _IsSearching ? _buildSearchList() : _buildList(),
      ),*/
            //drawer: Navigationdrawer(),
            ));
  

  List<Building> _buildList() 
    return _list; //_list.map((contact) =>  Uiitem(contact)).toList();
  

  List<Building> _buildSearchList() 
    if (_searchText.isEmpty) 
      return _searchList =
          _list; //_list.map((contact) =>  Uiitem(contact)).toList();
     else 
      /*for (int i = 0; i < _list.length; i++) 
        String name = _list.elementAt(i);
        if (name.toLowerCase().contains(_searchText.toLowerCase())) 
          _searchList.add(name);
        
      */

      _searchList = _list
          .where((element) =>
              element.name.toLowerCase().contains(_searchText.toLowerCase()) ||
              element.place.toLowerCase().contains(_searchText.toLowerCase()))
          .toList();
      print('$_searchList.length');
      return _searchList; //_searchList.map((contact) =>  Uiitem(contact)).toList();
    
  

  Widget buildBar(BuildContext context) 
    return AppBar(
        centerTitle: true,
        title: appBarTitle,
        iconTheme: IconThemeData(color: Colors.orange),
        backgroundColor: Colors.black,
        actions: <Widget>[
          IconButton(
            icon: actionIcon,
            onPressed: () 
              setState(() 
                if (this.actionIcon.icon == Icons.search) 
                  this.actionIcon = Icon(
                    Icons.close,
                    color: Colors.orange,
                  );
                  this.appBarTitle = TextField(
                    controller: _searchQuery,
                    style: TextStyle(
                      color: Colors.orange,
                    ),
                    decoration: InputDecoration(
                        hintText: "Search here..",
                        hintStyle: TextStyle(color: Colors.white)),
                  );
                  _handleSearchStart();
                 else 
                  _handleSearchEnd();
                
              );
            ,
          ),
        ]);
  

  void _handleSearchStart() 
    setState(() 
      _IsSearching = true;
    );
  

  void _handleSearchEnd() 
    setState(() 
      this.actionIcon = Icon(
        Icons.search,
        color: Colors.orange,
      );
      this.appBarTitle = Text(
        "My Properties",
        style: TextStyle(color: Colors.white),
      );
      _IsSearching = false;
      _searchQuery.clear();
    );
  


class Uiitem extends StatelessWidget 
  final Building building;
  Uiitem(this.building);

  Widget build(BuildContext context) 
    return Card(
      margin: EdgeInsets.fromLTRB(5, 5, 5, 7),
      elevation: 10.0,
      child: InkWell(
        splashColor: Colors.orange,
        onTap: () 
          print(building.id);
        ,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            AspectRatio(
              aspectRatio: 18.0 / 11.0,
              child: Image.asset(
                'assets/images/build.jpeg',
                fit: BoxFit.scaleDown,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(10.0, 15.0, 0.0, 0.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    this.building.name,
                    style: TextStyle(
                        fontFamily: 'Raleway',
                        fontWeight: FontWeight.bold,
                        fontSize: 14.0),
                    maxLines: 1,
                  ),
                  SizedBox(height: 0.0),
                  Text(
                    building.place,
                    style: TextStyle(fontFamily: 'Roboto'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  


void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SearchList(),
    );
  

【讨论】:

但我想把导航抽屉放在那里。 我没有您的抽屉密码。所以我只是说一下。你可以加回来。

以上是关于带有搜索过滤器的 Flutter 应用网格视图?的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 在列表视图中显示网格视图

如何在Flutter(2021)中创建过滤器搜索列表视图

刷新网格后剑道ui网格可分页大小发生变化

交错网格视图在 Flutter 中不向上滚动

Flutter:从网格视图横向滚动的列表视图过渡

flutter - 网格视图不显示在展开的小部件中。