Home > Enterprise >  Provider not updating value possible string to double issue
Provider not updating value possible string to double issue

Time:03-22

I am new to flutter and attempting to write my first app on my own outside of a course. I am working with using the Flutter Provider package, and I am successfully able to read values using Provide, but I am having issues writing over values to update them with Provider.

Code Walk Through

In my main.dar I am calling the create command on my class Week()

return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => WeekList()),
        ChangeNotifierProvider(create: (context) => Week()),
      ],
    ...

I think my issue might be going back and forth between String and double types.

In an alert Diolog I am calling,

String curentbudget = Provider.of<Week>(context).budget.toString();

That part works perfect and I then can assign the value to the TextEditingController

TextEditingController currentBudgetController = TextEditingController(text: curentbudget);

After editing the value in the alert dialog, I then try to save the value with my update function:

onPressed: () {
      //save new value
      double budgetDouble =double.parse(currentBudgetController.text);
      Provider.of<Week>(context, listen: false).updateBudget(newBudget: budgetDouble);
      //close Dialog
      Navigator.of(context).pop();
}

Again, not sure if it's not saving because it's a double / string issue.

My Week Class update function looks like this:

  //updateBudget
  void updateBudget({
    required double newBudget,
  }) {
    Week().budget = newBudget;
    notifyListeners();
  }

And the location I am trying to update the budget is:

child: Text(
        Provider.of<Week>(context).budget.toString(),
        style: const TextStyle(fontSize: 25.0),
      ),

Troubleshooting:

I stepped through with the debugger and when I update the value to let's say 300.0 I successfully get that value through the update function:

Week().budget = newBudget;

the next line is the notifyListeners(); and it looks like thats not updating the value in my view for some reason.

CodePudding user response:

You can call your method like this,

double budget = 0.0;

  void updateBudget({required double newBudget}) {
    budget = newBudget;
    notifyListeners();
  }

For getting the value you can use Consumer widget.

child: Consumer<Week>(builder: (context, weekData, child) {
   return Text(
      weekData.budget.toString(),
   );
}),
  • Related