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

相关推荐
见山是山-见水是水2 小时前
鸿蒙flutter第三方库适配 - 读书笔记
flutter·华为·harmonyos
Utopia^3 小时前
鸿蒙flutter第三方库适配 - 图片压缩工具
flutter·华为·harmonyos
踏着七彩祥云的小丑4 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid4 小时前
Python12(网络编程)
开发语言·网络·php
W23035765734 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090015 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳5 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...5 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102165 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert