'Flutter: SharedPreferences showing null value?

eg: details about the questions ............................................................................................i have set a address in home page using SharedPreferences but when i get that value in SearchModulePage showing null. i have tried many more times always showing null

Home Page:-

    import 'dart:convert';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:double_back_to_close_app/double_back_to_close_app.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoder/geocoder.dart';
import 'package:http/http.dart' as http;
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/category_model.dart';
import 'package:newbharatbiz/Screens/SearchServiceProvider.dart';
import 'package:newbharatbiz/Screens/SubCategoryPage.dart';
import 'package:newbharatbiz/Utils/NavDrawer.dart';
import 'package:newbharatbiz/Utils/Serverlinks.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Model Class/banner_model.dart';
import 'VendorRegistrationPage.dart';
import 'package:location/location.dart';

import 'package:flutter/services.dart';

var addressLine;
var getaddressLine;
var androidDeviceInfo;
var token;
var identifier;
var user_id;
var phone;
var name;

class HomePage extends StatefulWidget {
  @override
  _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<HomePage> {
  Future<BannerModel> BannerList() async {
    final response = await http.get(Uri.parse(Serverlinks.all_banner));
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      print(response);
      return BannerModel.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }

  Future<CategoryModel> CategoryList() async {
    final response = await http.get(Uri.parse(Serverlinks.category_list));
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      print(response);

      return CategoryModel.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }

  // late DateTime currentBackPressTime;
  List<String> imagesList = [];
  var currentLocation;
  int currentIndexPage = 0;

  @override
  void initState() {
    super.initState();
    getUserLocation();
    getdeviceid();
    gettoken();
    Setsharedpreferencevalue();
    Getsharedpreferencevalue();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.deepOrangeAccent,
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => VendorRegistrationPage(),
            ),
          );
        },
      ),
      drawer: NavDrawer(),
      appBar:
          AppBar(title: Text('New Bharat Biz'), centerTitle: true, actions: [
        IconButton(
          onPressed: () async {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SearchServiceProvider(),
              ),
            );
          },
          icon: Icon(Icons.search),
        ),
      ]),
      body: DoubleBackToCloseApp(
        child: SingleChildScrollView(
          child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
            FutureBuilder<BannerModel>(
                future: BannerList(),
                builder: (BuildContext context, snapshot) {
                  if (snapshot.hasData) {
                    print((snapshot.data));
                    snapshot.data!.banner.forEach((e) {
                      imagesList.add(snapshot.data!.imgPath + e.image);
                      print(imagesList.length);
                    });
                    return CarouselSlider(
                      //add return keyword here
                      options: CarouselOptions(
                        height: 160,
                        aspectRatio: 16 / 9,
                        viewportFraction: 0.8,
                        initialPage: 0,
                        enableInfiniteScroll: true,
                        reverse: false,
                        autoPlay: true,
                        autoPlayInterval: const Duration(seconds: 3),
                        autoPlayAnimationDuration:
                            const Duration(milliseconds: 800),
                        autoPlayCurve: Curves.fastOutSlowIn,
                        enlargeCenterPage: true,
                      ),

                      items: imagesList
                          .map(
                            (item) => Center(
                                child: Image.network(item,
                                    fit: BoxFit.cover, width: 1000)),
                          )
                          .toList(),
                    );
                  }
                  return const Center(
/*
                  child: SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation(Colors.blue),
                    ),
                  ),
*/
                      );
                }
                // By default, show a loading spinner.
                ),
            FutureBuilder<CategoryModel>(
              future: CategoryList(),
              builder: (BuildContext context, snapshot) {
                //_getId();
                if (snapshot.hasData) {
                  List<Result> data = snapshot.data!.result;

                  print((snapshot.data));

                  return GridView.builder(
                    itemCount: data.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 0,
                      mainAxisSpacing: 0,
                    ),
                    //padding: EdgeInsets.all(1),
                    itemBuilder: (ctx, index) {
                      return Padding(
                        padding: EdgeInsets.all(0.0),
                        child: new GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => SubCategoryPage(
                                  data[index].id,
                                ),
                              ),
                            );
                          },
                          child: new Container(
                            margin: const EdgeInsets.all(0),
                            padding: const EdgeInsets.all(0),
                            decoration: BoxDecoration(
                              border: Border.all(
                                width: 0.5,
                                color: Colors.grey,
                              ),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                SizedBox(
                                  height: 25,
                                ),
                                Image.network(
                                  snapshot.data!.imgPath + data[index].coverPic,
                                  height: 55,
                                  width: 55,
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                Expanded(
                                  child: Text(
                                    data[index].name,
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 15,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  );
                } else {
                  return const Center(
                    child: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation(Colors.blue),
                      ),
                    ),
                  );
                }
              },
            ),
          ]),
        ),
        snackBar: const SnackBar(
          content: Text('Tap back again to leave'),
        ),
      ),
    );
  }

/*
  Future<bool> onWillPop() {
    DateTime now = DateTime.now();
    if (currentBackPressTime == null ||
        now.difference(currentBackPressTime) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      return Future.value(false);
    }
    return Future.value(true);
  }
*/

  void getUserLocation() async {
    //call this async method from whereever you need
    LocationData? myLocation;
    String error;
    Location location = new Location();
    try {
      myLocation = await location.getLocation();
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'please grant permission';
        print(error);
      }
      if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
        error = 'permission denied- please enable it from app settings';
        print(error);
      }
      myLocation = null;
    }
    currentLocation = myLocation;
    final coordinates =
        new Coordinates(myLocation?.latitude, myLocation?.longitude);
    var addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    var first = addresses.first;
    String adminArea = first.adminArea;
    String locality = first.locality;
    String subLocality = first.subLocality;
    String subAdminArea = first.subAdminArea;
    addressLine = first.addressLine;
    String featureName = first.featureName;
    String thoroughfare = first.thoroughfare;
    String subThoroughfare = first.subThoroughfare;

    /*   print(' ${first.locality}, ${first.adminArea},${first.subLocality}, ${first.subAdminArea},${first.addressLine}, ${first.featureName},${first.thoroughfare}, ${first.subThoroughfare}');
    return first;*/
  }

  gettoken() async {
    //token = await FirebaseMessaging.instance.getToken();
    FirebaseMessaging.instance.getToken().then((token) {
      token = token.toString();
      // do whatever you want with the token here
    });
  }

  getdeviceid() async {
    final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();

    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
      androidDeviceInfo = androidInfo.id!; //UUID for Android

    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
      androidDeviceInfo = iosInfo.identifierForVendor; //UUID for Android
    }
  }

  void Setsharedpreferencevalue() async {
    setState(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      await prefs.setString('addressLine', addressLine);
      prefs.setString('deviceID', androidDeviceInfo);
      await prefs.setString("token", token!);
    });
  }

  void Getsharedpreferencevalue() async {
    setState(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();

      androidDeviceInfo = prefs.getString('deviceID');
      getaddressLine = prefs.getString('addressLine');
      token = prefs.getString('token');
      user_id = prefs.getString('user_id');
      phone = prefs.getString('phone');
      name = prefs.getString('name');

      print("info : ${androidDeviceInfo}");
    });
  }
}

SearchModulePage:-

    import 'dart:convert';
import 'package:flutter_mapbox_autocomplete/flutter_mapbox_autocomplete.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:newbharatbiz/Screens/SubCategoryPage.dart';
import 'package:shared_preferences/shared_preferences.dart';


var addressLine;

TextEditingController Locality = TextEditingController();


class SearchModulePage extends StatefulWidget {
  String id;
  String catId;
  String serviceName;
  String image;
  String imgPath;

  SearchModulePage(
      this.id, this.catId, this.serviceName, this.image, this.imgPath);

  @override
  _YourWidgetState createState() =>
      _YourWidgetState(id, catId, serviceName, image, imgPath);
}

class _YourWidgetState extends State<SearchModulePage> {
  String id;
  String catId;
  String serviceName;
  String image;
  String imgPath;

  _YourWidgetState(
      this.id, this.catId, this.serviceName, this.image, this.imgPath);

  @override
  void initState() {
    super.initState();
    getshareddprefernces();
  }


  @override
  Widget build(BuildContext context) {
    // getsharedprefernces();
    return WillPopScope(
      onWillPop: () async => true,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text(serviceName),
          leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () {
                Navigator.pop(
                    context, true); // It worked for me instead of above line
/*                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                      builder: (context) => SubCategoryPage(
                            catId,
                          )),
                );*/
              }),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              const SizedBox(height: 30),

              Image.network(
                imgPath + image,
                width: 60.0,
                height: 60.0,
              ),
              // Padding(padding: EdgeInsets.only(top: 15.0)),
              const SizedBox(height: 20),

              Text(serviceName,
                  style: TextStyle(color: Colors.black, fontSize: 15)),
              //  Padding(padding: EdgeInsets.only(top: 30.0)),
              const SizedBox(height: 10),
              Padding(
                padding: const EdgeInsets.all(20.0),
                child: TextFormField(
                  controller: Locality,
                  readOnly: true,
                 // initialValue: addressLine,
                  // set it to a string by default

                  decoration: InputDecoration(
                    hintText: "Search your locality",
                    hintStyle: TextStyle(
                      color: Color(0xff323131),
                    ),
                    suffixIcon: Icon(
                      Icons.location_on_rounded,
                      color: Color(0xFF00796B),
                    ),
                  ),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => MapBoxAutoCompleteWidget(
                          apiKey:
                              "pk.eyJ1IjoibmV3YmhhcmF0Yml6IiwiYSI6ImNrbWJqb3B5ZzIyZnUyd254M2JndmhnNnQifQ.Km7hMjBHD_kwHWL7x7Y-Jg",
                          hint: "Search your locality",
                          onSelect: (place) {
                            // TODO : Process the result gotten
                            Locality.text = place.placeName!;
                          },
                          limit: 10,
                        ),
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  //  FocusScope.of(context).requestFocus(FocusNode());
                  addressLine = Locality.text;

                  if (addressLine == "") {
                    Fluttertoast.showToast(
                        msg: "Enter your locality",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.CENTER,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.black54,
                        textColor: Colors.white,
                        fontSize: 16.0);
                    /*  var snackBar = SnackBar(content: Text('Enter your locality'));
                            ScaffoldMessenger.of(context).showSnackBar(snackBar);*/
                  } else {
                    //  String locality = Locality.text;

                  }
                },
                child: Text("Submit"),
                style: ElevatedButton.styleFrom(
                    primary: Color(0xFF00796B),
                    padding:
                        EdgeInsets.symmetric(horizontal: 100, vertical: 10),
                    textStyle:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
              ),
            ],
          ),
        ),
      ),
    );
  }
  void getshareddprefernces() async {
    setState(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      addressLine = await prefs.getString('addressLine');
      Locality.text = addressLine.toString();
      Fluttertoast.showToast(
          msg: addressLine,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black54,
          textColor: Colors.white,
          fontSize: 16.0);
    });
  }

}


Solution 1:[1]

You have to wait till all asynchronous process is over, then after that when all values (here address, deviceId and token) are set to variables, then you can save or set values to shared preferences.

Here is the sample code for you:

  @override
  void initState() {
    super.initState();
    initializeVariables().then((boolValue){
        Setsharedpreferencevalue();
    });
 // ..
  }

  Future<Boolean> initializeVariables() async {
    await getUserLocation();
    await getdeviceid();
    await gettoken();
    return true;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DeePanShu