Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// ignore_for_file: public_member_api_docs
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
/// A provider that exposes a [ValueNotifier] in two independent pieces.
///
/// [StoreProvider] will expose both [ValueNotifier] and [ValueNotifier.value] independently
/// to its dependents.
///
/// For the [ValueNotifier]:
///
/// ```dart
/// class MyStore extends ValueNotifier<int> {
/// MyStore(): super(0);
/// }
/// ```
///
/// it is possible to obtain the `MyStore` instance through:
///
/// ```dart
/// context.watch<MyStore>(context);
/// ```
///
/// and the current value through:
///
/// ```dart
/// context.watch<int>(context);
/// ```
class StoreProvider<Value, Controller extends ValueNotifier<Value>> extends SingleChildStatelessWidget {
/// Allows to specify parameters to [StoreProvider].
StoreProvider({
Key key,
@required this.create,
Widget child,
}) : super(key: key, child: child);
final Create<Controller> create;
@override
Widget buildWithChild(BuildContext context, Widget child) {
return InheritedProvider<Controller>(
create: create,
builder: (context, _) {
return ValueListenableProvider<Value>.value(
value: context.watch<Controller>(),
child: child,
);
},
);
}
}
import 'package:flutter/widgets.dart';
enum _Action {
increment,
decrement,
}
class MyStore extends ValueNotifier<int> {
MyStore() : super(0);
void increment() => value++;
void decrement() => value--;
}
class Bar {}
class Initial implements Bar {}
class Loading implements Bar {}
class Error implements Bar {
Error(this.err);
final Object err;
}
class Loaded implements Bar {
Loaded(this.value);
final int value;
}
class Foo extends ValueNotifier<Bar> {
Foo() : super(Initial());
Future<void> fetch() async {
value = Loading();
try {
final result = await Future<int>.delayed(Duration(seconds: 1));
value = Loaded(result);
} catch (err) {
value = Error(err);
}
}
}
@love179902483

This comment has been minimized.

Copy link

@love179902483 love179902483 commented Feb 3, 2020

看不懂

@zsytssk

This comment has been minimized.

Copy link

@zsytssk zsytssk commented Oct 30, 2020

...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment