Flutter Riverpod call StateProvider within a class that itself is a StateProvider - flutter

I have a Class that is being called by Widgets but this Class needs to pull data from another Class. Basically, I am using Riverpod as Dependency Injection, and am unsure if this is "correct" or am I doing it wrong. Here is what I did:
main.dart
var myClass1 = Class1();
final class1Provider = StateProvider((ref) => myClass1);
final class2Provider = StateProvider((ref) => Class2(myClass1));
Is this the recommended way or should I do something else?
FYI this does work;
Widget build(BuildContext context) {
displayData = (ref.watch(class2Provider.notifier).state).getData();
thanks

This is incorrect. You are using riverpod but are mixing it with global variables which trashes the whole point of using a state-management library.
You should create instances inside the StateProvider:
final class1Provider = StateProvider((ref) => Class1());
In order to access the value of one provider in another you need to use ref.watch() method inside the body of the provider:
final class2Provider = StateProvider((ref) {
final myClass1 = ref.watch(class1Provider);
return Class2(myClass1);
});
Finally, to consume a StateProvider you are watching the notifier instead of the state. This will give you an initial value correctly but will not rebuild your UI when the state changes. Instead you should watch the provider directly.
Widget build(BuildContext context) {
final displayData = ref.watch(class2Provider).getData();
}
For more info read the docs thoroughly https://riverpod.dev/docs/getting_started/.

Related

Modifying Lists inside of classes - Flutter, Riverpod, Hooks

I would like to have a class that contains a list of another class and be able to update it using Riverpod/Hooks. I'm trying to figure out the best syntax or even way to approach the issue.
I'm starting with a StateProvider to make it simpler and thought to use the List method .add() to add to the list but I'm getting the error: "The method 'add' can't be unconditionally invoked because the receiver can be 'null'." or null check operator used on null value (when I add the !)- so I think I'm not writing it correctly and I'm sure it has to do with the Riverpod or even Dart syntax.
Any suggestions or resources would be appreciated. Thanks in advance.
So for example:
Session({this.title, this.sessionThings})
String? title;
List<SessionThings> sessionThings;
}
class SessionThings{
SessionThings({this.title, this.time})
String? title;
double? time;
}
ref.read(buildExSessionProvider.notifier).state = Session()..sessionThings.add(SessionThings(title: 'something', time: 20);
using:
hooks_riverpod: ^1.0.3
flutter_hooks: ^0.18.3
Do not access state outside a notifier. Something like this could work:
class SessionStateNotifier extends StateNotifier<Session?> {
SessionStateNotifier() : super(null);
void create(String title) => state = Session(title: title);
void add(SessionThings things) =>
state = Session(title: state?.title, sessionThings: [...state?.sessionThings ?? [], things]);
}
Use with hooks
class MyApp extends HookConsumerWidget {
#override
Widget build(BuildContext context, WidgetRef ref) {
final state = useState(0);
final Session? session = ref.watch(sessionProvider);
final SessionStateNotifier sessionStateNotifier = ref.watch(sessionProvider.notifier);
return <widget>
}
}
``

Flutter Riverpod listen not being invoked

I'm trying to implement just a basic listener in a widget (I will want to show a snackbar) but it just isnt being invoked by the provider. Cant see what Im doing wrong here.
I've tried from other widgets and the listener still doesn't hear the event.
Any ideas?
int foo = 1;
final FooProvider = Provider<int>((ref) {
foo = foo + 1;
return foo;
});
class showSnack extends ConsumerWidget {
final int taskID;
const showSnack(this.taskID);
#override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<int>(FooProvider, (int? previousCount, int newCount) {
logger.d("Fooo event");
});
return TaskInfo(taskID);
}
}
The basic Provider is not a state-holding type of provider. It's basically a static provider of some sort of data or a service class, meaning that it can't be used to watch for state changes or for listening.
You should probably use the StateProvider, StateNotifierProvider or the ChangeNotifierProvider. You can read more about the different providers in the documentation.

How do I go about synchronously initialising my provider? (Riverpod)

I have a provider like so:
final profileImagesProvider =
ChangeNotifierProvider.family<ProfileImagesNotifier, List<String>>(
(ref, profileImages) => ProfileImagesNotifier(profileImages));
class ProfileImagesNotifier extends ChangeNotifier {
ProfileImagesNotifier(List<String> images);
List<String> images;
}
However, when I try to use the provider:
Widget build(BuildContext context, ScopedReader watch) {
var profileImages = watch(ProfileImagesNotifier(['test_1.png', 'test_2.png']))
print(profileImages.images) //null
}
The list is retrieved as a null.
Am I doing this right? (I'm a completely noob when it comes to river pod and state management).
Was incorrectly calling the constructor.
Should have been:
ProfileImagesNotifier(this.images);
rather than
ProfileImagesNotifier(List<String> images);

How to create a dependency for ChangeNotifierProvider and make it wait to complete?

I have ChangeNotifierProvider object that uses data stored sqflite asset database which need to be loaded at the beginning as future. The problem is that ChangeNotifierProvider doesn't wait for future operation to complete. I tried to add a mechanism to make ChangeNotifierProvider wait but couldn't succeed. (tried FutureBuilder, FutureProvider, using all together etc...)
Note : FutureProvider solves waiting problem but it doesn't listen the object as ChangeNotifierProvider does. When I use them in multiprovider I had two different object instances...
All solutions that I found in StackOverflow or other sites don't give a general solution or approach for this particular problem. (or I couldn't find) I believe there must be a very basic solution/approach and decided to ask for your help. How can I implement a future to this code or how can I make ChangeNotifierProvider wait for future?
Here is my summary code;
class DataSource with ChangeNotifier {
int _myId;
List _myList;
int get myId => _myId;
List get myList => _myList;
void setMyId(int changeMyId) {
_myId = changeMyId;
notifyListeners();
}
.... same setter code for myList object.
DataSource(){initDatabase();}
Future<bool> initDatabase() {
.... fetching data from asset database. (this code works properly)
return true;
}
}
main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<DataSource>(
create: (context) => DataSource(),
child: MaterialApp(
home: HomePage(),
),
);
}
}
Following code and widgets has this code part (it works fine)
return Consumer<DataSource>(
builder: (context, myDataSource, child) {.......
There are multiple ways that you can achieve. The main point of it is that you should stick to reactive principle rather than trying to await the change. Say for example, you could change the state of boolean value inside the DataSource class when the ajax request changes
class DataSource extends ChangeNotifier{
bool isDone = false;
Future<bool> initDatabase(){
//Do Whatever
isDone = true;
notifyListeners();
}
}
Then you could listen to this change in the build method like so
Widget build(BuildContext ctx){
bool isDone = Provider.of<DataSource>(context).isDone;
if(isDone){
// render result
}else{
// maybe render loading
}
}

Flutter Provider, using child widget to update a list

I'm new to using Flutter and I am currently struggling to understand how to use the Provider package for the following task, or if it is even the correct implementation in the first place.
I have a widget that uses another widget within itself to update a time value.
In the parent widget I have the following:
class _AddTimesScreenState extends State<AddTimesScreen> {
List<TimeOfDay> times = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Provider<List<TimeOfDay>>.value(
value: times,
child: SetTimes()
In the 2nd widget, which is used to update the times list by using a time picker I have:
class _SetTimesState extends State<SetTimes> {
#override
Widget build(BuildContext context) {
final times = Provider.of<List<TimeOfDay>>(context);
Essentially my goal is to be able to update the times list in the 2nd widget so it can then be used in the first widget. I have methods to add TimeOfDay objects to the list, but when the code is run the list in the first widget does not appear to be updated.
Am I using Provider in a way that it's intended, or have I completely misunderstood its application?
Thanks
In the TimeOfDay class make sure you are extending it with Change Notifier.
How does provider know it has to rebuild?
When the class (TimeOfDay in your case) extends ChangeNotifier, you are provided with a method called notifylisteners() , this triggers a rebuild to all the widgets consuming the provider. So you should call this in the function that is changing the objects data in your class TimeOfDay.
So make sure you are:
extending ChangeNotifier in your class/model.
calling notifylisteners when data is changed.
Example :
class MyClass extends ChangeNotifier{
int a = 0;
addSomething(){
//Here we are changing data
a = a + 1;
notifylisteners();
}
}
let me know if this solves your error.