Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: cannot access context in onSwipe when no cards left then "destroy" the widget tree #29

Merged
merged 1 commit into from
Jan 9, 2024

Conversation

husainazkas
Copy link
Contributor

@husainazkas husainazkas commented Jan 8, 2024

Description

Step to Reproduce Issue:

  1. Create a StatefulWidget for a page:
class FirstPage extends StatefulWidget {
  ...
}

class _FirstPageState extends State<FirstPage> {
  final List<Model> datas = [
    ...
  ];

  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return currentIndex == (datas.length - 1)
      ? NoDataLeft() // Another widget to show no data message
      : MyCards(
          datas: datas,
          onLiked: (index) {
            currentIndex = index;
            setState(() {});
          },
        );
    }
}
  1. Create a single common widget
class MyCards extends StatelessWidget {
  final List<Model> datas;
  final ValueChanged<int> onLiked;

  const MyCards({super.key, required this.datas, required this.onLiked});

  @override
  Widget build(BuildContext context) {
    return CardSwiper(
      onSwipe: (previousIndex, currentIndex, direction) {
        // If the last card swiped and disposed, this block cannot access context's inheritance anymore
        // For example:
        context.read<MyProvider>();
      },
      cardsCount: widget.items.length,
      cardBuilder: (context, index, xPercent, yPercent) {
        return MyCardItemView(
          onLiked: () {
            onLiked(index);
          },
        );
      },
    );
  }
}

Error will appears and points to card_swiper.dart line 251.

This PR will fix the issue, just to arrange order when to call super.dispose().

Pre-launch Checklist

Visual reference

@ricardodalarme
Copy link
Owner

thank you!

@ricardodalarme ricardodalarme merged commit 6df02e3 into ricardodalarme:main Jan 9, 2024
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants