Solved: initializing variables before build in flutter?

Question

Asked by cvsrt on January 05, 2022 (source).

I am trying to initialize a variable in the initstate. Before initializing null value is used in my scaffold. How can I wait for a variable then later load the build?I am using shared_preference plugin. This is my initstate:

void initState() {
    super.initState();

    _createInterstitialAd();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();

      future = Provider.of<Titles>(context, listen: false).fetchAndSetPlaces();
      identifier = await getimages();
    });

Here I am checking if it is null and it is always null:

@override
  Widget build(BuildContext context) {
    print(prefs);

Answer

Question answered by Yashu A (source).

Why you want to initialize variable in init state . Use Future Builder inside your context and fetch variable data first and then your build will execute.

class FutureDemoPage extends StatelessWidget {



Future<String> getData() {
    return Future.delayed(Duration(seconds: 2), () {
      return "I am data";
      // throw Exception("Custom Error");
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('Future Demo Page'),
        ),
        body: FutureBuilder(
          builder: (ctx, snapshot) {
            // Checking if future is resolved or not
            if (snapshot.connectionState == ConnectionState.done) {
              // If we got an error
              if (snapshot.hasError) {
                return Center(
                  child: Text(
                    '${snapshot.error} occured',
                    style: TextStyle(fontSize: 18),
                  ),
                );
  
            // if we got our data
          } else if (snapshot.hasData) {
            // Extracting data from snapshot object
            final data = snapshot.data as String;
            return Center(
              child: Text(
                '$data',
                style: TextStyle(fontSize: 18),
              ),
            );
          }
        }

        // Displaying LoadingSpinner to indicate waiting state
        return Center(
          child: CircularProgressIndicator(),
        );
      },

      // Future that needs to be resolved
      // inorder to display something on the Canvas
      future: getData(),
    ),
  ),
);

} }

FLUTTER FLUTTER-SHAREDPREFERENCE SHAREDPREFERENCES
SHARE: