首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >颤振SQFlite:在用数据库内容更新列表视图时遇到问题

颤振SQFlite:在用数据库内容更新列表视图时遇到问题
EN

Stack Overflow用户
提问于 2019-11-12 15:38:05
回答 1查看 635关注 0票数 0

我确实设法通过listview实现了数据库内容的显示。然而,它做得不恰当。运行仿真器后,存储在数据库中的内容应该会出现,但不会出现。它还显示数据库是空的,尽管它显然不是。但是,一旦我向数据库添加了一个新项并单击“保存”,所有内容都会显示出来(除了上次添加的内容,并显示在下一次更新中)。我不知道如何解决这个问题,我试着把_listTodos()放在任何地方,看看它是否在小部件之前执行,但是没有任何改进。--我认为问题在ListDisplay类中,所以您可以跳过其他部分,为了方便起见,我只需要完整的代码。

代码语言:javascript
复制
import 'package:flutter/material.dart';

import 'model/todo_model.dart';
import 'model/todo.dart';

class ListGradesPage extends StatefulWidget {
  final String title;

  ListGradesPage({this.title, Key key}) : super(key: key);

  _ListGradesPageState createState() => _ListGradesPageState();
}

var _todoItem;
var _lastInsertedId = 0;
final _model = TodoModel();

Future<void> _deleteTodo() async {
  _model.deleteAllTodo();
}

class _ListGradesPageState extends State<ListGradesPage> {
  //final _model = TodoModel();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.edit),
              onPressed: () {
                print('editing...');
                //_listTodos();
              }),
          IconButton(
              icon: Icon(Icons.delete),
              onPressed: () {
                print('deleting all...');
                setState(() {
                  _deleteTodo();
                });
              }),
        ],
      ),
      body: ListDisplayPage(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => AddGrade()),
          );
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
  }
}

class ListDisplayPage extends StatefulWidget {
  ListDisplay createState() => ListDisplay();
}

class ListDisplay extends State<ListDisplayPage> {
  int _selectedIndex;

  List<Todo> todos = new List<Todo>();

  Future<void> _listTodos() async {
    todos = await _model.getAllTodos();

    if (todos.isEmpty) {
      print('it is empty-2.');
    } else {
      print("not empty-2");
    }

    print('To Dos:');
    for (Todo todo in todos) {
      print(todo);
    }
  }

  _onSelected(int index) {
    _selectedIndex = index;
  }

  @override
  void initState() {
    super.initState();


    _listTodos();

    // _listTodos() is not calling the function above for some reason, but executes everything below it
    // In the database there are items stored however it says the databse is empty...
    // until i add a new item and everything shows up except the item i recently added


    if (todos.isEmpty) {

      print('To Dos:');
      for (Todo todo in todos) {
        print(todo);
      }

      print('it is empty.');
    } else {
      print("not empty");
    }
  }

  @override
  Widget build(BuildContext context) {
    //Color clr = Colors.transparent;

    return todos.isEmpty
        ? Center(
            child: Text(
                'Nothing to show! Is it empty? ' + (todos.isEmpty).toString()))
        : ListView.builder(
            itemCount: todos.length,
            itemBuilder: (context, index) {
              return Card(
                //                           <-- Card widget
                child: Container(
                  color: _selectedIndex != null && _selectedIndex == index
                      ? Colors.lightBlueAccent
                      : Colors.transparent,
                  child: ListTile(
                    leading: GestureDetector(
                      onTap: () {
                        setState(() {
                          _onSelected(index);
                          print(index);
                        });
                      },
                      child: Container(

                        width: MediaQuery.of(context).size.width / 2,
                        child:
                            Text(todos[index].sid + '\n' + todos[index].grade),
                      ),
                    ),
                  ),
                ),
              );
            },
          );
  }
}

class AddGrade extends StatelessWidget {
  String _sid, _grade;

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Add Grade"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: 'Student ID',
                  labelText: 'SID',
                ),
                onSaved: (String value) {
                  print('Saving SID $value');
                  _sid = value.toString();
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextFormField(
                decoration: const InputDecoration(
                  hintText: 'Student Grade',
                  labelText: 'Grade',
                ),
                onSaved: (String value) {
                  print('Saving Grade $value');
                  _grade = value.toString();
                },
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _formKey.currentState.save();
          _addTodo();
          //_listTodos();
          Navigator.pop(context);
        },
        child: Icon(Icons.save),
        backgroundColor: Colors.blue,
      ),
    );
  }

  Future<void> _addTodo() async {
    Todo newTodo = Todo(sid: _sid, grade: _grade);
    _lastInsertedId = await _model.insertTodo(newTodo);
  }
}

控制台输出(执行时):

代码语言:javascript
复制
Restarted application in 1,607ms.
I/flutter (14196): To Dos:
I/flutter (14196): it is empty.
I/flutter (14196): not empty-2
I/flutter (14196): To Dos:
I/flutter (14196): Todo{id: 1, sid: q, grade: qq}
I/flutter (14196): Todo{id: 2, sid: w, grade: ww}
I/flutter (14196): Todo{id: 3, sid: e, grade: ee}
I/flutter (14196): Todo{id: 4, sid: r, grade: }
I/flutter (14196): Todo{id: 5, sid: hh, grade: kk}

在添加新学生之前和添加新学生后(在我再次添加另一个学生之前,最近的一个都不会出现),

在此之前

之后

我很抱歉,如果我没有遵守指导方针,从来没有真正张贴问题在这里之前。

EN

回答 1

Stack Overflow用户

发布于 2019-11-13 00:20:21

你知道FutureBuilder吗?我建议将您的ListView.builder封装在未来的构建器中,并将_loadTodos函数作为未来传递。然后,您可以删除初始化todo的所有initState代码。

通常,我发现在initState中执行异步工作并不总是有效的。UI已经构建,并且不知道在异步工作完成时重建。另一个选项可能只是在异步函数使用todos完成后调用setState。不过,我认为FutureBuilder是更好的方法。

如果你需要额外的帮助,请告诉我。我也许可以帮你写一些。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58821949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档