我有一个小部件来创建列表视图项。看起来像这样:
class UploadedChallengeItem extends StatefulWidget {
final ChallengeUpload challengeUploadForItem;
final User user;
UploadedChallengeItem(
{Key key, @required this.challengeUploadForItem, this.user})
: super(key: key);
@override
_UploadedChallengeItemState createState() => _UploadedChallengeItemState();
}
class _UploadedChallengeItemState extends State<UploadedChallengeItem> {
@override
void dispose() {
super.dispose();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return
Container(
child: Row(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.08,
child: Row(
children: <Widget>[
Container(
width: (MediaQuery.of(context).size.width / 5) * 3,
child: Text(" " +
widget.challengeUploadForItem.score.toString() +
" points",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
))),
Container(
width: MediaQuery.of(context).size.width / 5,
alignment: Alignment.centerRight,
child: UpvoteButton(
challengeUploadForItem: widget.challengeUploadForItem,
user: widget.user)),
],
),
),
],
))
]));
}
}
在此列表视图项中,将有另一个看起来像这样的Widget:
class UpvoteButton extends StatefulWidget {
final ChallengeUpload challengeUploadForItem;
final User user;
UpvoteButton({Key key, @required this.challengeUploadForItem, this.user})
: super(key: key);
@override
_UpvoteButtonState createState() => _UpvoteButtonState();
}
class _UpvoteButtonState extends State<UpvoteButton> {
@override
void dispose() {
super.dispose();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: FlatButton(
onPressed: widget.challengeUploadForItem.checkIfUpvoted()
? null
: () => _postUpvoteChallengeUpload(
context, widget.challengeUploadForItem),
child: widget.challengeUploadForItem.checkIfUpvoted()
? Image.asset('assets/images/icupfilled.png', color: Colors.black)
: Image.asset('assets/images/icupoutline.png',
color: Colors.black)),
);
}
Future _postUpvoteChallengeUpload(
BuildContext context, ChallengeUpload challengeUpload) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token");
var url = RConstants.API_BASE_URL +
"/v1/challenges/upload/upvote/" +
challengeUpload.id.toString();
Response response = await Dio()
.post(url, options: Options(headers: {"Authorization": accessToken}));
setState(() {
widget.challengeUploadForItem.userUpvoted = "1";
widget.challengeUploadForItem.userDownvoted = "0";
widget.challengeUploadForItem.score = widget.challengeUploadForItem.score + 1;
});
} catch (e) {
Alert(
style: AlertStyle(
isCloseButton: false,
),
context: context,
title: "Something Went Wrong",
desc:
"Something went wrong while fetching the current challenge: " +
e.toString(),
type: AlertType.error)
.show();
}
}
}
现在,当我点击UpvoteButton小部件时,我想更新上方祖先小部件中的challengeUploadForItem
。我该如何实现?