【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方法,在这个方法中设置_loading为true,显示加载指示器。在模拟的操作完成后(这里用Future.delayed模拟),将_loading设置为false,加载指示器消失,用户可以继续操作页面。

相关推荐
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁5 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超5 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int5 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger5 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读5 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
CCCCCCCCharlie5 天前
Linux进程控制四大核心操作
linux·开发语言
君赏5 天前
棉宇宙 Flutter 热更新是如何落地的
flutter