Reputation: 387
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);
Upvotes: 0
Views: 2675
Reputation: 1561
i assume you have 3 different condition : first wait data for prefences, get future data from that prefences, and render result.
try this: bloc pattern
its basically a Stream to different State and Logic part of app ui
Upvotes: 0
Reputation: 2127
First you have to understand the Life cycle of flutter. I make it simple for you..
So Every override function have fixed functionality. For example initState can use only for normal initialisation. It can not hold/await the flow for several time. So that why any async method is not applicable inside the initState.
For Solution you have to use FutureBuilder for awaiting data or before navigating to the next page initialise the preferences then proceeded.
Upvotes: 0
Reputation: 79
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(),
),
),
);
} }
Upvotes: 2
Reputation: 3514
If you want to initialize
a variable later then we have late
keyword for that purpose. You can use that like below when declaring
a variable :
late String prefs;
Upvotes: 0