基于SharedPreferences实现Flutter温度转换历史记录展示求助
温度转换器添加历史记录功能实现
核心修改步骤
- 初始化SharedPreferences实例:在
initState中异步获取SharedPreferences实例,确保后续读写操作可用。 - 新增历史记录列表:定义
List<String> history变量,用于存储转换记录。 - 读取本地历史:初始化时从SharedPreferences读取已保存的历史记录,解析为字符串列表。
- 保存新记录:点击Convert按钮计算完成后,生成格式化的记录字符串,添加到历史列表并持久化到本地。
- 展示历史记录:在页面布局中添加可滚动的列表组件,显示所有历史转换记录。
完整修改后的代码
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.green), home: const TempApp(), ); } } class TempApp extends StatefulWidget { const TempApp({super.key}); @override TempState createState() => TempState(); } class TempState extends State<TempApp> { double? input; double? output; bool? fOrC; late SharedPreferences prefs; List<String> history = []; @override void initState() { super.initState(); input = 0.0; output = 0.0; fOrC = true; _initPrefs(); } // 初始化SharedPreferences并读取历史记录 void _initPrefs() async { prefs = await SharedPreferences.getInstance(); setState(() { // 读取保存的历史记录,为空则初始化空列表 history = prefs.getStringList('temp_history') ?? []; }); } // 保存新的转换记录到本地 void _saveHistoryRecord(String record) async { setState(() { history.insert(0, record); // 最新记录放在最前面 }); await prefs.setStringList('temp_history', history); } @override Widget build(BuildContext context) { final inputField = TextField( keyboardType: TextInputType.number, onChanged: (str) { try { input = double.parse(str); } catch (e) { input = 0.0; } }, decoration: InputDecoration( labelText: "Input a Value in ${fOrC == false ? "Fahrenheit" : "Celsius"}", ), textAlign: TextAlign.center, ); final appBar = AppBar(title: const Text("Temperature Calculator")); final tempSwitch = Container( padding: const EdgeInsets.all(15.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text("Fahrenheit"), Radio<bool>( groupValue: fOrC, value: false, onChanged: (v) => setState(() => fOrC = v), ), const Text("Celsius"), Radio<bool>( groupValue: fOrC, value: true, onChanged: (v) => setState(() => fOrC = v), ), ], ), ); final calcBtn = Container( child: ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: const Size(200, 50), maximumSize: const Size(200, 50), textStyle: const TextStyle(fontSize: 20), ), child: const Text("Convert"), onPressed: () { setState(() { fOrC == false ? output = (input! - 32) * (5 / 9) : output = (input! * 9 / 5) + 32; }); // 生成格式化的记录字符串 final record = fOrC == false ? "${input?.toStringAsFixed(2)} F → ${output?.toStringAsFixed(2)} C" : "${input?.toStringAsFixed(2)} C → ${output?.toStringAsFixed(2)} F"; // 保存记录 _saveHistoryRecord(record); // 显示转换结果弹窗 showDialog( context: context, builder: (context) => AlertDialog(content: Text(record)), ); }, ), ); // 历史记录列表组件 final historyList = Expanded( child: ListView.builder( padding: const EdgeInsets.only(top: 20), itemCount: history.length, itemBuilder: (context, index) { return Card( margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), child: Padding( padding: const EdgeInsets.all(12), child: Text(history[index]), ), ); }, ), ); return Scaffold( appBar: appBar, body: Container( padding: const EdgeInsets.all(16.0), child: Column( children: <Widget>[inputField, tempSwitch, calcBtn, historyList], ), ), ); } }
关键代码说明
_initPrefs方法:异步获取SharedPreferences实例,并读取本地存储的历史记录,初始化history列表。_saveHistoryRecord方法:将新生成的转换记录插入到历史列表头部(最新记录优先展示),然后将整个列表持久化到SharedPreferences。- 历史记录展示:使用
Expanded包裹ListView.builder,确保列表能在剩余空间滚动,每条记录用Card组件包裹提升视觉效果。
内容的提问来源于stack exchange,提问作者Huzaifa Zahid
相关产品推荐
相关产品推荐

