【问题标题】:How to store the user input session and retrieve it again?如何存储用户输入会话并再次检索它?
【发布时间】:2020-07-07 11:16:54
【问题描述】:

我的笔记应用程序遇到问题,其中用户的输入通过卡片表单保存在列表中,但我不知道如何单击该卡片并检索用户输入的相同会话我可以编辑它并完全替换以前的值。我在考虑可能为列表设置一个单独的键值对,这样我就可以将内容和标题分开,但我不知道如何调用它,因为目前它是data[index]

我的想法是基本上保存便笺,然后能够单击它,编辑并再次保存它,而无需创建新便笺。

视频示例:

Flutter notes issue

我曾尝试使用initStatedidChangeDependencies,但效果并不理想。

我的代码:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

final data = [];
void main() => runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    ));

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return (Scaffold(
      backgroundColor: Colors.blueGrey[700],
      appBar: AppBar(
        automaticallyImplyLeading: false,
        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(
        padding: const EdgeInsets.only(top: 10.0),
        itemCount: data.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            child: Card(
              child: Padding(
                padding: const EdgeInsets.only(
                    top: 12.0, bottom: 10, left: 10.0, right: 10.0),
                child: ListTile(
                  dense: true,
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => SharedPreference1()));
                  },
                  title: Text(
                    data[index],
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        elevation: 9.0,
        child: Icon(Icons.add),
        onPressed: () async {
          await Navigator.push(context,
              MaterialPageRoute(builder: (context) => SharedPreference1()));
        },
        backgroundColor: Colors.blueGrey[300],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    ));
  }
}

Future<bool> saveData(String nameKey, String value) async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  return await preferences.setString(nameKey, value);
}

Future<String> loadData(String nameKey) async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  return preferences.getString(nameKey);
}

class Hero extends State<SharedPreference1> {
  TextEditingController _notesController1 = new TextEditingController();
  TextEditingController _notesController2 = new TextEditingController();
  Widget buildSaveButton(context) {
    return Container(
      color: Colors.blueGrey[700],
      margin: EdgeInsets.only(top: 340.0),
      child: RaisedButton.icon(
        elevation: 9.0,
        icon: Icon(Icons.save),
        label: Text('Save'),
        color: Colors.white,
        onPressed: () async {
          await saveData("_key_name", _notesController1.text);
          await setData();
          print(data);
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => Home()));
        },
      ),
    );
  }

  @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: InputDecoration(
                  border: InputBorder.none,
                  hintText: 'Note Title',
                ),
                style: TextStyle(
                  fontSize: 20,
                  color: Colors.white,
                  fontFamily: 'Montserrat',
                ),
              ),
            ),
            FlatButton(
              child: 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: InputDecoration(
            border: InputBorder.none,
            hintText: 'Create Note Here',
          ),
          cursorColor: Colors.white,
          autofocus: true,
          style: TextStyle(
              color: Colors.white, fontSize: 18, fontFamily: 'Montserrat'),
        ),
      ),
    );
  }

  setData() {
    loadData("_key_name").then((value) {
      setState(() {
        if (value == null) {
          print("Value not available.");
        } else {
          data.add(value);
        }
      });
    });
  }
}

class SharedPreference1 extends StatefulWidget {
  SharedPreference1() : super();
  @override
  Hero createState() => Hero();
}

【问题讨论】:

  • 您可以使用共享偏好来解决您的问题。

标签: android flutter flutter-layout


【解决方案1】:

这样做。

  1. 创建一个 Note 类。
class Note {
  int id;
  String title;
  String content;
}
  1. 更改您的SharedPreference1
class SharedPreference1 extends StatefulWidget {

  final Note note;

  SharedPreference1({this.note}) : super();
  @override
  Hero createState() => Hero();
}
  1. 在编辑笔记时将笔记对象传递给SharedPreference1
Note newNote = await Navigator.push(context, MaterialPageRoute(
                            builder: (context) => SharedPreference1(note: data[index],)));
setsState((){
  data[index] = newNote;
});

等到弹出下一个屏幕,然后将返回的对象设置到列表中。

4.当用户保存笔记时,检查您是否正在编辑创建新笔记的笔记。

if(widget.note == null){
  //New Note
  //save the note

}else{
  //Editing the note
  //save the note
  //return the note to home screen 
  Note newNote = Note();
  newNote.id = widget.note.id;
  newNote.title = //set title;
  newNote.content = //set content
  //return this newNote to previous screen
  Navigator.of(context).pop(newNote);
}
  1. 当您添加新笔记时,请照旧执行。

您的data 列表将是Note 的列表。

【讨论】:

  • 您好,感谢您的回答。我刚刚尝试了代码并将其添加到我的代码中。现在的问题是该值不再保存在列表中,如果我遗漏了其他东西或没有。无论如何,这里是包含所有更改的代码链接,hastebin.com/zejutuwere.java
  • 好的,该链接已过期。只需检查此链接。 pastebin.com/Jis2D3ms
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多