как изменить цвет флаттера при загрузке списка IconButton

У меня есть список сообщений и кнопка "Нравится" в каждой строке или сообщении. Теперь пользователь может лайкать любой пост. Теперь мне нужно проверить, понравился ли пользователю пост, и этот пост, как iconButton, будет синим. Сообщение, которое не понравилось пользователю, цвет iconButton будет серым. И мне нужно проверить это, когда загружается список сообщений.

class HomePage extends StatefulWidget {

  String userId;
// receive userId from the Login as a parameter
  HomePage(this.userId);


  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<HomePage> {

  var currentLocation;
  var locationName;
  var pinCode;
  int _counter;
  Map data;
  bool isPressed = false;
  String documentId;
  bool isLikedPressedFrmFirestore =  false;

  void _incrementCounter() {
      _counter++;
      isPressed= true;
      updateLikeData();
  }


    void userIdExistForLikeOrNot() async {
      DocumentReference docRef = FirebaseFirestore.instance.collection('feeds').getDocuments() as DocumentReference;
      DocumentSnapshot docSnapshot = await docRef.get();
      List likedUser = docSnapshot.data()['liked_user_id'];
      if(likedUser.contains(widget.userId) == true){
        isPressed = true;
      }else{
        isPressed = false;
      }
      print(isPressed);
    }

Код продолжить...

  Widget getIcon(documentId) {
    return FutureBuilder<bool>(
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        Color color = Colors.grey; // set proper default color
        if (snapshot != null && snapshot.connectionState == ConnectionState.done &&
            snapshot.hasData != null) {
          color = Colors.blue; // set proper "liked" color
        }
        return Icon(
          Icons.thumb_up,
          color: color,
        );
      },
      future: checkFeedLikedOrNot(documentId),
    );
  }


  Future<void> updateLikeData() async{
    //FirebaseFirestore.instance.collection('feeds').doc(documentId).update({"like_count":_counter,});
    DocumentReference docRef = FirebaseFirestore.instance.collection('feeds').doc(documentId);
    DocumentSnapshot docSnapshot = await docRef.get();
    List likedUser = docSnapshot.data()['liked_user_id'];
    if(likedUser.contains(widget.userId) == true){
      print('user already exist=='+ widget.userId);
      docRef.update({"like_count":_counter, 'is_liked':false,'liked_user_id': FieldValue.arrayRemove([widget.userId])});
    }else{
      docRef.update({"like_count":_counter,'is_liked':true, 'liked_user_id': FieldValue.arrayUnion([widget.userId])});
      //docRef.update({'liked_user_id' : FieldValue.arrayUnion([documentId])});
    }
  }

  Future<bool> checkFeedLikedOrNot(documentId) async {
    DocumentReference docRef = FirebaseFirestore.instance.collection('post').doc(documentId);
    DocumentSnapshot docSnapshot = await docRef.get();
    List likedUser = docSnapshot.data()['liked_user_id'];
    return likedUser.contains(widget.userId);
  }

  /*checkFeedLikedOrNot() async{
    DocumentReference docRef = FirebaseFirestore.instance.collection('feeds').doc(documentId);
    DocumentSnapshot docSnapshot = await docRef.get();
    List likedUser = docSnapshot.data()['liked_user_id'];
    if(likedUser.contains(widget.userId) == true){
      print('user already exist=='+ widget.userId);
      //color will be blue
    }else{
      //color will be grey
    }
  }*/



  getUserLocation() async {//call this async method from whereever you need

    LocationData myLocation;
    String error;
    Location location = new Location();
    try {
      myLocation = await location.getLocation();
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'please grant permission';
        print(error);
      }
      if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
        error = 'permission denied- please enable it from app settings';
        print(error);
      }
      myLocation = null;
    }
    currentLocation = myLocation;
    final coordinates = new Coordinates(
        myLocation.latitude, myLocation.longitude);
    var addresses = await Geocoder.local.findAddressesFromCoordinates(
        coordinates);
    var first = addresses.first;


    locationName = ('locality: ${first.locality} adminArea: ${first.adminArea} addressLine: ${first.addressLine}');
    print(' ${first.locality}, ${first.adminArea},${first.subLocality}, ${first.subAdminArea},${first.addressLine}, ${first.featureName},${first.thoroughfare}, ${first.subThoroughfare}');

    return first;
  }
  @override
  void initState() {
    super.initState();
    getUserLocation();
    //fetchLikeData();
    userIdExistForLikeOrNot();
  }

  /*Widget getIcon(documentId) {
    return FutureBuilder(
      builder: (context, snapshot) {
        Color color = Colors.grey; // set proper default color
        if (snapshot.connectionState != ConnectionState.none &&
            snapshot.hasData != null) {
          color = Colors.blue; // set proper "liked" color
        }
        return Icon(
          Icons.thumb_up,
          color: color,
        );
      },
      future: checkFeedLikedOrNot(documentId),
    );
  }*/




  Stream blogsStream;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[

            Text('Home Page'),
            RaisedButton(
              onPressed:(){
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => CreateFeed()),
                );

              },
              // navigateToSubPage(context);
              child: Text("Create Feed", style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold,fontSize: 13.0 )),
              color: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),

            ),

          ],
        ),
        centerTitle: false,

      ),
      body: SingleChildScrollView(
      child: Container(
          color: Colors.white,
        child: /*blogsStream != null ?*/
             Column(
              children: <Widget>[
                StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance.collection("feeds").snapshots(),
                builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapshot){
                  if(querySnapshot.hasError)
                    return Text("Some Error");

                  if(querySnapshot.connectionState == ConnectionState.waiting){
                    return CircularProgressIndicator();
                  }else{

                    final list = querySnapshot.data.docs;

                    return ListView.builder(
                      shrinkWrap: true,
                      primary: false,
                      itemCount: list.length,
                      itemBuilder:(context, index)  {
                        print(index);
                        return Card(
                          elevation: 5,
                          shape: Border(bottom: BorderSide(color: Colors.lightBlue, width: 5)),
                            child: Column(
                                children: <Widget> [
                                  ListTile(

                                    leading: CircleAvatar(
                                        radius: 30.0,
                                        backgroundImage:
                                        NetworkImage(list[index].data()["profileImg"]),
                                        backgroundColor: Colors.transparent,
                                    ),
                                    trailing: RaisedButton(
                                      onPressed: () {
                                        Alert(context: context, title: "My Location", desc: locationName).show();
                                      },
                                      color: Colors.blue,
                                      child: Text("Location", style: TextStyle(color: Colors.white70,fontWeight: FontWeight.bold,fontSize: 15.0 )),
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                                    ),
                                    title: Text(list[index].data()["authorName"]),
                                    subtitle: Text(list[index].data()["title"]),

                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                                    width: MediaQuery.of(context).size.width,
                                    //child: Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."),
                                    child: Text(list[index].data()["desc"]),
                                  ),
                                  Container(
                                      padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                                      //child: Image.asset("playstore.png", height: 150,fit:BoxFit.fill)
                                      child: CachedNetworkImage(
                                        imageUrl: list[index].data()["imgUrl"],
                                        width: MediaQuery.of(context).size.width,
                                        fit: BoxFit.cover,
                                      ),

                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,

                                      children: <Widget> [
                                        Row(
                                          children: <Widget>[
                                            new IconButton(
                                              icon: getIcon(list[index].id),
                                              //icon: new Icon(Icons.thumb_up),
                                              //color: await checkFeedLikedOrNot(list[index].id) ? Colors.blue : Colors.grey,
                                              //color:(isPressed) ? Color(0xff007397) : Color(0xff9A9A9A),
                                              onPressed: (){
                                                 print(widget.userId); // userId
                                                 documentId = list[index].id;
                                                _counter = list[index].data()["like_count"];
                                                _incrementCounter();
                                              },
                                            ),

                                            Text('Like'),
                                            SizedBox(width : 5),// to generate space between icon and text
                                             //Text('$_counter'),
                                            //Text( _counter.toString()),
                                            Text(list[index].data()["like_count"].toString()),
                                            SizedBox(width : 23),
                                          ],
                                        ),
                                        Row(
                                          children: <Widget> [
                                            Text("280 Comments"),
                                            SizedBox(width : 23),
                                            Text("29 Shares")
                                          ],
                                        ),
                                        SizedBox(height: 10),
                                      ],
                                    ),
                                  ),
                                  /*Divider(                 // ListView divider
                                    color: Theme.of(context).cardColor,
                                  )*/
                                  SizedBox.fromSize(    // To increase the card bottom
                                    size: Size(0, 20),
                                  ),
                                ],
                              )
                        );

                      },

                    );
                  }
                }
            )
          ],
        )
            /*: Container(
          alignment: Alignment.center,
          child: CircularProgressIndicator(),*/
        ),
      ),
      );

  }

}

0 ответов

Другие вопросы по тегам