Search code examples
flutterdartprovider

flutter toggle a state with provider state management flutter


I'm trying to implement a provider to render between different widget when the state changes.

Here, I have defined a function called toggleContainer() in the provider controller.

class UserNotifier extends ChangeNotifier {
  toggleContainer() {
    bool isExpanded = false;
    if (isExpanded == false) {
      isExpanded = true;
    } else {
      isExpanded = false;
    }
    notifyListeners();
  }
}

Then, in the app I declared the useNofifier as below and also implement the function

Widget build(BuildContext context) {
    UserNotifier userNotifier = Provider.of<UserNotifier>(context);
    return Scaffold(
      body: Container(
        padding: EdgeInsets.only( ...

           GestureDetector(
              onTap: () {
                userNotifier.toggleContainer();
              },
              child: Container(
                child: userNotifier.isEpanded ? Text("close") : Text('open'), //isExpanded is undifened
              ),
            ),

So now, I don't the proper implementation and the isEpanded returns undefined.

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserNotifier()),
      ],
      child: const MyApp(),
    ),
  );
}


Solution

  • First issue is coming because isExpanded is inside toggleContainer(). It will be on class level.

    class UserNotifier extends ChangeNotifier {
      bool isExpanded = false;
      toggleContainer() { 
        isExpanded = !isExpanded;
        notifyListeners();
      }
    }
    

    Next issue is typo, it will be child: userNotifier.isExpanded.

    But it will be recommended to use Consumer widget in this case

    Consumer<UserNotifier>(
      builder: (context, value, child) {
        return GestureDetector(
          onTap: () {
            value.toggleContainer();
          },
          child: Container(
            child: value.isExpanded
                ? const Text("close")
                : const Text('open'), //isExpanded is undifened
          ),
        );
      },
    )