I am writing a simeple todo list app, the todo item stored in sqlite
sqflite: ^2.0.0 3
right now. I want to load the sqlite todo data before loading the flutter page, this is my initial code looks like in flutter:
class _HomePageState extends State<HomePage> {
GlobalKey _inputViewKey = GlobalKey();
List<Todo> _todos = [];
@override
void initState() {
var _db = DBProvider.db;
_todos = await _db.getAllTodo();
super.initState();
}
}
and this is the function to load data from database:
Future<List<Todo>> getAllTodo() async {
final db = await database;
var result = await db.query('Todo');
return result.map((it) => Todo.fromJson(it)).toList();
}
the IDE told that I should add async in the initial function. When I add the async function, the initial function could not work. What should I do to make it work? how to initial the async data before the HomePage?
CodePudding user response:
You cant mark async on inistate. You can try this
class _HomePageState extends State<HomePage> {
GlobalKey _inputViewKey = GlobalKey();
List<Todo> _todos = [];
@override
void initState() {
var _db = DBProvider.db;
getAllTodo();
super.initState();
}
}
And in the method
getAllTodo() async {
final db = await database;
var result = await db.query('Todo');
_todos = result.map((it) => Todo.fromJson(it)).toList();
setState((){});
}