-1

right now i have a ChangeNotifierProvider, and i want to set some values straight in the initState method. those values come from a backend API, that are retrieved in that provider.

I am stuck is this situation for a while now, hope i can get some help.

Here is the ChangeNotifierProvider

final userProvider = ChangeNotifierProvider.autoDispose.family<UserProxy, String>((ref, id) {
  var notifier = UserProxy(userId: id);

  notifier.load();

  return notifier;
});

class UserProxy extends ChangeNotifier {
  String userId;

  User? user;

  UserProxy({this.userId = ""});

  void load() async {
      await getUser().then((value) => generateObject(value));
  }

  Future<String> getUser() async {
    Map<String, String> queryParams = {
      "id": userId,
    };

    var url = Uri.https("asdadas.asdasd.com", "endpoint", queryParams);

    Map<String, String> headers = {
      'content-type': "application/json",
    };

    var response = await http.get(url,
        headers: headers,);

    print(response.body);

    return response.body;
  }

  User generateObject(String jsonString) {
    this.user = User.fromJson(jsonDecode(jsonString));

    notifyListeners();

    return this.user ?? User();
  }
}
filipe
  • 139
  • 2
  • 17
  • If you are using `Riverpod` for state management, you don't need to use `Stateful Widgets`. Meaning that you wouldn't have an `initState`. You may be confused about how to use `Riverpod`. – J. S. Oct 13 '21 at 10:06
  • i can say that i am, because i am doing a project at work, never done flutter, i am only a backend software dev... The reason for my question, is because i am trying to create the edit page for the mobile app, so i need to set the controllers text based on the data that comes from db, but if i do that in the build method, is always reseting – filipe Oct 13 '21 at 10:14
  • I understand the issue. In my opinion `Riverpod` is not the easiest state management to understand and use as a new Flutter developer. Using something simpler like `Provider` or `ScopedModel` would be easier. Having said that, try taking a look at how the creator of `Riverpod` does it: https://github.com/rrousselGit/river_pod/blob/master/examples/todos/lib/main.dart – J. S. Oct 13 '21 at 10:20
  • thanks for your help, i will check it out, once again appreciate it – filipe Oct 13 '21 at 10:25

1 Answers1

1

For this case I would suggest

FutureProvider.autoDispose.family<UserProxy, String>((ref, id) async { .... })

then change your StateWidget to ConsumerStatefulWidget and ConsumerState<> then

ref.watch(provider(11)).when(
  loading: (){},
  error: (Object err, StackTrace? st){ },
  data: (user){
    // build widget with result here.

  },
)
Akabrando
  • 176
  • 1
  • 9