我一直在试图弄清楚如何用持久状态管理器构建一个flutter应用程序。我似乎不能让它工作。这是我的应用程序与状态管理器。
我想存储实际的类,而不仅仅是一个整数,这使它有点复杂,但嘿,这就是我的目标。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
/// Use a provider. Multiprovider works just fine
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => State()),
],
child: const MyApp(),
),
);
}
// Define the data type we want to use
// We will use time and value to track data over time
class MyData {
final DateTime time;
final int value;
MyData(this.time, this.value);
}
// Use a state with a change notifier (provider stuff)
class State with ChangeNotifier {
late List<MyData> _dataset = [];
List<MyData> get dataset => _dataset;
State() {
// The dataset is a list of objects
_dataset = [];
}
void addData(time, value) {
// Add data to the dataset
MyData datapoint = MyData(time, value);
_dataset.add(datapoint);
}
void clearData() {
// Clear the dataset
_dataset = [];
}
}
// The actual widget
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have added this many datapoints'),
const Count(),
IconButton(
onPressed: () =>
context.read<State>().addData(DateTime.now(), 100),
icon: const Icon(Icons.add)),
IconButton(
onPressed: () => context.read<State>().clearData(),
icon: const Icon(Icons.remove))
],
),
),
);
}
}
// And the parsing of the data to a widget
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<State>().dataset.length}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headlineMedium,
);
}
}
问题是,我怎样才能给它添加一个持久的逻辑呢?
1条答案
按热度按时间bnl4lu3b1#
持久化数据可以在状态初始化时添加,为了将数据保存在Key-value storage中,需要使用
json.encode
和json.decode
等字符串化每个对象。这里有一个更新的代码片段,将工作。
我删除了您的注解,并在添加持久性逻辑的代码处添加了注解。