flutter使用Shared Preferences进行数据持久化的示例代码
时间: 2024-04-15 10:07:31 浏览: 97
以下是使用Shared Preferences进行数据持久化的示例代码:
```dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ExamplePage extends StatefulWidget {
@override
_ExamplePageState createState() => _ExamplePageState();
}
class _ExamplePageState extends State<ExamplePage> {
TextEditingController _controller = TextEditingController();
String _savedText = '';
@override
void initState() {
super.initState();
_loadSavedText();
}
void _loadSavedText() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String savedText = prefs.getString('savedText') ?? '';
setState(() {
_savedText = savedText;
_controller.text = savedText;
});
}
void _saveText(String text) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('savedText', text);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Example Page'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Enter some text',
),
onChanged: (text) {
_saveText(text);
},
),
SizedBox(height: 16.0),
Text(
'Saved text: $_savedText',
style: TextStyle(fontSize: 18.0),
),
],
),
),
);
}
}
```
在上述代码中,我们首先在initState()方法中加载之前保存的文本,并将其设置为文本框的默认值。然后,我们在文本框中输入文本时使用SharedPreferences实例保存文本。最后,我们将保存的文本显示在屏幕上。
阅读全文