rrousselGit / state_notifier

ValueNotifier, but outside Flutter and with some extra perks
MIT License
311 stars 28 forks source link

[Question] Does StateNotifier works with StreamProvider #29

Closed hsul4n closed 4 years ago

hsul4n commented 4 years ago

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(),
      ),
    );
  }
}
rrousselGit commented 4 years ago

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
  }
}
hsul4n commented 4 years ago

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.

rrousselGit commented 4 years ago

LocatorMixin works only with StateNotifier

hsul4n commented 4 years ago

LocatorMixin works only with StateNotifier

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

rrousselGit commented 4 years ago

Not for now, no. But PRs are welcomed

hsul4n commented 4 years ago

Not for now, no. But PRs are welcomed

I like that.. 👍