美文网首页flutter
flutter 网络请求加载图

flutter 网络请求加载图

作者: 心旷则神怡 | 来源:发表于2022-04-19 10:52 被阅读0次

//网络请求加载图

import 'package:flutter/material.dart';

enum LoadingStatus {
  loading, // 加载中
  loadingSuccess, // 加载成功
  loadingFailed, // 加载错误
}

// ignore: must_be_immutable
class LoadingPage extends StatefulWidget {
  final Widget child;
  // 重新加载
  final Function(LoadingPage widget) reloadData;
  //记录加载状态,默认loading
  LoadingStatus loadingStatus;

  late _LoadingPageState state;
  LoadingPage({
    Key? key,
    required this.child,//需要加载的widget
    required this.reloadData, // 重新加载
    this.loadingStatus = LoadingStatus.loading,//正在加载...
  }) : super(key: key);

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

class _LoadingPageState extends State<LoadingPage> {

  @override
  Widget build(BuildContext context) {
    widget.state = this;
    return _buildBody();
  }

  Widget _buildBody() {
    switch (widget.loadingStatus) {
      case LoadingStatus.loading:
        return _buildLoadingPage();
      case LoadingStatus.loadingSuccess:
        return widget.child;
      case LoadingStatus.loadingFailed:
        return _buildErrorPage();
    }
  }
  
  Widget _buildLoadingPage() {
    return Container(
      color: Colors.black45,
      width: double.infinity,
      height: double.infinity,
      child: const Center(
        child: SizedBox(
          height: 55.0,
          width: 55.0,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      ),
    );
  }

  Widget _buildErrorPage() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Text("页面出错啦!"),
          TextButton(onPressed: (){
            widget.reloadData(widget);
          }, child: const Text("重新加载")),
        ],
      ),
    );
  }

  void updateStatus(LoadingStatus status) {
    setState(() {
      widget.loadingStatus = status;
    });
  }
}

使用

Widget _buildContent(){
    var loadingView = LoadingPage(
      loadingStatus: LoadingStatus.loading,
      child: const Center(child: Text("请求到数据了")),
      reloadData: (LoadingPage widget) {
        widget.state.updateStatus(LoadingStatus.loading);
        Future.delayed(const Duration(seconds: 2), () {
          widget.state.updateStatus(LoadingStatus.loadingSuccess);
        });
      },
    );
//延迟两秒,仿网络请求
    Future.delayed(const Duration(seconds: 2), (){
      loadingView.state.updateStatus(LoadingStatus.loadingFailed);
    });
    return loadingView;
  }

相关文章

网友评论

    本文标题:flutter 网络请求加载图

    本文链接:https://www.haomeiwen.com/subject/jtdsertx.html