0

I'm implementing a chat-based app in Flutter. I was thinking of using Provider package to create two main notifiers: UserService and ChatService. The first one handles the signIn (and all the other functions user-related), while the latter handles chat specific functions. However, the chatService needs to access the UserService for some functionalities. I tried to use ProxyProvider and this is the code:

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<UserService>(builder: (_) => UserService.instance()),
        ChangeNotifierProxyProvider<UserService, ChatService>(builder: (_, user, chatService) => ChatService.init(user))
      ],
      child: MaterialApp(
          ...
      ),
    );
  }
}

However, when I run the app, flutter throws this error:

Tried to use Provider with a subtype of Listenable/Stream (ChatService).

This is likely a mistake, as Provider will not automatically update dependents when ChatService is updated. Instead, consider changing Provider for more specific implementation that handles the update mechanism, such as:

  • ListenableProvider
  • ChangeNotifierProvider
  • ValueListenableProvider

Thank you!

1 Answers1

3

It's not clear which "architecture" you are going to use, Provider is simply a mechanism to retrieve objects in the widget tree in a safe way.

Assuming you mean UserService and ChatService, and these are ChangeNotifiers (could be BLoC or anything else) - here's an example of how you'd hook them up with Provider:

main() {
  runApp(MultiProvider(
    providers: [
        ChangeNotifierProvider<UserService>(create: (_) => UserService()),
        ChangeNotifierProxyProvider<UserService, ChatService>(
          create: (_) => ChatService(),
          update: (_, userService, chatService) => chatService..userService= userService
        ),
      ],
      child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ChatService>(
      builder: (context, chatService, _) => Text(chatService.currentUser.lastMessage) // or whatever you need to do
    );
  }
}
Frank Treacy
  • 3,386
  • 1
  • 16
  • 16
  • with architecture I mean which components to create (in your case notifiers) and how many of them (one notifier to avoid my problem vs. two notifiers as in your case). Thank you for your reply! – Michele Papale Dec 19 '19 at 21:49
  • 1
    I had the same error, but now I see my error, I was using ProxyProvider instead of ChangeNotifierProxyProvider. Thanks!!! – Piyey May 13 '20 at 01:08