I’m trying to use ".when" method on a provider I created but I got "The method when isn’t defined for the type Future"
I would like to use a service class for all my bluetooth method.
part 'bluetooth_manager.g.dart';
@riverpod
class BluetoothService extends _$BluetoothService {
@override
void build() {}
Future<List<Device>> discoverDevices() async {
//Scan devices
await Future.delayed(const Duration(seconds: 5));
}
}
View:
class ModulesView extends ConsumerWidget {
const ModulesView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: ref.watch(bluetoothServiceProvider.notifier).discoverDevices().when(
data: (data) => modulesFound(ref, data),
loading: () => loading(),
error: (error, stacktrace) => ErrorView(errorMessage: "errorMessage", retryFunction: () {}),
),
),
);
}
}
2
Answers
In your code,
discoverDevices
is just a regular function. If you need to expose its value so that you can "watch" it, make it the returned value of thebuild
method. Other methods that don’t need their values to be watched can stay in the notifier. You can call them and get their values imperatively, for example in a button callback.In your widget, you can use it like this (I use explicit type annotations for clarity):
Generally, it should follow the pattern from this example.
If you need a value to update the UI, you should wrap the discoverDevices method with a FutureProvider
then you should be able to watch in the builder
otherwise you can call bluetoothServiceProvider directly if you have other method that does not require UI changes