我是 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'),
);
}
}
uj5u.com熱心網友回復:
SharedPrefences Visibility Widget將幫助您有條件地隱藏和顯示您的 cookie 小部件。
如果您希望用戶使用鏈接在您的應用中打開某些內容,您應該考慮搜索深層鏈接。
我不能給出具體的解決方案,但可以提供實作最常見情況的資源:
- 深度鏈接包:uni_links
- 一篇文章https://medium.com/flutter-community/deep-links-and-flutter-applications-how-to-handle-them-properly-8c9865af9283
- Flutter 官方深度鏈接指南
uj5u.com熱心網友回復:
共享偏好應該是最好的選擇。
您云使用FutureBuilder根據共享首選項的資料呈現(或不呈現)對話框。
您應該在類內部但在方法外部創建一個異步函式:build()
Future<bool> cookiesAccepted() async {
var prefs = await SharedPreferences.getInstance();
if (prefs.containsKey('cookies')) {
bool? info = prefs.getBool('cookies');
return info ?? false;
}
return false;
}
并將其放入您的build()方法中。
FutureBuilder<bool>(
future: cookiesAccepted(),
builder: (BuildContext context, AsyncSnapshot<bool> response) {
if (response.hasData) {
if (!response.data!) { //If the cookies were not accepted
return Text("Your cookies dialog");
}
}
},
),
請記住將資料存盤在 SharedPreferences 中 prefs.setBool('cookies', value);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411620.html
標籤:
