0
votes

Let's say I have two text fields rendered in Flutter: "net price" and "gross price". I'd like to sync them so when user updates the net price, the gross price is automatically calculated and updated. When the user changes the gross price, the net price field should be updated. How can I achieve such behaviour in Flutter?

1
Use TextEditingControllers. Since your TextFields are likely to reside in the same Widget, I think Provider is an overkill here... - Riwen

1 Answers

2
votes

I would recommend using the provider package for this problem.

Basically, you create a class which extends ChangeNotifier and holds the values for the two TextFields, then you provide it for both of the Text widgets, somewhere in a common parent widget with:

ChangeNotifierProvider(
  create: (context) => MyClass(),
  child: MyApp(),
),

Now whenever you change one of the TextFields just call a function from MyClass which calculates what the new value should be for the other TextField. For example:

void calculate() {
    // Some calculation and updating the values of the TextFields
    notifyListeners();
  }

Notice the notifyListeners() call which tells the widgets that are listening to this model to rebuild.

To listen to this model wrap your Text widgets inside a consumer like:

return Consumer<MyClass>(
builder: (context, myClass, child) {
  return Text("Total price: ${myClass.netPrice}");
});

You can learn more from the flutter state management tutorial