I have a project with Flutter. I am using Provider (4.0.5) for state management. I am getting this warning, "setstate or markneedsbuild() called during build" This is big problem for me. I think this problem will be grow in release mode. How can I fix this problem?
import 'package:example/models/notebook_model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class NotebookState with ChangeNotifier {
DateTime notebookDate = DateTime.now();
DateTime notebookDateState(DateTime date){
notebookDate = date;
notifyListeners();
return notebookDate;
}
Future<List<NotebookModel>> getNotebook()
{
notifyListeners();
return NotebookBLL.getNotebooks();
}
addNotebook(String noteTitle, String content, String date){
NotebookModel newNotebook = NotebookModel(
noteTitle: noteTitle, content: content, date: date);
NotebookBLL.insert(newNotebook);
notifyListeners();
}
updateNotebook(int id, String noteTitle, String content, String date){
NotebookModel updateNotebook = NotebookModel(
id: id,
noteTitle: noteTitle,
content: content,
date: date
);
NotebookBLL.update(updateNotebook);
notifyListeners();
}
deleteNotebook(int id){
NotebookBLL.delete(id);
notifyListeners();
}
}
This is my UI code
Consumer<NotebookState>(builder: (context, state, a) {
return FutureBuilder(
future: state.getNotebook(),
builder: (BuildContext context, snapshot) {
return snapshot.hasData
? createNotebookList(context, snapshot.data)
: Container(); }); }
I guess you should remove notify listeners from the getNotebook()
function.
The reason is that notifyListener
rebuilds your widget tree because it causes setState
.And you can't rebuild widgets during it's being built with the Future Builder
So you can't use setState (or notify listeners in this case) in a builder
like you did.