Search code examples
flutterproviderchangenotifier

How to listen to multiple sources in flutter using a ChangeNotifier?


I have the widget whose text needs to update based on what is entered in two TextFields. What is the right way to listen to two sources in this situation (and in general)?

I just wrote two classes:

class MyTextField extends StatelessWidget {
  const MyTextField({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newData) => context.read<Data>().changeString(newData),
    );
  }
}

And MyTextField2 the same.

The HomePage widget:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('build HomePage');
    return Scaffold(
      appBar: AppBar(
        title: Container(child: Text(context.watch<Data>().getData),),
      ),
      body: Center(
        child: Column(
          children: [
            MyTextField(),
            MyTextField2(),
            Text(context.watch<Data>().getData),
          ],
        ),
      )
    );
  }
}

The Data class:

class Data with ChangeNotifier
{
  String _data = 'some text';
  String get getData => _data;

  void changeString(String newString)
  {
    _data = newString;
    notifyListeners();
  }
}

Am I correct in that the HomePage widget is listening to two sources? Can conflicts occur if both TextField are changed at the same time?


Solution

  • You can wrap MaterialApp in your main.dart file with MultiProvider(providers: [//your providers])