【flutter】加载指示器(loading indicator)阻止用户在某个操作执行期间操作页面

在Flutter中,通过显示一个加载指示器(loading indicator)来阻止用户在某个操作执行期间操作页面。以下是一个简单的示例代码,演示了按钮被点击后执行某操作,在操作完成前显示加载指示器,阻止用户操作页面:

dart 复制代码
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  bool _loading = false;

  void _performOperation() {
    setState(() {
      _loading = true;
    });

    // 模拟某个操作,比如网络请求或其他耗时操作
    Future.delayed(Duration(seconds: 2), () {
      setState(() {
        _loading = false;
        // 在这里添加操作完成后的逻辑
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading Indicator Example'),
      ),
      body: Center(
        child: _loading
            ? CircularProgressIndicator() // 显示加载指示器
            : ElevatedButton(
                onPressed: _performOperation,
                child: Text('Perform Operation'),
              ),
      ),
    );
  }
}

在这个示例中,当用户点击按钮时,会触发_performOperation方法,在这个方法中设置_loadingtrue,显示加载指示器。在模拟的操作完成后(这里用Future.delayed模拟),将_loading设置为false,加载指示器消失,用户可以继续操作页面。

相关推荐
xiaoshuaishuai83 小时前
C# 实现百度搜索算法逆向
开发语言·windows·c#·dubbo
yuan199973 小时前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
蒸汽求职3 小时前
北美求职身份过渡:Day 1 CPT 的合规红线与安全入职指南
开发语言·人工智能·安全·pdf·github·开源协议
YuanDaima20483 小时前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法
fox_lht4 小时前
7.3.结构体-方法
开发语言·后端·rust
chenbin___4 小时前
检查hooks依赖的工具(转自千问)
开发语言·前端·javascript·react native·react.js
久爱@勿忘4 小时前
vue/uniapp H5页面截图
开发语言·前端·javascript
2301_800976934 小时前
python的协程
开发语言·python
武超杰4 小时前
Spring Cloud Alibaba Nacos 进阶:配置隔离、集群、持久化与开机自启
java·开发语言
Rabitebla4 小时前
C++类和对象(中):默认函数 + 运算符重载 + 日期类实现完整笔记
java·开发语言·javascript