如何保持状态?

时间:2019-06-19 10:11:03

标签: flutter dart setstate

ListView.builder(
          itemCount: _list.length,
          itemBuilder: (context, i) {
            return ListTile(
              title: todonoteShow(context, _list[i]),
              leading: IconButton(
                icon: _list[i].isDone == true
                    ? Icon(
                        Icons.radio_button_checked,
                        color: Theme.of(context).primaryColor,
                      )
                    : Icon(Icons.radio_button_unchecked),
                onPressed: () {
                  setState(() {
                    _list[i].isDone = !_list[i].isDone;
                  });
                },

这是我的代码,当我单击按钮时,状态更改了,这是正确的,

,但是当我打开另一个页面并返回时,图标的状态将重置,

我使用sqflite,我的问题是当我单击图标按钮时,

如何将参数 _list [i] .isDone 保存到数据库中,

谢谢!

database//
 final String columnIsDone = 'isDone';

Future<int> updateTodo(Todonote todonote) async {
    var d = await db;
    var res = d.update(tableName, todonote.toMap(),
       );
    print('$res');
    return res;
  }

todo.dart//
_saveTodo1(String thing, bool isDone) async {
    if (widget.todonote != null) {
      Todonote upd = Todonote.fromMap({
        'id': widget.todonote.id,
        'thing': widget.todonote.thing,
        'isDone': isDone == true ? 1 : 0
      });
      await widget.db.updateTodo(upd);
      return upd;
    }
  }

iconbutton//
 onPressed: () {
                      setState(() {
                        _list[i].isDone = !_list[i].isDone;
                      });
                      _saveTodo1(_list[i].thing, _list[i].isDone);
                    },

我确实喜欢上面的方法,但是没有用!

class DataBase {
  Database _database;
  final String tableName = 'notetodo';
  final String columnId = 'id';
  final String columnThing = 'thing';
  final String columnIsDone = 'isDone';
  final String tableName2 = 'notetodo2';
  final String columnId2 = 'id2';
  final String columnTitle = 'title';
  final String columnThing2 = 'thing2';
  final String columnDate = 'date';

  initDb() async {
    var directoryPath = await getDatabasesPath();
    String path = join(directoryPath, 'notetodo.db');
    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    print('good,version:1');
    return db;
  }

  FutureOr<void> _onCreate(Database db, int version) async {
    await db.execute('''create table $tableName(
            $columnId integer primary key,
            $columnThing text not null,
            $columnIsDone integer)''');
    await db.execute('''create table $tableName2(
            $columnId2 integer primary key,
            $columnThing2 text not null,
            $columnDate text not null,
            $columnTitle text)''');
    print('right');
    db.close();
  }

enter image description here

1 个答案:

答案 0 :(得分:0)

我使用firebase的firestore存储我的数据以保存Google Keep的克隆,当我需要更改按钮时(无论是否选择标签),我都创建了一个带有true和false值的标签标签,每当我更改数据时,我都会在内部对其进行更改消防站。