如何解决如何更改IconButton listview onload的颜色
我有帖子的列表视图,每行或每个帖子中都有一个类似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,);
}*/
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,fontSize: 15.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"],fit: BoxFit.cover,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"),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(),*/
),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。