Skip to content

Instantly share code, notes, and snippets.

@rrousselGit
Last active February 5, 2023 14:17
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rrousselGit/4910f3125e41600df3c2577e26967c91 to your computer and use it in GitHub Desktop.
Save rrousselGit/4910f3125e41600df3c2577e26967c91 to your computer and use it in GitHub Desktop.
// 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
Copy link

看不懂

@zsytssk
Copy link

zsytssk commented Oct 30, 2020

...

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