Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ How to Implement Adaptive Pageview in Flutter

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š How to Implement Adaptive Pageview in Flutter


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Exciting News! Our blog has a new Home! ๐Ÿš€

Background

The PageView widget allows user to transition between different screens in their Flutter application. As per Flutter doc,

PageView is a scrollable list that works page by page. Each child of a page view is forced to be the same size as the viewport.

Each child within a PageView is typically constrained to the same size as the viewport, limiting flexibility in layout design. But what if we want our PageView to dynamically adjust its size based on the content it contains?

In this article, weโ€™ll implement the PageView with children of different heights to make it flexible.

What weโ€™ll achieve at the end of this blog?

Implement Adaptive Pageview in Flutter

You can find the full source code on GitHub.

Table of Content

  • Background
  • Let's get started
  • Implement Adaptive PageView
    • Implement SizeNotifier Widget
    • Implement PageView using SizeNotifier
    • Use Custom ThreePageScrollView
    • Add PageContoller to PageView
    • Add ThreePageScrollView to UI
    • Enhance PageView Scrolling with FastPageViewScrollPhysics
  • Conclusion

Let's get started

First, let's quickly have a look at the Pageview in Flutter, For simplicity, we have added a simple UI.

class StarterPageView extends StatelessWidget {
  StarterPageView({super.key});

  final List<int> items= List.generate(5, (index) => index);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 400,
      child: PageView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Container(
              margin: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color:Colors.black,
              ),
              child: Wrap(
                children: List.generate(index+1, (index) {
                  return Container(
                    margin: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.yellow,
                    ),
                    height: 50,
                    child: ListTile(
                      title: Text('Page ${index+1}'),
                    ),
                  );

                }),
              )
          );
        },
      ),
    );
  }
}

Here is the result,

Flutter PageView with Static Layout

The problem with the Pageview in Flutter is it canโ€™t have dynamic height.

If we have a tab that might have a height of 100 px and another 200 px then it canโ€™t adjust the height to the currently displayed page. ๐Ÿ˜ž๐Ÿ˜ž

Our goal? To create a PageView that adjusts its dimensions based on its content. So, Letโ€™s start implementing it without wasting time.

Implement Adaptive PageView

We'll divide implementation into 5 simple steps to make each step easy to understand.

Implement SizeNotifier Widget

To implement dynamic sizing within our PageView, we'll start by implementing a widget that measures the size of the child and notifies the parent widget if the child's size is different than the previous one.

class SizeNotifierWidget extends StatefulWidget {
  final Widget child;
  final ValueChanged<Size> onSizeChange;

  const SizeNotifierWidget({
    super.key,
    required this.child,
    required this.onSizeChange,
  });

  @override
  State<SizeNotifierWidget> createState() => _SizeNotifierWidgetState();
}

class _SizeNotifierWidgetState extends State<SizeNotifierWidget> {
  Size? _oldSize;

  @override
  void didUpdateWidget(covariant SizeNotifierWidget oldWidget) {
    WidgetsBinding.instance.addPostFrameCallback((_) => _notifySize());
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  void _notifySize() {
    final size = context.size;
    if (size != null && _oldSize != size) {
      _oldSize = size;
      widget.onSizeChange(size);
    }
  }
}

This widget is used to monitor the size of its child widget and trigger a callback whenever that size changes. Letโ€™s break it down,

It takes two required parameters,

  • child: The child widget that this SizeNotifierWidget will render.

  • onSizeChange: A callback function that will be invoked whenever the size of this widget changes.

Inside the didUpdateWidget() Method,

  • This method is called whenever the widget is rebuilt with a different configuration.

  • Inside this method, a post-frame callback is added using WidgetsBinding.instance.addPostFrameCallback(). This callback ensures that _notifySize() is called after the frame is rendered. This is necessary because the size of a widget is only available after it has been laid out on the screen.

Implement PageView using SizeNotifier

Now, weโ€™ll use this widget to measure the size of the current item in the PageView. So, whenever the child has a different height then it notifies about that.

class ThreePageScrollView extends StatefulWidget {
  final Widget current;

  const ThreePageScrollView({
    super.key,
    required this.current,
  });

  @override
  State<ThreePageScrollView> createState() => _ThreePageScrollViewState();
}

class _ThreePageScrollViewState extends State<ThreePageScrollView> {
  double? _currentItemHeight;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Opacity(
          opacity: 0,
          child: SizeNotifierWidget(
            child: widget.current,
            onSizeChange: (size) {
              setState(() {
                _currentItemHeight = size.height;
              });
            },
          ),
        ),
        SizedBox(
            height: _currentItemHeight ?? 0,
            child: PageView(
              children: [
                widget.current,
              ],
            )),
      ],
    );
  }
}

The code is pretty simple, here we've used the SizeNotifier widget to measure the size of the current item and set that size to give it to PageView.
Let's add a simple UI to see if it's working or not.

Use Custom ThreePageScrollView

We'll add a simple UI to verify its functionality.

class FinalPageView extends StatelessWidget {
  FinalPageView({super.key});

  int itemCount = 1; // Number of items in the page view

  @override
  Widget build(BuildContext context) {
    return ThreePageScrollView(
      current: getItem(),
    );
  }

  Widget getItem() {
    return Container(
        margin: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.black,
        ),
        child: Wrap(
          children: List.generate(itemCount, (index) {
            return Container(
              margin: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Colors.yellow,
              ),
              height: 50,
              child: ListTile(
                title: Text('Page ${index + 1}'),
              ),
            );
          }),
        ));
  }
}

The code is pretty straightforward, we have used our Custom PageView and added a child from the getItem() function. Let's see what it looks like,

Custom PageView

Ah, got it!!

Now, let's make it swipeable.๐Ÿ˜ƒ

Add PageController to PageView
Weโ€™ll implement the PageViewController to manage PageView and to make it scrollable.

class ThreePageScrollView extends StatefulWidget {
  final Widget current;
  final Widget? next;
  final Widget? previous;
  final Function(int)? onPageChanged;

  const ThreePageScrollView({
    super.key,
    required this.current,
    this.next,
    this.previous,
    required this.onPageChanged,
  });

  @override
  State<ThreePageScrollView> createState() => _ThreePageScrollViewState();
}

class _ThreePageScrollViewState extends State<ThreePageScrollView> {
  late PageController _pageController;

  double? _currentItemHeight;
  late int currentPage;

  @override
  void initState() {
    super.initState();
    currentPage = widget.previous == null ? 0 : 1;

    _pageController = PageController(initialPage: currentPage);
    _pageController.addListener(() {
      final newPage = _pageController.page?.toInt();
      if (newPage == null || newPage.toDouble() != _pageController.page) return;

      if (newPage == currentPage) {
        return;
      }

      _pageController.jumpToPage(1);
      widget.onPageChanged!(newPage > currentPage ? 1 : -1);
      currentPage = 1;
    });
  }

  @override
  void didUpdateWidget(covariant ThreePageScrollView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.previous != oldWidget.previous) {
      final newPage = widget.previous == null ? 0 : 1;
      if (newPage != currentPage) {
        currentPage = newPage;
        _pageController.jumpToPage(newPage);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
      ....
        SizedBox(
            height: _currentItemHeight ?? 0,
            child: PageView(
              controller: _pageController,
              physics: const FastPageViewScrollPhysics(),
              children: [
                if (widget.previous != null) widget.previous!,
                widget.current,
                if (widget.next != null) widget.next!,
              ],
            )),
      ],
    );
  }
}

Here we have-
Before implementing PageContoller, it's essential to have the previous and next child other than the current one to make it scrollable. So, We have set the following parameters,

  • next: A widget representing the next page.
  • previous: A widget representing the previous page.
  • onPageChanged(int): A callback function that is invoked when the page changes. It receives an integer parameter indicating the direction of the change (-1 for the previous, 1 for the next).

Variables: _pageController to manage PageView and currentPage variable is used to keep track of the current page index.

initState() Method

  • Sets the initial page based on whether previous is provided. If previous is null, set the current page to 0; otherwise, set it to 1.
  • Adds a listener to _pageController to detect page changes. When the page changes, it calls widget.onPageChanged with the direction of the change.

didUpdateWidget() Method

It checks if previous has changed and updates the current page accordingly. If previous becomes null, it sets the current page to 0; otherwise, it sets it to 1.

To read the full version, please visit this blog.

Weโ€™re Grateful to have you with us on this journey!

I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.

Follow Canopas to get updates on interesting articles!

...



๐Ÿ“Œ How to Implement Adaptive Pageview in Flutter


๐Ÿ“ˆ 73.82 Punkte

๐Ÿ“Œ Flutter Performance, Flutter Games, Flutter Tooling, & More (#AskFlutter at Flutter Live)


๐Ÿ“ˆ 47.89 Punkte

๐Ÿ“Œ PageView - Flutter Widget of the Week


๐Ÿ“ˆ 47.34 Punkte

๐Ÿ“Œ Nevma Adaptive Images Plugin up to 0.6.66 on WordPress adaptive-images-script.php $REQUEST['adaptive-images-settings'] directory traversal


๐Ÿ“ˆ 39.47 Punkte

๐Ÿ“Œ Origin of Flutter, Dart 2.0, E-Commerce with Flutter, & More (#AskFlutter at Flutter Live)


๐Ÿ“ˆ 35.92 Punkte

๐Ÿ“Œ Flutter news from GDD China: uniting Flutter on web and mobile, and introducing Flutter 1.9


๐Ÿ“ˆ 35.92 Punkte

๐Ÿ“Œ Implement React v18 from Scratch Using WASM and Rust - [10] Implement Update for Single Node.


๐Ÿ“ˆ 26.64 Punkte

๐Ÿ“Œ Implement React v18 from Scratch Using WASM and Rust - [11] Implement Event System


๐Ÿ“ˆ 26.64 Punkte

๐Ÿ“Œ Xbox Adaptive Controller kann bald mit "Adaptive Kit" erweitert werden


๐Ÿ“ˆ 26.31 Punkte

๐Ÿ“Œ Nevma Adaptive Images Plugin up to 0.6.66 on WordPress adaptive-images-script.php Parameter privilege escalation


๐Ÿ“ˆ 26.31 Punkte

๐Ÿ“Œ Microsoft Devices Adaptive Accessories review: Crazily adaptive and customizable


๐Ÿ“ˆ 26.31 Punkte

๐Ÿ“Œ How To Create Adaptive And Responsive NavBar in Flutter?


๐Ÿ“ˆ 25.13 Punkte

๐Ÿ“Œ Mastering Adaptive Flutter Themes: Crafting a Responsive Theme Selector Page


๐Ÿ“ˆ 25.13 Punkte

๐Ÿ“Œ Hamilton app built with Flutter and featured on iOS and Android (Flutter Developer Story)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Hamilton app built with Flutter and featured on iOS and Android (Flutter Developer Story)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ FLUTTER & DART โ€“ THE COMPLETE FLUTTER APP DEVELOPMENT COURSE


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Adding a Streams API to a Flutter Plugin - The Boring Flutter Development Show, Ep. 7.5


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Q&A and Tour of Flutter Samples Index - The Boring Flutter Development Show, Ep. 7.4


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ How to Publish a Flutter Package - The Boring Flutter Development Show, Ep. 7.3


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Alibaba used Flutter to build 50+ million user Xianyu app (Flutter Developer Story)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Publishing a Flutter App to the Play Store (The Boring Flutter Development Show, Ep. 8.4)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter's Search Support - The Boring Flutter Development Show


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Exploring Flutter Samples and Examples (The Boring Flutter Development Show, Ep. 11)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter Live - Flutter Announcements and Updates (Livestream)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter Design (Flutter Live)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter Design (Flutter Live)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Announcing Flutter 1.0 (Flutter Live)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Announcing Flutter 1.0 (Flutter Live)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter 1.0, Square Reader SDK, 2Dimensions Flare, & More! (Flutter Live Top 5 Recap)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter 1.0, Square Reader SDK, 2Dimensions Flare, & More! (Flutter Live Top 5 Recap)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Flutter Development (Flutter Live)


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Google Maps for Flutter, Platform Channels, Mobile Ads, & More - #AskFlutter at Flutter Live


๐Ÿ“ˆ 23.95 Punkte

๐Ÿ“Œ Reverse Engineering a Flutter app by recompiling Flutter Engine


๐Ÿ“ˆ 23.95 Punkte











matomo