Ad

Future Builder Runs Forever, If Memoizer Used Doesnt Notify To The Listerners

I am trying to switch the drawer tab, according to the value stored in shared preferences using the following code.

code works fine when memoizer is not used but future builder runs forever.

If I use memorizer future builder still runs at least two times (not forever), but get and set functions doesn't work and new values are not updated and are not notified to the widgets.

I need some way to stop running future builder forever and notify users as well accordingly by triggering get and set functions present in it

Notifier class

class SwitchAppProvider extends ChangeNotifier {


  switchApp(value) async {

     
        // initialize instance of sharedpreference
        SharedPreferences prefs = await SharedPreferences.getInstance();

        prefs.setBool('key', value);

        notifyListeners();
     
  }


Future<bool?> getValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final value = prefs.getBool('key');
    return value;
  }
}

Drawer

Widget _buildDrawer() {
  return ChangeNotifierProvider<SwitchAppProvider>(
    create: (context) => SwitchAppProvider(),
    child: Consumer<SwitchAppProvider>(
      builder: (context, provider, _) {
        return Container(
          width: 260,
          child: Drawer(
            child: Material(
              color: Color.fromRGBO(62, 180, 137, 1),
              child: ListView(
                children: <Widget>[
                  Container(
                    padding: AppLandingView.padding,
                    child: Column(
                      children: [
                        const SizedBox(height: 10),
                        FutureBuilder(
                          future: provider.getValue(),
                          builder: (BuildContext context,
                              AsyncSnapshot<dynamic> snapshot) {
                            if (snapshot.data == true) {
                              return _buildMenuItem(
                                text: 'widget1',
                                icon: Icons.add_business,
                                onTap: () {
                                  provider.switchApp(false);
                                },
                              );
                            } else {
                              return _buildMenuItem(
                                text: 'widget2',
                                icon: Icons.add_business,
                                onTap: () {
                                  provider.switchApp(true);
                                },
                              );
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    ),
  );
}

Scaffold

@override
Widget build(BuildContext context) {
  return Scaffold(
    drawer: _buildDrawer(),
  );
}

Update

I analysed further, problem lies in provider.getValue(), if i use notifyListeners() before returning the value future builder runs forever

I removed it and the future builder doesn't run forever, but it doesn't update other widgets.

Scenario is

widget 1

  1. contains a drawer
  2. has a button to switch app
  3. on tap value is set using shared preferences (setValue() function) and listeners are notified
  4. in widget 1 notifier is working well and changing the drawer button option when setValue() is called on tap.
  5. everything resolved in widget 1, as its calling setValue() hence notifyListeners() is triggered and widget1 is rerendered

widget 2

  1. only gets value from shared preferences(getValue() function). getValue function cant use notifyListeners(), if used futurebuilder is running forever

  2. widget 2 don't set any value so it doesn't use setValue() hence it's not getting notified

  3. how I can notify widget 2, when on tap setValue() is triggered in widget 1

i.e widget1 sets the app using setValue() function

widget2 gets value from getValue() function and get notified

Update 2

class SwitchAppProvider with ChangeNotifier {
   dynamic  _myValue;

  dynamic get myValue => _myValue;

   set myValue(dynamic newValue) {
     _myValue = newValue;
     notifyListeners();
   }

  setValue(value) async {
    // initialize instance of sharedpreference
    SharedPreferences prefs = await SharedPreferences.getInstance();

     await  prefs.setBool('key', value);

    notifyListeners();
  }

  SwitchAppProvider(){
    getValue();
  }

  Future<void> getValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
     myValue = prefs.getBool('key');


  }


}


widget 2

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
        value: SwitchAppProvider(),

        child:  Consumer<SwitchAppProvider>(
            builder: (BuildContext context, SwitchAppProvider provider, _) {



              if (provider.myValue == true) {
                return Center(
                  child: CircularProgressIndicator(),
                );
              } else {
                return Container(
                    child: Text('provider.myValue'));
              }
            })
    );
  }
}

_buildMenuItem

  // helper widget to build item of drawer
  Widget _buildMenuItem({
    required String text,
    required IconData icon,
    required GestureTapCallback onTap,
  }) {
    final color = Colors.white;
    final hoverColor = Colors.white;

    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(text, style: TextStyle(color: color, fontSize: 18)),
      hoverColor: hoverColor,
      onTap: onTap,
    );
  }

Ad

Answer

"If I use memorizer future builder still runs at least two times (not forever), but get and set functions doesn't work and new values are not updated and are not notified to the widgets."

That is the expected behaviour:

An AsyncMemoizer is used when some function may be run multiple times in order to get its result, but it only actually needs to be run once for its effect. 

so prefs.setBool('key', value); is executed only the first time.

You definitely do not want to use it.

If you edit your code to remove the AsyncMemoizer, we can try to help you further.

Edit after Update

You are right, the getValue() function should not notify listeners, if it does that, then the listeners will rebuild and ask for the value again, which will notify listeners, which will rebuild and ask for the value again, which... (you get the point).

There is something wrong in your reasoning. widget1 and widget2 are not notified, the Consumer is notified. Which will rebuild everything. The code is quite complicated and it could be simplified a lot by removing unneeded widgets.

I will suggest you to

  1. await prefs.setBool('isWhatsappBusiness', value); before notifying listeners.
  2. have a look at this answer for a similar problem.

Edit 3

I do not know what you are doing wrong, but this works:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

class SwitchAppProvider extends ChangeNotifier {
  switchApp(value) async {
    // initialize instance of sharedpreference
    SharedPreferences prefs = await SharedPreferences.getInstance();

    await prefs.setBool('key', value);

    notifyListeners();
  }

  Future<bool?> getValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final value = prefs.getBool('key');
    return value;
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        drawer: _buildDrawer(),
      ),
    );
  }

  Widget _buildDrawer() {
    return ChangeNotifierProvider<SwitchAppProvider>(
      create: (context) => SwitchAppProvider(),
      child: Consumer<SwitchAppProvider>(
        builder: (context, provider, _) {
          return SizedBox(
            width: 260,
            child: Drawer(
              child: Material(
                color: const Color.fromRGBO(62, 180, 137, 1),
                child: ListView(
                  children: <Widget>[
                    Column(
                      children: [
                        const SizedBox(height: 10),
                        FutureBuilder(
                          future: provider.getValue(),
                          builder: (BuildContext context,
                              AsyncSnapshot<dynamic> snapshot) {
                            print('Am I building?');
                            if (snapshot.data == true) {
                              return ListTile(
                                tileColor: Colors.red[200],
                                title: const Text('widget1'),
                                leading: const Icon(Icons.flutter_dash),
                                onTap: () {
                                  provider.switchApp(false);
                                },
                              );
                            } else {
                              return ListTile(
                                tileColor: Colors.green[200],
                                title: const Text('widget2'),
                                leading: const Icon(Icons.ac_unit),
                                onTap: () {
                                  provider.switchApp(true);
                                },
                              );
                            }
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

If you still cannot get it working, then the problem is somewhere else.

Edit 4

First, I suggest you to be more clear in future questions. Write all the code that is needed immediately and remove widgets that are not needed. Avoid confusion given by naming different things in the same way.

The second widget does not update because it is listening to a different notifier.

When you do

return ChangeNotifierProvider.value(
        value: SwitchAppProvider(),

in Widget2 you are creating a new provider object, you are not listening to changes in the provider you created in the Drawer.

You need to move the ChangeNotifierProvider.value widget higher in the widget tree, and use the same one:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

class SwitchAppProvider extends ChangeNotifier {
  switchApp(value) async {
    // initialize instance of sharedpreference
    SharedPreferences prefs = await SharedPreferences.getInstance();

    await prefs.setBool('key', value);

    notifyListeners();
  }

  Future<bool?> getValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final value = prefs.getBool('key');
    return value;
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChangeNotifierProvider<SwitchAppProvider>(
        create: (context) => SwitchAppProvider(),
        child: Scaffold(
          appBar: AppBar(),
          drawer: _buildDrawer(),
          body: const Widget2(),
        ),
      ),
    );
  }

  Widget _buildDrawer() {
    return Consumer<SwitchAppProvider>(builder: (context, provider, _) {
      return SizedBox(
        width: 260,
        child: Drawer(
          child: Material(
            color: const Color.fromRGBO(62, 180, 137, 1),
            child: ListView(
              children: <Widget>[
                Column(
                  children: [
                    const SizedBox(height: 10),
                    FutureBuilder(
                      future: provider.getValue(),
                      builder: (BuildContext context,
                          AsyncSnapshot<dynamic> snapshot) {
                        print('Am I building?');
                        if (snapshot.data == true) {
                          return ListTile(
                            tileColor: Colors.red[200],
                            title: const Text('widget1'),
                            leading: const Icon(Icons.flutter_dash),
                            onTap: () {
                              provider.switchApp(false);
                            },
                          );
                        } else {
                          return ListTile(
                            tileColor: Colors.green[200],
                            title: const Text('widget2'),
                            leading: const Icon(Icons.ac_unit),
                            onTap: () {
                              provider.switchApp(true);
                            },
                          );
                        }
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    });
  }
}

class Widget2 extends StatelessWidget {
  const Widget2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<SwitchAppProvider>(
      builder: (BuildContext context, SwitchAppProvider provider, _) {
        return FutureBuilder(
          future: provider.getValue(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            print('Am I building even more ?');
            if (snapshot.data == true) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return const Text('provider.myValue');
            }
          },
        );
      },
    );
  }
}
Ad
source: stackoverflow.com
Ad