RefreshIndicator Widget and Attributes

RefreshIndicator Widget and Attributes

ยท

2 min read

In mobile app development, providing users with a seamless and responsive experience is crucial. One way to enhance user interaction is by incorporating a pull-to-refresh feature, allowing users to update content effortlessly. Flutter's RefreshIndicator widget is the perfect tool for achieving this functionality. In this blog post, we'll explore the RefreshIndicator widget along with its key attributes and provide a complete example to help you implement pull-to-refresh in your Flutter app.

The RefreshIndicator widget is a part of the Flutter framework designed specifically for adding pull-to-refresh functionality to your app. It provides a visual cue to users, indicating that they can refresh the content by dragging down the screen.

Attributes of RefreshIndicator:

  1. onRefresh (required):

    • A callback function triggered when the user initiates the refresh action. This is where you should implement the logic to update your data.
  2. child (required):

    • The widget that holds the content you want to refresh. This can be a ListView, GridView, or any other scrollable widget.
  3. color:

    • The color of the refresh indicator.
  4. backgroundColor:

    • The background color of the refresh indicator.
  5. displacement:

    • The distance from the top where the indicator should trigger the refresh.

Example:

Let's create a simple Flutter app with a RefreshIndicator to refresh a list of items. We'll use a ListView for this example.

// main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pull-to-Refresh Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> items = List.generate(10, (index) => 'Item $index');

  Future<void> _refresh() async {
    // Simulate a delay for fetching new data
    await Future.delayed(Duration(seconds: 2));

    // Update the list with new data
    setState(() {
      items = List.generate(10, (index) => 'New Item $index');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pull-to-Refresh Example'),
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) => ListTile(
            title: Text(items[index]),
          ),
        ),
      ),
    );
  }
}

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย