我单击的那个特定盒子的flutter更改setstateicon
我想在点击的循环中更改该特定盒子的图标。 我有两个具有ONTAP功能的图标。然后,单击用户添加到最爱列表以及响应ID成功并添加到最爱时,则更改了框FAV图标。但是在我的情况下,成功响应后,它更改了循环中所有盒子的图标。 因此,请帮助我如何添加图标/或最爱SVG图像的索引。
这是我的代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Persondetail.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mindmatch/utils/Auth.dart';
class Sent extends StatefulWidget {
Sent({Key? key}) : super(key: key);
@override
_Sent createState() => _Sent();
}
class _Sent extends State<Sent>{
var UsrID = Auth.prefs?.getString('usrid');
var data;
var usrpic = "";
var user = "";
var usridf = "";
var favicon = "assets/images/Fav_1.svg";
@override
void initState() {
super.initState();
getData();
}
getData() async{
//var res = await http.get(Uri(host: url));
var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
data = jsonDecode(res.body);
print(data);
setState(() {});
print(res.body);
}
@override
Widget build(BuildContext context){
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
return
data != null? Expanded(
child: Padding(
padding: sidePadding,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//maxCrossAxisExtent: 200,
crossAxisCount: 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 0.75,
),
itemCount: data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Auth.prefs?.setString('profid', data[index]['id']);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Persondetail()),
);
},
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Stack(
children: [
Positioned(
top: 5,
right: 5,
child: InkWell(
onTap: () async{
usridf = data[index]['id'];
user = '${UsrID}';
final body = null;
final url = Uri.https('www.*******.net', '/index.php',{'act':'addfav','usridf': usridf, 'user': user});
final response = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: body
);
print(url);
int statusCode = response.statusCode;
//var responseBody = json.decode(response.body);
Map<String, dynamic> responseBody = jsonDecode(response.body);
setState(() {});
var list = responseBody['error'];
var stringList = list.join("\n");
print(stringList); //Prints "in new line"
var statusRes = responseBody['status'];
//var UserPhone = responseBody['phone'];
//var UserID = responseBody['usrid'];
if(statusRes == 'add success'){
print('success: '+statusRes);
} else if(statusRes == 'remove success') {
print('success: '+statusRes);
} else {
print('error: '+statusRes);
}
setState(() {
favicon = "assets/images/Fav_2.svg";
});
},
child: SvgPicture.asset(
width: 30,
favicon,
height: 30,
),
),
),
Positioned(
bottom: 5,
left: 10,
right: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//Row(
//mainAxisAlignment: MainAxisAlignment.start,
//children: <Widget>[
SizedBox(width: 5.0),
Text(
data[index]['fulname'],
style: TextStyle(
color: Colors.white,
fontSize: 15
),
),
addVerticalSpace(0),
Text(
'Dieppe, Canada.',
style: TextStyle(
color: Colors.white,
fontSize: 10
),
)
//],
//),
],
),
Column(
//textDirection: TextDirection.rtl,
children: [
CircleAvatar(
radius: 18,
backgroundColor: Color(0xff8f9df2),
child: IconButton(
icon: SvgPicture.asset(
'assets/images/f_chat.svg',
width: 18,
height: 18,
),
onPressed: () {},
),
),
],
),
]
),
),
],
),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage("https://www.*******.net/files/profile/${data[index]['profimage']}"),
colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.3), BlendMode.darken),
),
),
),
);
},
)
)
): const Center(
child: CircularProgressIndicator(),
);
}
}
请帮助我如何执行此操作,并更改我单击的该框的SVG图像/图标。
I want to change icon of that specific box in a loop that I click.
I have two icons that have onTap functionality. and on click user add to fav list and when the response id success and add to fav then the box fav icon changed. but in my case after the success response, it changed the icon of all boxes in the loop.
So please help with how I add indexing for an icon/or fav SVG image.
here is my code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Persondetail.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mindmatch/utils/Auth.dart';
class Sent extends StatefulWidget {
Sent({Key? key}) : super(key: key);
@override
_Sent createState() => _Sent();
}
class _Sent extends State<Sent>{
var UsrID = Auth.prefs?.getString('usrid');
var data;
var usrpic = "";
var user = "";
var usridf = "";
var favicon = "assets/images/Fav_1.svg";
@override
void initState() {
super.initState();
getData();
}
getData() async{
//var res = await http.get(Uri(host: url));
var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
data = jsonDecode(res.body);
print(data);
setState(() {});
print(res.body);
}
@override
Widget build(BuildContext context){
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
return
data != null? Expanded(
child: Padding(
padding: sidePadding,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//maxCrossAxisExtent: 200,
crossAxisCount: 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 0.75,
),
itemCount: data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Auth.prefs?.setString('profid', data[index]['id']);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Persondetail()),
);
},
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Stack(
children: [
Positioned(
top: 5,
right: 5,
child: InkWell(
onTap: () async{
usridf = data[index]['id'];
user = '${UsrID}';
final body = null;
final url = Uri.https('www.*******.net', '/index.php',{'act':'addfav','usridf': usridf, 'user': user});
final response = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: body
);
print(url);
int statusCode = response.statusCode;
//var responseBody = json.decode(response.body);
Map<String, dynamic> responseBody = jsonDecode(response.body);
setState(() {});
var list = responseBody['error'];
var stringList = list.join("\n");
print(stringList); //Prints "in new line"
var statusRes = responseBody['status'];
//var UserPhone = responseBody['phone'];
//var UserID = responseBody['usrid'];
if(statusRes == 'add success'){
print('success: '+statusRes);
} else if(statusRes == 'remove success') {
print('success: '+statusRes);
} else {
print('error: '+statusRes);
}
setState(() {
favicon = "assets/images/Fav_2.svg";
});
},
child: SvgPicture.asset(
width: 30,
favicon,
height: 30,
),
),
),
Positioned(
bottom: 5,
left: 10,
right: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//Row(
//mainAxisAlignment: MainAxisAlignment.start,
//children: <Widget>[
SizedBox(width: 5.0),
Text(
data[index]['fulname'],
style: TextStyle(
color: Colors.white,
fontSize: 15
),
),
addVerticalSpace(0),
Text(
'Dieppe, Canada.',
style: TextStyle(
color: Colors.white,
fontSize: 10
),
)
//],
//),
],
),
Column(
//textDirection: TextDirection.rtl,
children: [
CircleAvatar(
radius: 18,
backgroundColor: Color(0xff8f9df2),
child: IconButton(
icon: SvgPicture.asset(
'assets/images/f_chat.svg',
width: 18,
height: 18,
),
onPressed: () {},
),
),
],
),
]
),
),
],
),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage("https://www.*******.net/files/profile/${data[index]['profimage']}"),
colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.3), BlendMode.darken),
),
),
),
);
},
)
)
): const Center(
child: CircularProgressIndicator(),
);
}
}
Please help me with how I do this and changed the SVG image/icon of that box that I click.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是因为您正在为类变量设置图标,因此您面临此问题。
声明这样的favicon列表的变量。
在您的getData方法中,这样修改以生成等于数据长度的n数字的粉丝。
或者,您甚至可以将图标属性应用到数据中,并以后使用它,而无需创建单独的变量,您应该根据数据处理图标。我用简单的推动创建了一个列表。
在Tap方法上
,使用Favicon:
除此之外,请尝试使用SetState()一次进行操作。您称之为两次。
That's because you are setting the icon for the class variable and hence you are facing this issue.
Declare a variable for a list of favIcon like this.
In your getData method modify like this to generate n numbers of favicons equal to the length of data.
Or you can even app Icon property to the data and use it later without creating a separate variable and you should handle the icons based on the data. I created a list with a plain simple push.
And on tap method
And while using favIcon:
Apart from this, try to use setState() only once for an action. You are calling it twice.