Как получить доступ к свойствам предка во Флаттере - PullRequest
0 голосов
/ 19 июня 2019

У меня есть виджет для создания элемента списка.Это выглядит так:

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)),
              ],
            ),
          ),
        ],
      ))
    ]));
  }
}

В этом элементе представления списка будет другой виджет, который выглядит следующим образом:

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 в виджете предка выше.Как я могу это сделать?

...