I've implemented Provider pattern in a simple Notes app.
Problem :
Data is loaded on the screen only when the app reloads or the screen gets rebuilt.
This is my note_list
stateless widget which displays the notes :
class NoteList extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Note List"),
),
body: getnoteListView(context),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ChangeNotifierProvider(
builder: (context) => NoteProvider(),
child: NoteDetail(Note('', '', 2), 'Add Note'),
);
}));
},
tooltip: "Add Note",
child: Icon(Icons.add),
),
);
}
ListView getnoteListView(BuildContext context) { // <---- the thing to be focused here
final noteProvider = Provider.of<NoteProvider>(context);
var noteList = noteProvider.noteList;
var count = noteList.length;
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int index) {
print(noteList[index].title);
return Text(
noteList[index].title,
style: titleStyle,
);
},
);
}
}
And the NoteProvider.dart
:
import 'package:flutter/material.dart';
import 'package:pass_list/models/note.dart';
import 'package:pass_list/utils/database_helper.dart';
// https://stackoverflow.com/a/56713184
class NoteProvider with ChangeNotifier {
DatabaseHelper databaseHelper = DatabaseHelper();
List<Note> _noteList = [];
int count = 0;
// get updateListView;
get noteList => _noteList;
NoteProvider(){
fetchNotes();
}
void setNoteList(notesList) {
_noteList = notesList;
// notifyListeners(); <- this didn't work either
}
fetchNotes() async {
await databaseHelper.initializeDatabase();
List<Note> noteList = await databaseHelper.getNoteList();
setNoteList(noteList);
}
Future<int> updateNote(note) async{
var result = await databaseHelper.updateNote(note);
await fetchNotes();
notifyListeners();
return result;
}
Future<int> insertNote(note) async{
var result = await databaseHelper.insertNote(note);
await fetchNotes();
notifyListeners();
return result;
}
Future<int> deleteNote(noteId) async{
var result = await databaseHelper.deleteNote(noteId);
await fetchNotes();
notifyListeners();
return result;
}
}
Here's the repo, in case you wish to run the app : Repo
Directory Structure :
lib
├── main.dart
├── models
│ └── note.dart
├── screens
│ ├── note_detail.dart
│ └── note_list.dart
└── utils
├── database_helper.dart
└── NoteProvider.dart
Video of the problem : https://youtu.be/YrAVTum9P6E
Update :
Since in the constructor for noteProvider I've fetchNotes so maybe due to that, when the app is loaded it's being fetched and due to that I added in all other functions too. But that didn't end as expected and am still facing the error.
Help with design and best practices
Moreover it would be better if someone could point to me some resources like blog/actual code where I can see this implemented. That would be really awesome.
Thanks.