如何使用提供程序获取异步数据? (颤振)

时间:2020-04-11 10:54:41

标签: flutter provider sqflite

背景

我正在构建用于练习Flutter的超级简单的TODO列表应用程序。如果输入字符串并单击“添加”,则文本将显示在上部列表中。

问题

何时以及如何调用model.getTasks()(=异步更新数据)和model.refresh()(= notifyListeners)?

我发现列表没有立即更新,因为我没有为await使用model.getTasks()。我尝试了这些,但是我想知道是否有更好的方法。

  • 使用await model.getTasks()并使build成为异步函数。 ->编译错误
  • await model.getTasks()之前添加model.refresh()。 ->在打开应用程序时,model.tasks在呈现ListView之前不会更新。创建新任务时,model.getTasks()被两次调用。

屏幕截图

App TODO list page

代码详细信息

  • model.tasksList<Task>,用于存储从数据库(sqflite)获取的任务。
  • model.getTasks()是一个异步函数,用于从数据库中获取数据并覆盖model.tasks
  • model.refresh()仅用于呼叫notifyListeners()
  • TodoListPage是模型notifyListeners的侦听器。
class TodoListPage extends StatelessWidget {
  final TextEditingController _textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    print('TodoListPage.build');
    final model = Provider.of<TodoListModel>(context);
    model.getTasks();

    Future createTask() async {
      TaskData taskData = await DatabaseHandler()
          .insertTask(new TaskData(name: _textFieldController.text));
      model.refresh();
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'TODO List',
        ),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 150,
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return Text(model.tasks[index].name);
              },
              itemCount: model.tasks.length,
            ),
          ),
          Text(
            'Add',
          ),
          Form(
            child: Column(
              children: <Widget>[
                TextFormField(
                  controller: _textFieldController,
                ),
                RaisedButton(
                  onPressed: () {
                    print('onPressed');
                    print(_textFieldController.text);
                    createTask();
                  },
                  child: Text('New'),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

您可以在FutureBuilder内使用StatefulWidget

class TodoListPage extends StatefulWidget {
  @override 
  _TodoListPageState createState() => _TodoListPageState();
}

class _TodoListPageState extends State<TodoListPage> {
  TodoListModel model;
  Future<List<Tasks>> _getTasks;

  @override
  void didChangeDependencies() {
    model = Provider.of<TodoListModel>(context);
    _getTasks = model.getTasks();
  }

  @override
  Widget build() {
    FutureBuilder<List<Tasks>>(
      future: _getTasks,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return Text("Loading tasks...");
        }

        final tasks = snapshot.data;

        // ...
      }
    );
  }
}

在您的模型中:

Future<List<Tasks>> getTasks() async {
  if (tasks == null) {
    tasks = await loadFromDatabase();
  }

  return tasks;
}

答案 1 :(得分:0)

设置ChangeNotifierProvider时,它会调用TodoListModel() 只能refreshTasks()一次 类似于Widget build()中的model.getTastks()

然后我将消费者放置在Widget树中尽可能深的位置 当我按下RaiseButton或在notifyListeners();

上时,此消费者每次都会获得新版本
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class TodoList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) => TodoListModel()),
      ],
    child: TodoListPage()
    );
  }
}


class TodoListPage extends StatelessWidget {
  final TextEditingController _textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    print('TodoListPage.build');

    // listen: false, if the provider sends e notify, this part is not refreshing
    final model = Provider.of<TodoListModel>(context, listen: false);

    // i place this future in the TodoListModel Class
    /*Future createTask() async {
      //TaskData taskData = await DatabaseHandler().insertTask(new TaskData(name: _textFieldController.text));

      model.refreshTasks();
    }*/

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'TODO List',
        ),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 150,
            child: new Consumer<TodoListModel>(
                builder: (context, prov2, child) {

                  // this part is updating every notifyListeners
                  //      it's better when you place the consumer,as deep as possible in the widget tree
                  print("Consumer build");

                  return ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return Text(model.tasks[index].name);
                    },
                    itemCount: model.tasks.length,
                  );
                },
            ),
          ),
          Text(
            'Add',
          ),
          Form(
            child: Column(
              children: <Widget>[
                TextFormField(
                  controller: _textFieldController,
                ),
                RaisedButton(
                  onPressed: () {
                    print('onPressed');
                    //print(_textFieldController.text);
                    //createTask();
                    model.createTask(new TaskData(name: _textFieldController.text));
                  },
                  child: Text('New'),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

class TaskData {
  final String name;

  TaskData({this.name});
}

class TodoListModel extends ChangeNotifier {

  // this Function only calls when the Provider is set at ChangeNotifierProvider like initTodoListModel
  TodoListModel () {
    print("TodoListModel Class");

    refreshTasks();
  }

  // define TaskData, with getter
  List<TaskData> _tasks = [new TaskData(name: "test"), new TaskData(name: "test2")];
  List<TaskData> get tasks => _tasks;

  // getTasks async
  Future refreshTasks() async {

    // fetch something in the Database
    // _tasks = await await DatabaseHandler().getTasks();

    notifyListeners();

  }

  Future createTask(TaskData newTask) async {

    // add Task with DatabseHandler, or in this example a simple list.add
    _tasks.add(newTask);

    //refreshing with notifyListeners
    refreshTasks();
  }

}