I am using Flutters provider
library but I have problem getting it to update the UI.
I am performing a simple HTTP POST
and want to update my UI if an error occured.
This is the logic in my provider:
class DeviceProvider extends ChangeNotifier {
// Enum with possible states: Initial, Loading, Error & Success
APIState state = APIState.Initial;
...
void sendConfig() async {
try {
http.Response postResponse = await http.post(...);
if (postResponse.ok) {
state = APIState.Success;
} else {
state = APIState.Error;
}
} on SocketException catch (e) {
state = APIState.Error;
}
notifyListeners();
}
}
This my UI:
return ChangeNotifierProvider<DeviceProvider>(
create: (_) => DeviceProvider(),
child: Consumer<DeviceProvider>(
builder: (_, model, __) {
switch (model.state) {
// Display error
case APIState.Error:
return Text('Error');
// Ignore all other states
case APIState.Loading:
case APIState.Initial:
case APIState.Success:
return const Visibility(
child: Text("Gone"),
visible: false,
);
}
},
),
);
My main.dart looks like this:
void main() => runApp(
MultiProvider(
providers: [
...
ChangeNotifierProvider<DeviceProvider>(create: (_) => DeviceProvider()),
],
child: const MyApp(),
),
);
Now, I know for a fact that the code is executed and that the state is indeed Error
.
However, my error widget does not seem to be notified at all even tho I call notifyListeners
.
What am I missing?
CodePudding user response:
i think the problem arises when you use an other change notifier provider in your ui . when you trigger send config function you are triggering it with change notifier provider that you provided in your main.dart thats ok and all . but in your ui you attach a consumer to another provider in which you haven't triggered send config.
FIX : DON'T RETURN A ChangeNotifierProvider INSTEAD JUST RETURN A CONSUMER