Flutter中TextField输入数据保存后首页展示问题求助
解决Flutter列表数据无法展示的问题
我帮你排查出了几个关键问题,咱们逐个修复就能解决数据不展示的问题啦:
问题分析&修复步骤
Home组件是无状态的,无法响应数据变化
你当前的Home是StatelessWidget,当data列表更新后,它不会自动重建UI。咱们把它改成StatefulWidget,这样数据变化时调用setState就能刷新列表了。ListView没有绑定要展示的数据
你代码里的ListView.builder的title对应的Text是空的,得把它改成Text(data[index]),这样才能把列表里的内容显示出来。SharedPreferences存储逻辑错误,会覆盖旧数据
现在你用setString每次只存单个值,新数据会直接覆盖旧的。应该改用setStringList来存储整个data列表,加载的时候用getStringList获取完整的列表数据。数据加载逻辑重复添加内容
原来的setData方法每次加载都会把同一个值追加到列表里,咱们改成直接替换整个列表,避免重复数据。另外,Hero这个类名和Flutter自带的导航组件重名了,我把它改成SharedPreferencePageState,避免冲突。
修改后的完整代码
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; TextEditingController _notesController1 = TextEditingController(); TextEditingController _notesController2 = TextEditingController(); List<String> data = []; void main() => runApp(const MaterialApp( debugShowCheckedModeBanner: false, home: Home(), )); // 改成StatefulWidget class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { // 页面初始化时加载数据 @override void initState() { super.initState(); _loadData(); } // 加载完整的列表数据 Future<void> _loadData() async { SharedPreferences preferences = await SharedPreferences.getInstance(); List<String>? loadedData = preferences.getStringList("_key_notes"); setState(() { data = loadedData ?? []; }); } @override Widget build(BuildContext context) { return Scaffold( drawer: Drawer( child: ListView( children: <Widget>[ ListTile( title: Text( 'Glass', style: TextStyle( fontSize: 15.0, letterSpacing: 1.0, color: Colors.black, fontFamily: 'Montserrat', ), ), ), const ListTile( title: Text('Trash'), ), ], ), ), backgroundColor: Colors.blueGrey[700], appBar: AppBar( title: Text( 'Glass', style: TextStyle( fontSize: 20.0, letterSpacing: 1.0, color: Colors.white, fontFamily: 'Montserrat', ), ), centerTitle: true, backgroundColor: Colors.blueGrey[700], ), body: ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return Card( child: ListTile( onTap: () {}, // 绑定列表数据 title: Text(data[index]), ), ); }, ), floatingActionButton: FloatingActionButton( elevation: 9.0, child: const Icon(Icons.add), onPressed: () async { // 跳转后返回时重新加载数据 await Navigator.push( context, MaterialPageRoute(builder: (context) => const SharedPreference1())); _loadData(); }, backgroundColor: Colors.blueGrey[300], ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, ); } } // 保存整个列表到SharedPreferences Future<bool> saveData(List<String> notes) async { SharedPreferences preferences = await SharedPreferences.getInstance(); return await preferences.setStringList("_key_notes", notes); } class SharedPreferencePageState extends State<SharedPreference1> { Widget buildSaveButton(context) { return Container( color: Colors.blueGrey[700], margin: const EdgeInsets.only(top: 340.0), child: RaisedButton.icon( elevation: 9.0, icon: const Icon(Icons.save), label: const Text('Save'), color: Colors.white, onPressed: () async { if (_notesController2.text.isNotEmpty) { // 添加新数据到列表 data.add(_notesController2.text); // 保存整个列表 await saveData(data); // 清空输入框 _notesController2.clear(); _notesController1.clear(); // 返回首页 Navigator.pop(context); } }, ), ); } @override Widget build(BuildContext context) { return Scaffold( body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, color: Colors.blueGrey[700], child: SafeArea( child: SingleChildScrollView( child: Column( children: <Widget>[ buildHeading(context), buildNotesText(), buildSaveButton(context), ], ), ), ), ), ); } } Widget buildHeading(context) { return Material( color: Colors.blueGrey[700], child: Padding( padding: const EdgeInsets.only(left: 20.0, top: 10.0), child: Row( children: <Widget>[ Expanded( child: TextField( maxLines: 1, controller: _notesController1, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Note Title', ), style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Montserrat', ), ), ), FlatButton( child: const Icon(Icons.close, color: Colors.white, size: 27), onPressed: () { Navigator.of(context).pop(); }, ) ], ), ), ); } Widget buildNotesText() { return Material( color: Colors.blueGrey[700], child: Padding( padding: const EdgeInsets.all(20.0), child: TextField( maxLines: null, controller: _notesController2, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Create Note Here', ), cursorColor: Colors.white, autofocus: true, style: TextStyle(color: Colors.white, fontSize: 18, fontFamily: 'Montserrat'), ), ), ); } class SharedPreference1 extends StatefulWidget { const SharedPreference1({super.key}); @override SharedPreferencePageState createState() => SharedPreferencePageState(); }
内容的提问来源于stack exchange,提问作者NevMthw
相关产品推荐
相关产品推荐

