我是 Flutter 和 Dart 语言的初学者,并试图弄清楚如何在页面加载时有条件地(基于用户偏好)呈现 cookie 设置对话框(弹出)。我已经找到了一些 3rd 方包(sharedpreferences)来存储用户偏好的键值对。我想要做的是检查用户偏好,如果未找到或错误(单击拒绝未给予同意)此弹出窗口将继续出现在所有页面上。我还希望用户能够通过单击链接打开此 cookie 设置弹出窗口。我怎样才能做到这一点?
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: CookiesWidget(),
),
),
);
}
}
class CookiesWidget extends StatelessWidget {
const CookiesWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Cookie Settings'),
content: const Text('This website uses cookies. Please click OK to accept.'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Deny'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
),
child: const Text('Show Cookie Settings'),
);
}
}