rrousselGit/state_notifier

[Question] Does StateNotifier works with StreamProvider

hsul4n opened this issue · 6 comments

Does state_notifier support StreamProvider for watching changes so, for example, I'm trying to listen to connectivity changes.

Here's the example:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<ConnectivityResult>(
          create: (_) => Connectivity().onConnectivityChanged,
        ),
        ChangeNotifierProvider<Counter>(
          create: (_) => Counter(),
        ),
      ],
      child: MaterialApp(
        home: MyHomePage(),
      ),
    );
  }
}

class Counter extends ValueNotifier<int> with LocatorMixin {
  Counter() : super(0);

  void increment() {
    this.value++;
    if (read<ConnectivityResult>() != ConnectivityResult.none) {
      // call api
    }
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Home Page'),
      ),
      body: Center(
        child:
            Text('You clicked button ${context.watch<Counter>().value} times'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => context.read<Counter>().increment(),
      ),
    );
  }
}

You can use the update method

ConnectivityResult lastConnectivity;

@override
void update(Reader watch) {
  final connectivity = watch<ConnectivityResult>();
  if (connectivity != lastConnectivity) {
    lastConnectivity = connectivity;
   // TODO API call
  }
}

You can use the update method

ConnectivityResult lastConnectivity;

@override
void update(Reader watch) {
  final connectivity = watch<ConnectivityResult>();
  if (connectivity != lastConnectivity) {
    lastConnectivity = connectivity;
   // TODO API call
  }
}

This works great with StateNotifier & StateNotifierProvider but what about if I'm using something like ChangeNotifierProvider or ValueNotifier as my example above.

LocatorMixin works only with StateNotifier

LocatorMixin works only with StateNotifier

So, is there any future planning for implementing with ‘Provider’.

Not for now, no. But PRs are welcomed

Not for now, no. But PRs are welcomed

I like that.. 👍