wahyu
wahyu

Reputation: 2405

How to read more than 1 data using shared preferences in Flutter

I am trying to write and read data using shared preferences, but I didn't know how to read for more than one data.. The route is like this... I have 3 screens (Login, Home, and Profile screen) inside Home and Profile Screen consist of bottom tab navigator... so after I pass Login Screen, I want to save username and id to pass it inside Home and Profile Screen... so far I have saved username and id inside Login Screen and I just didn't get the idea how to read both of them.. here is the code

class _BottomTab extends State<BottomTab> {
  @override
  Widget build(BuildContext context) {
    return FutureProvider<String>(
      create: (context) async {
        final prefs = await SharedPreferences.getInstance();
        return prefs.getString("username");
      },

      child: ...,
      );
    }
  }
}

here is when calling username but I didn't know how the way to call id

Widget build() {
  final username = Provider.of<String>(context).toString();

  if (username == null) {
    return "Loading...";
  }
  return Text("Hi $username");
}

I have tried to make a new function and define that function inside initState()... but the problem is the data always re-build whenever I click bottomTab... that's why I didn't use this method (declare function inside initState)

Upvotes: 0

Views: 217

Answers (1)

Taur
Taur

Reputation: 564

do like this

class _BottomTab extends State<BottomTab> {
  @override
  Widget build(BuildContext context) {
    return FutureProvider<String/* or 'Map' if you can*/>(
      create: (context) async {
        final prefs = await SharedPreferences.getInstance();
        final username = prefs.getString("username");
        final id = prefs.getId("id");
        final userMap = {"username":username, "id":id};
        // return userMap /* if return type is Map */
        return json.encode(userMap); /* if return type is String */
      },

      child: ...,
      );
    }
  }
}

now call

Widget build() {
  final userInfo = Provider.of<String>(context).toString();
  final userMap = json.encode(userStr);
  final username = userMap["username"]; 
  if (username == null) {
    return "Loading...";
  }
  return Text("Hi $username");
}

!!! this code have not been tested

Upvotes: 1

Related Questions