Flutter: Firebase How to change the query and the

2019-07-14 00:46发布

问题:

I am trying to change the query according to the selected community.

When you select the community you must show the content of this community.

I have found a solution but I do not think it is the right one, because the application has 39 countries.

Those 39 require you to have a query for each one and there are many lines of code.

I hope there is some better solution than what I found.

GIF APP - The error that appears is because there is no other country.

SearchClub.dart

This is the function that returns a query related to the countries.

I want to use one and not make several queries for each country.

searchClubs(TextEditingController countryChanged) {
        var widgetFireUpdate;
        setState(() {
            if(countryChanged.text == 'SPAIN') {
              widgetFireUpdate = new FirebaseAnimatedList(
                query: FirebaseDatabase.instance.reference().child(widget.player.platform).child("CLUB").orderByChild('country').equalTo(countryChanged.text),
                sort: (a, b) => a.value['createdDate'].compareTo(b.value['createdDate']),
                reverse: true,
                shrinkWrap: true,
                defaultChild: new CircularProgressIndicator(),
                itemBuilder: (BuildContext context, DataSnapshot snapshot,
                    Animation<double> animation, int index) {
                  return new StreamBuilder<Event>(
                    stream: itemRef2.orderByKey().onValue,
                    builder: (context, AsyncSnapshot<Event> snapshot2){
                      if(snapshot2.hasData) {
                        try {
                          return new Container(
                            decoration: new BoxDecoration(
                              color: Colors.grey[300],
                            ),
                            child: new ListTile(
                                leading: snapshot.value['logoURL'].toString().indexOf('images/assets/logo_notfound.png') == -1 ? new CachedNetworkImage(imageUrl: snapshot.value['logoURL'], width: MediaQuery.of(context).size.width/8) : new Image.asset(snapshot.value['logoURL'], width: MediaQuery.of(context).size.width/8),
                                title: new Text(snapshot.value['name'].toUpperCase(), style: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context).size.width/30)),
                                subtitle: new RichText(
                                  text: new TextSpan(
                                      children: <TextSpan>[
                                        new TextSpan(text: "CAPITÁN:", style: new TextStyle(color: Colors.black, fontSize: MediaQuery.of(context).size.width/35, fontWeight: FontWeight.bold)),
                                        new TextSpan(text: " ${snapshot.value['captain'].toUpperCase()}", style: new TextStyle(color: Colors.black, fontSize: MediaQuery.of(context).size.width/35)),
                                      ]
                                  ),
                                ),
                            ),
                          );

                        }catch(e) {
                          return new Container();
                        }
                      } else if(snapshot2.hasError){
                        return new Container();
                      } else {
                        return new Container(
                          child: new Center(
                            child: new CircularProgressIndicator(
                              backgroundColor: Colors.red,
                            ),
                          ),
                        );
                      }
                    },
                  );
                },
              );
            } else if(countryChanged.text == 'BRAZIL') {
              widgetFireUpdate = new FirebaseAnimatedList(
                query: FirebaseDatabase.instance.reference().child(widget.player.platform).child("CLUB").orderByChild('country').equalTo(countryChanged.text),
                sort: (a, b) => a.value['createdDate'].compareTo(b.value['createdDate']),
                reverse: true,
                shrinkWrap: true,
                defaultChild: new CircularProgressIndicator(),
                itemBuilder: (BuildContext context, DataSnapshot snapshot,
                    Animation<double> animation, int index) {
                  return new StreamBuilder<Event>(
                    stream: itemRef2.orderByKey().onValue,
                    builder: (context, AsyncSnapshot<Event> snapshot2){
                      if(snapshot2.hasData) {
                        try {
                          return new Container(
                            decoration: new BoxDecoration(
                              color: Colors.grey[300],
                            ),
                            child: new ListTile(
                              leading: snapshot.value['logoURL'].toString().indexOf('images/assets/logo_notfound.png') == -1 ? new CachedNetworkImage(imageUrl: snapshot.value['logoURL'], width: MediaQuery.of(context).size.width/8) : new Image.asset(snapshot.value['logoURL'], width: MediaQuery.of(context).size.width/8),
                              title: new Text(snapshot.value['name'].toUpperCase(), style: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context).size.width/30)),
                              subtitle: new RichText(
                                text: new TextSpan(
                                    children: <TextSpan>[
                                      new TextSpan(text: "CAPITÁN:", style: new TextStyle(color: Colors.black, fontSize: MediaQuery.of(context).size.width/35, fontWeight: FontWeight.bold)),
                                      new TextSpan(text: " ${snapshot.value['captain'].toUpperCase()}", style: new TextStyle(color: Colors.black, fontSize: MediaQuery.of(context).size.width/35)),
                                    ]
                                ),
                              ),
                            ),
                          );

                        }catch(e) {
                          return new Container();
                        }
                      } else if(snapshot2.hasError){
                        return new Container();
                      } else {
                        return new Container(
                          child: new Center(
                            child: new CircularProgressIndicator(
                              backgroundColor: Colors.red,
                            ),
                          ),
                        );
                      }
                    },
                  );
                },
              );
            }
        });
        return widgetFireUpdate;
      }


  // OPEN LIST COMMUNITY
  Widget _buildBottomPicker() {
    final FixedExtentScrollController scrollController = new FixedExtentScrollController();
    return new Container(
      height: MediaQuery.of(context).size.height/3.5,
      color: CupertinoColors.white,
      child: new DefaultTextStyle(
        style: const TextStyle(
          color: CupertinoColors.black,
          fontSize: 22.0,
        ),
        child: new SafeArea(
          child: new CupertinoPicker(
            scrollController: scrollController,
            itemExtent: MediaQuery.of(context).size.height/15,
            magnification: 0.7,
            diameterRatio: 0.5,
            backgroundColor: CupertinoColors.white,
            onSelectedItemChanged: (int index) {
              setState(() {
                _comunidad.text = _comunidades[index];
                _imgComunidad = _imgComunidades[index];
              });
            },
            children: new List<Widget>.generate(_comunidades.length, (int index) {
              return new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  new Text(_comunidades[index]),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }


@override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: searchBar.build(context),
      body: new Container(
        color: widget.themeConsole,
        child: new Column(
          children: <Widget>[
            new Card(
              elevation: 0.0,
              color: Colors.grey[50],
              child: new Container(
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Container(
                      width: MediaQuery.of(context).size.width/1.35,
                      child: new TextFormField(
                        controller: _comunidad,
                        style: new TextStyle(color: Colors.white),
                        enabled: false,
                        decoration: new InputDecoration(
                          labelText: 'Community:',
                          labelStyle: new TextStyle(color: Colors.white),
                          icon: new Image.asset(_imgComunidad, width: 24.0),
                          filled: true,
                          fillColor: Colors.grey[800],
                        ),
                        validator: (String value){
                          player.country = value;
                        },
                      ),
                    ),
                    new IconButton(
                      icon: new Icon(Icons.flag, color: Colors.grey[800], size: 30.0,),
                      color: Colors.black,
                      onPressed: ()async {
                        await showModalBottomSheet<void>(
                          context: context,
                          builder: (BuildContext context) {
                            return _buildBottomPicker();
                          },
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            new Flexible(child: searchClubs(_comunidad))
          ],
        )
      ),
    );
  }

SearchClub Complete: https://pastebin.com/zbeU6M1u