乐闻世界logo
搜索文章和话题

Which Flutter widget enables screen refresh?

2024年7月4日 01:22

In Flutter, the widget that enables screen refresh is RefreshIndicator. This widget is commonly used to wrap a scrollable widget, such as ListView or ScrollView, and when the user pulls down, it triggers a callback to refresh the data and rebuild the UI.

Usage Example

Here is a basic example using RefreshIndicator:

dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: HomeScreen(), ); } } class HomeScreen extends StatefulWidget { _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { List<String> items = List.generate(20, (i) => "Item $i"); Future<void> refreshList() async { await Future.delayed(Duration(seconds: 2)); // Simulate a network request setState(() { items = List.generate(40, (i) => "Refreshed item $i"); }); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Refresh Indicator Demo")), body: RefreshIndicator( onRefresh: refreshList, child: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ListTile(title: Text(items[index])); }, ), ), ); } }

In this example, we create a RefreshIndicator that wraps ListView.builder. The onRefresh property is an asynchronous callback that updates the list data. In this function, Future.delayed is used to simulate a network request, and setState is called to update the UI and add more items to the list. When the user pulls down on the ListView, RefreshIndicator displays a loading animation until the asynchronous operation completes.

This approach is ideal for implementing the 'pull-to-refresh' functionality, enhancing user experience by allowing users to update page content with simple gestures.

标签:Flutter