如何只显示一次警报对话框?我希望在用户首次加载屏幕以显示指令时出现警报对话框。取消对话后,我不希望再次出现。
答案 0 :(得分:1)
您可以使用Shared Preferences
启动应用程序时,请从共享首选项(例如:isFirstLoaded)中获取值。如果isFirstLoaded == true,则显示对话框。
关闭对话框时,将isFirstLoaded = false设置并保存到共享首选项。
下面是一个示例(请注意,该示例在点击“返回”键时不会处理dismiss事件)。
将shared_preferences添加到您的pubspec.yaml
shared_preferences:^ 0.5.1 + 1
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyStatelessApp());
}
class MyStatelessApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Stateless Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: StatelessWidgetDemo(),
);
}
}
class StatelessWidgetDemo extends StatelessWidget {
final keyIsFirstLoaded = 'is_first_loaded';
@override
Widget build(BuildContext context) {
Future.delayed(Duration.zero, () => showDialogIfFirstLoaded(context));
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Flutter Stateless Demo'),
),
body: Center(
child: Text('Hello'),
)));
}
showDialogIfFirstLoaded(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isFirstLoaded = prefs.getBool(keyIsFirstLoaded);
if (isFirstLoaded == null) {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Title"),
content: new Text("This is one time dialog"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("Dismiss"),
onPressed: () {
// Close the dialog
Navigator.of(context).pop();
prefs.setBool(keyIsFirstLoaded, false);
},
),
],
);
},
);
}
}
}