How to properly use flutter riverpod to share data between widgets in different files?

1k views Asked by At

I am able to share data between widgets when the widgets are int he same file but when the widgets are in different files, the ui does not rebuild and i do not seem to get it right.

Please kindly check my codes below and see where I'm falling short. (I added image for easy reading and text code for easy CTRL C - CTRL V)

Objective

I'm trying to share data between multiple widgets in different files IMAGE HERE

but it doesn't notify the other widgets / rebuild When button at line 45 is tapped, text at line 44 change successfully but screen at line 26 doesn't change

//--------------navigation_provider.dart----------------//

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class NavigationProvider extends ChangeNotifier{

bool showUserProfile = true;
  
void toggleProfile(toggle){
showUserProfile = toggle;
notifyListeners();
}
}

//--------------desktop_scaffold.dart----------------//

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:premiumpeaches/providers/navigation_provider.dart';
import 'package:flutter/material.dart';

final navigatorProvider = ChangeNotifierProvider((ref) => NavigationProvider());
class DesktopScaffold extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return SizedBox(
      child: ref.watch(navigatorProvider).showUserProfile == true ? UserProfileComponent() : ProfileSettingsComponent()
    )
  
}

//--------------user_profile_component.dart----------------//

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:premiumpeaches/providers/navigation_provider.dart';
import 'package:flutter/material.dart';

final navigatorProvider = ChangeNotifierProvider((ref) => NavigationProvider());
class UserProfileComponent extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return InkWell(
onTap:(){
ref.watch(navigatorProvider).toggleProfile(false);
},
child:Text('Click Me')
)
  
}
1

There are 1 answers

5
Rémi Rousselet On BEST ANSWER

You defined navigatorProvider twice.

That's likely the source of your problem. Two providers mean two different states. So interacting with one navigatorProvider has no effect on the other

Rather than defining navigatorProvider twice, you most likely instead want to import it.

For example inside desktop_scaffold.dart you could do:

import 'user_profile_component.dart';

You can then use navigatorProvider all the same. But now, you only have a single navigatorProvider, so all interactions goes through that one.