Flutter 如何更改图标按钮列表视图的颜色加载颤振
我有一个帖子列表视图,并且在每一行或帖子中都有类似的图标按钮。现在用户可以喜欢任何帖子。现在我需要检查用户是否喜欢一篇文章,并且该文章的图标按钮将是蓝色的。用户不喜欢的帖子,图标按钮颜色将为灰色。当邮件列表加载时,我需要检查它Flutter 如何更改图标按钮列表视图的颜色加载颤振,flutter,listview,iconbutton,Flutter,Listview,Iconbutton,我有一个帖子列表视图,并且在每一行或帖子中都有类似的图标按钮。现在用户可以喜欢任何帖子。现在我需要检查用户是否喜欢一篇文章,并且该文章的图标按钮将是蓝色的。用户不喜欢的帖子,图标按钮颜色将为灰色。当邮件列表加载时,我需要检查它 class HomePage extends StatefulWidget { String userId; // receive userId from the Login as a parameter HomePage(this.userId); @
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);
}
类主页扩展StatefulWidget{
字符串用户标识;
//从登录名接收userId作为参数
主页(this.userId);
@凌驾
_LoginPagentate createState()=>_LoginPagentate();
}
类_loginpagentate扩展状态{
无功电流定位;
变量位置名称;
变数pinCode;
内部计数器;
地图数据;
bool isPressed=false;
字符串documentId;
bool isLikedPressedFrmFirestore=false;
void _incrementCounter(){
_计数器++;
isPressed=true;
updateLikeData();
}
void userIdExistForLikeOrNot()异步{
DocumentReference docRef=FirebaseFirestore.instance.collection('feeds').getDocuments()作为DocumentReference;
DocumentSnapshot docSnapshot=等待docRef.get();
List likedUser=docSnapshot.data();
if(likeuser.contains(widget.userId)==true){
isPressed=true;
}否则{
isPressed=false;
}
打印(已打印);
}
代码继续
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(),*/
),
),
);
}
}
Widget getIcon(documentId){
回归未来建设者(
生成器:(BuildContext上下文,异步快照){
Color Color=Colors.grey;//设置正确的默认颜色
if(snapshot!=null&&snapshot.connectionState==connectionState.done&&
snapshot.hasData!=null){
color=Colors.blue;//设置合适的“喜欢的”颜色
}
返回图标(
图标。竖起大拇指,
颜色:颜色,
);
},
未来:checkFeedLikedOrNot(文档ID),
);
}
Future updateLikeData()异步{
//FirebaseFirestore.instance.collection('feeds').doc(documentId).update({“like_count”:{u counter,});
DocumentReference docRef=FirebaseFirestore.instance.collection('feeds').doc(documentId);
DocumentSnapshot docSnapshot=等待docRef.get();
List likedUser=docSnapshot.data();
if(likeuser.contains(widget.userId)==true){
打印('user ready exist='+widget.userId);
docRef.update({“like_count”:{u计数器,'is_liked':false,'liked_user_id':FieldValue.arrayRemove([widget.userId]);
}否则{
docRef.update({“like_count”:{u counter,'is_liked':true,'liked_user_id':FieldValue.arrayUnion([widget.userId]);
//docRef.update({'userid':FieldValue.arrayUnion([documentId]));
}
}
未来checkFeedLikedOrNot(documentId)异步{
DocumentReference docRef=FirebaseFirestore.instance.collection('post').doc(documentId);
DocumentSnapshot docSnapshot=等待docRef.get();
List likedUser=docSnapshot.data();
返回likeuser.contains(widget.userId);
}
/*checkFeedLikedOrNot()异步{
DocumentReference docRef=FirebaseFirestore.instance.collection('feeds').doc(documentId);
DocumentSnapshot docSnapshot=等待docRef.get();
List likedUser=docSnapshot.data();
if(likeuser.contains(widget.userId)==true){
打印('user ready exist='+widget.userId);
//颜色将是蓝色
}否则{
//颜色将是灰色的
}
}*/
getUserLocation()async{//在需要时调用此异步方法
位置数据定位;
字符串错误;
位置=新位置();
试一试{
myLocation=等待位置。getLocation();
}平台上异常捕获(e){
如果(e.code=='权限被拒绝'){
错误='请授予权限';
打印(错误);
}
如果(e.code=='PERMISSION\u DENIED\u NEVER\u ASK'){
错误='权限被拒绝-请从应用程序设置启用';
打印(错误);
}
myLocation=null;
}
currentLocation=myLocation;
最终坐标=新坐标(
myLocation.纬度,myLocation.经度);
var addresses=await Geocoder.local.findAddressesFromCoordinates(
坐标);
var first=addresses.first;
locationName=('Location:${first.Location}adminArea:${first.adminArea}地址行:${first.addressLine}');
打印(${first.locality}、${first.adminArea}、${first.subLocality}、${first.subAdminArea}、${first.addressLine}、${first.featureName}、${first.throughtree}、${first.subthroughtree});
先返回;
}
@凌驾
void initState(){
super.initState();
getUserLocation();
//fetchLikeData();
userIdExistForLikeOrNot();
}
/*小部件getIcon(文档ID){
回归未来建设者(
生成器:(上下文,快照){
Color Color=Colors.grey;//设置正确的默认颜色
如果(snapshot.connectionState!=connectionState.none&&
snapshot.hasData!=null){
color=Colors.blue;//设置合适的“喜欢的”颜色
}
返回图标(
图标。竖起大拇指,
颜色:颜色,
);
},
未来:checkFeedLikedOrNot(文档ID),
);
}*/
流博客流;
@凌驾
小部件构建(构建上下文){
返回脚手架(
背景颜色:Colors.blue,
appBar:appBar(
标题:世界其他地区(
mainAxisAlignment:mainAxisAlignment.spaceBetween,
儿童:[
文本(“主页”),
升起的按钮(
已按下:(){
导航器。推(
上下文
MaterialPage路由(生成器:(上下文)=>CreateFeed()),
);
},
//导航子页面(上下文);
子项:文本(“创建提要”,样式:TextStyle(颜色:Colors.blue,fontWeight:fontWeight.bold,fontSize:13.0)),
颜色:颜色,白色,
形状:RoundedRectangleBorder(borderRadius:borderRadius.circular(5.0)),
),
],