首页 > 解决方案 > Flutter - 列表视图中的选项卡过滤

问题描述

我有All、Bar、Supermarket、Restaurant... 等标签。我想要做的是,每当我点击“全部”时,它应该显示来自 firestore 的全部数据,但是每当我点击其他选项卡时,它应该相应地过滤列表视图......

这是选项卡的代码

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Categories extends StatefulWidget {
  @override
  _CategoriesState createState() => _CategoriesState();
}

class _CategoriesState extends State<Categories> {
  List<String> companyTypes = [];

  int selectedIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 20),
      child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection('Company-Categories')
            .orderBy('comptype')
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            Text('Loading');
          } else {
            companyTypes = ['All'];
            for (int i = 0; i < snapshot.data.docs.length; i++) {
              DocumentSnapshot snap = snapshot.data.docs[i];
              companyTypes.add(snap.data()['comptype']);
            }
            return Padding(
              padding: EdgeInsets.symmetric(vertical: 20),
              child: SizedBox(
                height: 35, // 35
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: companyTypes.length,
                  itemBuilder: (context, index) => buildCategoriItem(index),
                ),
              ),
            );
          }
          return Container(width: 0.0, height: 0.0);
        },
      ),
    );
  }

  Widget buildCategoriItem(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
      child: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 0),
        padding: EdgeInsets.symmetric(
          horizontal: 20, //20
          vertical: 5, //5
        ),
        decoration: BoxDecoration(
            color:
                selectedIndex == index ? Color(0xFFEFF3EE) : Colors.transparent,
            borderRadius: BorderRadius.circular(
              16, // 16
            )),
        child: Text(
          companyTypes[index],
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color:
                selectedIndex == index ? Color(0xFF84AB5C) : Color(0xFFC2C2B5),
          ),
        ),
      ),
    );
  }
}

这是列表视图的代码

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:url_launcher/url_launcher.dart';

class ContactCard extends StatefulWidget {
  @override
  _ContactCardState createState() => _ContactCardState();
}

class _ContactCardState extends State<ContactCard> {
  ScrollController _scrollController = new ScrollController();
  List<String> companyTypes = [];
  // By default first one is selected

  @override
  Widget build(BuildContext context) {
    void customLaunch(command) async {
      if (await canLaunch(command)) {
        await launch(command);
      } else {
        print(' could not launch $command');
      }
    }

    return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('Phonebook')
          .orderBy('name')
          .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

        return ListView(
          scrollDirection: Axis.vertical,
          controller: _scrollController,
          shrinkWrap: true,
          children: snapshot.data.docs.map((document) {
            return Padding(
              padding: const EdgeInsets.only(left: 15, right: 15),
              child: Card(
                child: ListTile(
                  leading: CircleAvatar(
                    radius: 20,
                    child: ClipOval(
                      child: SizedBox(
                        height: 100,
                        width: 100,
                        child: Image.network(
                          document['logo'],
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Flexible(
                        child: Text(
                          document['name'],
                          style: TextStyle(fontSize: 14),
                        ),
                      ),
                      CircleAvatar(
                        backgroundColor: Colors.white12,
                        child: IconButton(
                          icon: Icon(
                            Icons.call,
                          ),
                          onPressed: () {
                            var callNum = document['primaryPhone'];
                            customLaunch("tel:$callNum"); //;
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }).toList(),
        );
      },
    );
  }
}

最后,这是主页

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:phonebook_admin/Screens/Add/addButtonsPage.dart';

import 'contact_card.dart';
import 'widgets/categories.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(
            Icons.add,
            color: Colors.white,
            size: 30,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AddButtonsPage()),
            );
          },
        ),
        title: Center(
          child: Text('Phonebook'),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
              size: 30,
            ),
            onPressed: () {
              // do something
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Column(
            children: <Widget>[
              Categories(),
              ContactCard(),
            ],
          ),
        ),
      ),
    );
  }
}

标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读