How to initiate ValueNotifier value from Future

Issue

I need to initiate my ChangeNotifierProvider<ValueNotifier> from http result. I have service like this.

class AddressService {
  Future<Address> getMainAddress() async {
     return await callHttpHere();
  }
}

And in my StatelessWidget:

Widget build(BuildContext context){
  return Scaffold(
    body: ChangeNotifierProvider<ValueNotifier<Address>>(
      create: (_) => ValueNotifier(IWantInitiateThisFrom_GetMainAddress);
    ),
  );
}

Solution

You can use a FutureBuilder:

Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder(
      builder: (context, AsyncSnapshot<Address> snapshot) {
        if (!snapshot.hasData) return Container();

        return ChangeNotifierProvider<ValueNotifier<Address>>(
          create: (_) => ValueNotifier(snapshot.data),
        );
      },
    ),
  );
}

Answered By – creativecreatorormaybenot

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.