provider我是在 中使用状态管理的新手flutter。
我创建了一个名为的模型Counter:
导入'包:flutter/foundation.dart';
class Counter with ChangeNotifier {
int value = 0;
void increment() {
value++;
notifyListeners();
}
void decrement() {
value--;
notifyListeners();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当值发生变化时,我可以将其保存在本地SharedPreferences,以便下次从该值开始。
value但是,我不知道从本地加载数据并在课堂上设置的正确方法是什么Counter。
我应该main.dart在应用程序初始化时加载文件中保存的数据,然后setValue加载该数据吗?
或者有什么解决方案,例如直接在我的Counter类中加载数据?
创建一个 SharedPreferencesProvider
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesProvider {
final Future<SharedPreferences> sharedPreferences;
SharedPreferencesProvider(this.sharedPreferences);
Stream<SharedPreferences> get prefsState => sharedPreferences.asStream();
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个 Provider 并使用 StreamProvider ,如下所示
return MultiProvider(
providers: [
Provider<SharedPreferencesProvider>(create: (_) => SharedPreferencesProvider(SharedPreferences.getInstance())),
StreamProvider(create: (context) => context.read<SharedPreferencesProvider>().prefsState, initialData: null)
Run Code Online (Sandbox Code Playgroud)
然后使用 context.watch 消耗 Widget 构建中的状态
@override
Widget build(BuildContext context) {
sharedPrefs = context.watch<SharedPreferences>();
Run Code Online (Sandbox Code Playgroud)
Ana*_*sad -2
使用shared_preferences插件
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
SharedPreferencesDemo({Key key}) : super(key: key);
@override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<int> _counter;
Future<void> _incrementCounter() async {
final SharedPreferences prefs = await _prefs;
final int counter = (prefs.getInt('counter') ?? 0) + 1;
setState(() {
_counter = prefs.setInt("counter", counter).then((bool success) {
return counter;
});
});
}
@override
void initState() {
super.initState();
_counter = _prefs.then((SharedPreferences prefs) {
return (prefs.getInt('counter') ?? 0);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("SharedPreferences Demo"),
),
body: Center(
child: FutureBuilder<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const CircularProgressIndicator();
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
}
})),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}Run Code Online (Sandbox Code Playgroud)
参考站点:https ://pub.dev/packages/shared_preferences#-example-tab-
| 归档时间: |
|
| 查看次数: |
7405 次 |
| 最近记录: |