Flutter 案例学习之:下拉刷新

Flutter 案例学习之:下拉刷新_第1张图片

GitHub:https://github.com/happy-python/flutter_demos/tree/master/swipe_to_refresh_demo

在 Flutter 中使用 RefreshIndicator 来实现下拉刷新的功能。

A widget that supports the Material "swipe to refresh" idiom.

When child of RefreshIndicator is over scrolled , an animated circular progress indicator is displayed & onRefresh callback is called. Callback returns a future, after complete of which UI is updated & refresh indicator disappears.

In this example we will load random user profile using free API RandomUser, which provides random user on each refresh.

Things to remember while implementing RefreshIndicator is:

  • RefreshIndicator requires key to implement state.
  • onRefresh(RefreshCallback) method required completable future.
  • child is typically ListView or CustomScrollView.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tutorial',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage("Refresh Indicator"),
    );
  }
}

class HomePage extends StatefulWidget {
  final String title;

  HomePage(this.title);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State {
  // RefreshIndicator requires key to implement state
  final GlobalKey _refreshKey =
      GlobalKey();

  // 初始数据
  User user = User("Default User",
      "https://www.bsn.eu/wp-content/uploads/2016/12/user-icon-image-placeholder-300-grey.jpg");

  // onRefresh(RefreshCallback) method required completable future
  // `Future` completed with `null`.
  Future _refresh() {
    return getUser().then((_user) {
      setState(() {
        user = _user;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshKey.currentState.show();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: [
            IconButton(
              icon: Icon(Icons.refresh),
              tooltip: 'Refresh',
              onPressed: () {
                _refreshKey.currentState.show();
              },
            )
          ],
        ),
        body: RefreshIndicator(
          key: _refreshKey,
          // child is typically ListView or CustomScrollView
          child: ListView(
            children: [
              Padding(
                padding: EdgeInsets.only(top: 24.0),
                child: Center(
                  child: Column(
                    children: [
                      Image.network(
                        user.image,
                        height: 128.0,
                        width: 128.0,
                      ),
                      SizedBox(
                        height: 24.0,
                      ),
                      Text(user.name),
                    ],
                  ),
                ),
              ),
            ],
          ),
          onRefresh: _refresh,
        ));
  }
}

class User {
  final String name, image;

  User(this.name, this.image);

  factory User.fromJson(Map json) {
    json = json['results'][0];
    String name = json['name']['first'] + " " + json['name']['last'];
    String image = json['picture']['large'];
    return User(name, image);
  }
}

Future getUser() async {
  final response = await http.get("https://randomuser.me/api/");
  final json = jsonDecode(response.body);
  return User.fromJson(json);
}

_refresh(): this method call getUser() which returns User on future. When user is returned by getUser(), our user(of state) is updated & setState is called for rebuild.

Future _refresh() {
    return getUser().then((_user) {
      setState(() {
        user = _user;
      });
    });
}

One thing missing here is user needs to swipe to see data at start, we can make data load automatically at start by updating indicator state inside initState once widget is build.

@override
void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshKey.currentState.show();
    });
}

你可能感兴趣的:(Flutter 案例学习之:下拉刷新)