How do I close a screen (call Navigator.pop
) when a certain value changes?
I am using riverpod
to watch for the values.
CodePudding user response:
You need to create some kind of Function that handle that. The function required a build context to get the Navigator and you could call the Navigator.of(context).pop or Navigator.pop(context) when you want.
onChangeValue(BuildContext context, dynamic value){
if(value!=null){
Navigator.of(context).pop();
}
}
CodePudding user response:
Use the WidgetRef.listen
to listen to state changes. From the docs:
Listen to a provider and call listener whenever its value changes.
This is useful for showing modals or other imperative logic.
The code is going to be something like this:
class MyHomePage extends ConsumerWidget {
const MyHomePage({super.key});
@override
Widget build(context, ref) {
ref.listen(theProvider, (previous, next) {
if (isTheEnd(next)) {
Navigator.of(context).pop();
}
});
...
Here's a complete example:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends ConsumerWidget {
const MyHomePage({super.key});
@override
Widget build(context, ref) {
ref.listen(counterProvider, (previous, next) {
if (next % 2 == 0) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Value is even: $next'),
),
);
}
});
final counter = ref.watch(counterProvider);
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
final counterProvider = StateNotifierProvider<Counter, int>((ref) {
return Counter();
});
class Counter extends StateNotifier<int> {
Counter() : super(0);
void increment() => state ;
}