retrieve<VM extends ViewModel> static method

ViewModelConsumer retrieve<VM extends ViewModel>({
  1. Key? key,
  2. required ViewModelConsumerBuilder<VM> builder,
  3. Widget? child,
})

一个不创建 ViewModel 的 ViewModelConsumer,用于在 Widget 树中某个位置获取 ViewModel

Implementation

static ViewModelConsumer retrieve<VM extends ViewModel>({
  Key? key,
  required ViewModelConsumerBuilder<VM> builder,
  Widget? child,
}) {
  return ViewModelConsumer(
    key: key,
    creators: const [],
    shareStrategy: ViewModelShareStrategy.none,
    builder: (context, child) {
      final viewModel = context.getViewModel<VM>();
      assert(
        viewModel != null,
        'ViewModel of type $VM not found in context',
      );
      return builder(context, viewModel!, child);
    },
    child: child,
  );
}