Home > other >  How to not bounce and scroll when within screen size
How to not bounce and scroll when within screen size

Time:12-09

When I run the following code on an iPhone, the GridView bounces.

If the contents of the GridView over the iPhone screen size, I want it to scroll, but if it is within the iPhone screen size, I do not want it to bounce or scroll.

How do I modify the code below?

import 'package:flutter/material.dart';

void main() {
  runApp(const DemoPage());
}

class DemoPage extends StatelessWidget {
  const DemoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Demo'),
        ),
        body: GridView.count(
          crossAxisCount: 2,
          mainAxisSpacing: 8,
          crossAxisSpacing: 8,
          children: const [
            Text("A"),
            Text("B"),
          ],
        ),
      )
    );
  }
}

As a side note, when launched in Chrome as shown below, it does not bounce if the content is smaller than the screen size, so it is working as expected. I would like to have this behavior on iPhone app as well.

$ flutter run
Multiple devices found:
...
[1]: macOS (macos)
[2]: Chrome (chrome)
Please choose one (To quit, press "q/Q"): 2

CodePudding user response:

I use the responsive_builder library when I want to use different logics on different devices.

You can use the following code as an answer to your question.

ScreenTypeLayout(
  // if device is mobile phone..
  mobile: GridView.count(
    physics: const NeverScrollableScrollPhysics(),
    crossAxisCount: 2,
    mainAxisSpacing: 8,
    crossAxisSpacing: 8,
    children: const [
      Text("A"),
      Text("B"),
    ],
  ),
  // if device is tablet..
  tablet: GridView.count(
    physics: const BouncingScrollPhysics(),
    crossAxisCount: 2,
    mainAxisSpacing: 8,
    crossAxisSpacing: 8,
    children: const [
      Text("A"),
      Text("B"),
    ],
  ),
);

CodePudding user response:

I noticed that primary is mentioned in document physics.

Defaults to matching platform conventions. Furthermore, if primary is false, then the user cannot scroll if there is insufficient content to scroll, while if primary is true, they can always attempt to scroll.

And below is mentioned in primary.

When this is true, the scroll view is scrollable even if it does not have sufficient content to actually scroll. Otherwise, by default the user can only scroll the view if it has sufficient content. See physics.

Just add primary: false,.

import 'package:flutter/material.dart';

void main() {
  runApp(const DemoPage());
}

class DemoPage extends StatelessWidget {
  const DemoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Demo'),
        ),
        body: GridView.count(
          primary: false, //            
  • Related