1

I have a provider which defaults to Throwing UnimplemedtedError.. I wanted to override it and give a value while navigating to another screen because I need the value for the next screen. see below my implementation

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter chat Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutterfire_ui order'),
    );
  }
}

class MyHomePage extends ConsumerStatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  ConsumerState<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends ConsumerState<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final test = TestObject(
        id: '123455', content: 'test content', other: 'other value testing');
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [


            //*override 1
            //*doesnt work
            ProviderScope(
              overrides: [sampleProvider.overrideWithValue(test)],
              child: ElevatedButton(
                  onPressed: () => Navigator.of(context).push(
                      MaterialPageRoute(builder: (context) => const Screen2())),
                  child: const Text('go to screen2')),
            ),


            //* override 2
            //* this method works
            ElevatedButton(
                onPressed: () => Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => ProviderScope(
                        overrides: [sampleProvider.overrideWithValue(test)],
                        child: const Screen2()))),
                child: const Text('go to screen2')),
          ],
        ),
      ),
    );
  }
}


final sampleProvider =
    Provider<TestObject>((ref) => throw UnimplementedError());

.

As we can see I have 2 implementations where the first override doesn't work and throws an error. but the second implementation works fine. Now, I'm wondering why the first one doesn't work and the other one works when the implementation is almost the same?.

another question is while there is a way we can override a provider while navigating using Navigator 1.0, how can we implement the same when using go_router?

john
  • 1,438
  • 8
  • 18

0 Answers0