【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快速入门(Java开发者版)
java·开发语言·笔记·python
Y3815326621 小时前
SERP API 请求体 Gzip 压缩优化实战:大数据量降带宽 80%
开发语言·前端·php
weixin199701080161 小时前
☁️《抖店API基础¥0.018/百次·增值¥0.05/百次:云内云外价差架构实战》(附Python源码)
开发语言·python·架构
萌动的小火苗2 小时前
1、python基础面试题
java·开发语言·python
运维行者_2 小时前
网络监控与ITSM集成:从告警到工单,实现运维自动化闭环
开发语言·网络·分布式·后端·架构·flask·php
小叮当爱咖啡2 小时前
Day3.参数+Prompt三板斧
开发语言·python·prompt
菜冻鱼2 小时前
Python-pandas-索引与筛选
开发语言·笔记·python·numpy·pandas·学习方法
鹿角片ljp3 小时前
Java面试复盘(二):String不可变、字符串常量池与字符串拼接
开发语言·python
小秋求学记.3 小时前
PHP安全漏洞实战:从环境配置到RCE攻击
开发语言·php
看浪的路人4 小时前
第3讲:代码补全引擎
开发语言·windows·python