FutureBuilder and ChangeNotifier in same widget

48 Views Asked by At

I have a use case in a widget where I load some initial data thru http and present that data on the widget and then I interact with the widget which causes the data to be updated. I guess this is a very common scenario in many apps

How should this be accomplished, do I load the initial data using FutureBuilder (I am doing this in another widget and it is working fine) and then do the updates using ChangeNotifier and notifying (with notifyListeners()) the widget that the data has been updated

How are these used together in the same widget ? Or is there some other pattern to use ? What is the best practice ?

1

There are 1 best solutions below

0
Hassan On BEST ANSWER

Not sure without seeing your code. But with the Provider we can handle it like following:

Your Widget

class YourWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          // Use FutureBuilder to load initial data
          FutureBuilder<String>(
            future: fetchData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                return Text('Data: ${snapshot.data}');
              }
            },
          ),
          ElevatedButton(
            onPressed: () {
              Provider.of<DataModel>(context, listen: false).updateData(
                  'Updated Data ${DateTime.now().millisecondsSinceEpoch}');
            },
            child: Text('Update Data'),
          ),
        ],
      ),
    );
  }

  // Simulated async function to fetch data
  Future<String> fetchData() async {
    await Future.delayed(Duration(seconds: 2)); // Simulating delay
    return 'Initial Data';
  }
}

Model class with change notifier

class DataModel extends ChangeNotifier {
  String _data = "Initial Data";

  String get data => _data;

  // Method to update data
  void updateData(String newData) {
    _data = newData;
    notifyListeners(); // Notify listeners that data has changed
  }
}