【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,加载指示器消失,用户可以继续操作页面。

相关推荐
科雷软件测试24 分钟前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO1 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
笨笨饿3 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
艾为电子4 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
棉花骑士4 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言
IGAn CTOU4 小时前
PHP使用Redis实战实录2:Redis扩展方法和PHP连接Redis的多种方案
开发语言·redis·php
环黄金线HHJX.4 小时前
TSE框架配置与部署详解
开发语言·python
Vfw3VsDKo5 小时前
Maui 实践:Go 接口以类型之名,给 runtime 传递方法参数
开发语言·后端·golang
Pyeako5 小时前
PyQt5 + PaddleOCR实战:打造桌面级实时文字识别工具
开发语言·人工智能·python·qt·paddleocr·pyqt5
白藏y6 小时前
【C++】muduo接口补充
开发语言·c++·muduo