Home > OS >  How can I display a logged in user details in flutter
How can I display a logged in user details in flutter

Time:01-23

I have used get method to retrieve user details and have got 200 status as well. I am having confusion how to show the details in UI. In my homepage I have a floating action button which leads to the profile page. Any help would be much appreciated Thank you.

Future getProfile() async {
    String? token = await getToken();
    final response = await http.get(Uri.parse('$API_URL/user'), headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    });

    print(response.statusCode);
    if (response.statusCode == 200) {
      if (response.body != "") {
        var results = json.decode(response.body);

        var resultData = results['data']['name'];
       
        print(resultData);
      }
    }
  }

CodePudding user response:

you can use a FutureBuilder like this:

FutureBuilder<dynamic>(
    future: getProfile,
    builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
       switch (snapshot.connectionState) {
         case ConnectionState.waiting: return Text('Loading....');
         default:
           if (snapshot.hasError)
              return Text('Error: ${snapshot.error}');
           else
              return Text('Result: ${snapshot.data}');
        }
      },
    );

...

Future getProfile() async {
    String? token = await getToken();

    final response = await http.get(Uri.parse('$API_URL/user'), headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    });

    dynamic resultData; 

    if (response.statusCode == 200) {
      if (response.body != "") {
        var results = json.decode(response.body);

       resultData = results['data']['name'];
       
        print(resultData);
      }
    }

    return resultData;
  }

CodePudding user response:

When you are working with network data (i.e. API responses), the best practice states that you should convert the received data into Dart objects. You will then be able to easily access your data.

Quick and easy approach (not recommended)

For a quick and dirty approach, you could do the following: 1- create a model for your user. Create new file and name it user_model.dart

class User{
  String id;
  String name;
  // Add whatever other properties you need to pull from the server here
  User({
    this.id,
    this.name,  
  });
  // This function will help you convert the deata you receive from the server
  // into an instance of User
  factory User.fromJson(Map<String, dynamic> json) => User({
    id: json['id'],
    namne: json['name']
  })
}

2- Instanciate a new user in your getProfile() function

Future<User?> getProfile() async { // you want to get a Future<User>
  String? token = await getToken();
  final response = await http.get(Uri.parse('$API_URL/user'), headers: {
     'Accept': 'application/json',
     'Authorization': 'Bearer $token'
  });

  print(response.statusCode);
  if (response.statusCode == 200) {
    if (response.body != "") {
      var result = json.decode(response.body)['data']; // select the data you need here
      final user = User.fromJson(result) // create a new User instance
      return user // return it
    }
  }
  // in case something went wrong you want to return null
  // you can always check the nullity of your instance later in your code
  return null;
}

3- In your UI, you can consume the newly created instance like so. I am assuming you are inside a build() function of any widget!

//...
@override
Widget build(BuildContext context) {
  return FutureBuilder<dynamic>(
    future: getProfile,
    builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
      if(snapshot.hasData){
        final user = snapshot;
        // now you can access your user's data as you wish
        print(user.id);
        print(user.name);
      }
    );
}
//...

Better Approach (recommended)

The above approach, although seems to work, won't be ideal for a more complex project. For that, you want to follow a road map that could look like the following:

  • Automate object serialization/deserialization using packages like freezed. This will offload you from any unwanted error injection by building toJson and fromJson methods, among others, for you ;). Check their documentation for more details.
  • Manage data streams using a state management library like bloc. You can access your state, in your case the user's profile data, from anywhere in the widget tree without having to use FutureBuilder everywhere. It will also help you keep in sync with your data. Check their well-written documentation for more details on how to use it.

I have mentioned these two libraries here because they are the ones I work with all the time and that I am familiar with. They might be others out there that do more or less the same. It's up to you to pick whichever you feel comfortable with ;)

Once you get familiar with a state management library you could architect your app as follow:

/...
-lib
  |- model #build your data instance and return object
  |- repository #call API methods and convert received data to model instance
  |- api #make HTTP calls
  |- ui #build UI elements
  |- bloc #receive events from UI and call repository functions then return datastreams to UI
  •  Tags:  
  • Related