0

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

KatieK
  • 83
  • 2
  • 7

1 Answers1

0

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>
  }
}
``
user18309290
  • 5,777
  • 2
  • 4
  • 22
  • That doesn't necessarily seem applicable to using Riverpod and flutter hooks. I could move into using a StateNotifierProvider and I was thinking of doing that long term however I don't have a huge level of comfort with notifiers yet. Can you provide explanation to your "do not access state outside a notifier" comment? – KatieK May 05 '22 at 07:57