在Flutter中,通過顯示一個加載指示器(loading indicator)來阻止用戶在某個操作執行期間操作頁面。以下是一個簡單的示例代碼,演示了按鈕被點擊后執行某操作,在操作完成前顯示加載指示器,阻止用戶操作頁面:
import 'package:flutter/material.dart';void main() {runApp(MyApp());
}class MyApp extends StatelessWidget {Widget build(BuildContext context) {return MaterialApp(home: MyHomePage(),);}
}class MyHomePage extends StatefulWidget { _MyHomePageState createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {bool _loading = false;void _performOperation() {setState(() {_loading = true;});// 模擬某個操作,比如網絡請求或其他耗時操作Future.delayed(Duration(seconds: 2), () {setState(() {_loading = false;// 在這里添加操作完成后的邏輯});});}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
,加載指示器消失,用戶可以繼續操作頁面。