mirkancal
mirkancal

Reputation: 5345

How to use RefreshIndicator without Scroll widget?

I'm trying to use RefreshIndicator but without using a scrolling widget, I can't use it. My goal is here is to just to show a Text widget and add pull to refresh functionality.

 if (snapshot.data.isEmpty) {
            return RefreshIndicator(
              onRefresh: () async {
                _init();
              },
              child: Center(
                child: Text('No data'),
              ),
            );
          }

I've wrapped my Text('No data') widget in a SingleChildScrollView but it didn't work. My solution is now below but it looks ugly. Is there a better way to do it?

  if (snapshot.data.isEmpty) {
            return RefreshIndicator(
              onRefresh: () async {
                _init();
                print('we scrolled');
              },
              child: Center(
                child: ListView.builder(
                  itemCount: 1,
                  itemBuilder: (context, index) {
                    return Text('No data\nPull to Refresh');
                  },
                ),
              ),
            );
          }

enter image description here

Upvotes: 0

Views: 1525

Answers (2)

Fady Fawzy
Fady Fawzy

Reputation: 51

I've created a versatile SmartRefreshIndicator widget that can be used with

both scrollable and non-scrollable child widgets.

It's perfect for integrating pull-to-refresh functionality in various UI elements, such as ListView, Column, or any widget that requires refresh capabilities.

class SmartRefreshIndicator extends StatelessWidget {
  final Future<void> Function() onRefresh;
  final Widget child;
  final bool isChildScrollable;

  const SmartRefreshIndicator({
    super.key,
    required this.onRefresh,
    required this.child,
    this.isChildScrollable = false,
  });

  @override
  Widget build(context) {
    return LayoutBuilder(
      builder: (context, constraints) => RefreshIndicator(
        onRefresh: onRefresh,
        child: isChildScrollable
            ? child
            : SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: SizedBox(
                  height: constraints.maxHeight,
                  child: child,
                ),
              ),
      ),
    );
  }
}

Feel free to extend and customize it further to match your specific needs!

Upvotes: 0

Ali Bacelonia
Ali Bacelonia

Reputation: 1343

set physics to always scrollable

ListView.builder(
              physics:AlwaysScrollableScrollPhysics(),
              itemCount: 1,
              itemBuilder: (context, index) {
                return Text('No data\nPull to Refresh');
              },
            )

Upvotes: 3

Related Questions