Riverpods with hooks Flutter – using Provider

Issue

Could someone give an example of additional state modifications in Riverpods preferably with riverpod_hooks – I’d like to be able to use it without making an additional widget, so for example:

onPress: () {
           useProvider(genderProvider).state = Gender.female;
           },

I’m having a bit of difficulty understanding the Riverpods documentation with regards to using the provider once it’s been implemented. I understand the increment portion .state++, but I can’t find a clear example of changing the state value after initialization. As in x is initialized to zero but you just want to make it 42 or an input value.

For instance I have an enum of Gender {male, female, non-binary} and I made a GenderProvider but I’m having trouble figuring out the best way to be able to change the gender in my app using a button. I’m also not entirely sure how much alike Provider and RiverPods are, it seems like there are a lot of semantical differences?

this is how the provider is declared in my code currently:

enum Gender {
  male,
  female,
  nonBinary
}

final genderProvider = StateProvider((_) => Gender.female);

Thanks in advance, I appreciate any suggestions.

Solution

onPress: () => context.read(genderProvider).state = Gender.female,

enter image description here

Full Source Code:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

void main() {
  runApp(
    ProviderScope(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        home: HomePage(),
      ),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final gender = useProvider(genderProvider).state;
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Gender: ${describeEnum(gender)}'),
            const SizedBox(height: 16.0),
            ElevatedButton(
              child: Text('MALE'),
              onPressed: () => context.read(genderProvider).state = Gender.male,
            ),
            const SizedBox(height: 8.0),
            ElevatedButton(
              child: Text('FEMALE'),
              onPressed: () =>
                  context.read(genderProvider).state = Gender.female,
            ),
          ],
        ),
      ),
    );
  }
}

enum Gender { male, female, nonBinary }

final genderProvider = StateProvider((_) => Gender.female);

Answered By – Thierry

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.