user13111806
user13111806

Reputation:

GET Request in Flutter

i start yesteraday with flutter and today i have a problem with GET request.

It looks like I can't get data from my URL, I have no idea why when I paste it into my browser everything works

I tried to get one single User object, but nothing work for me :(

my code,

User.dart

class User{
  int id;
  String firstName;
  String lastName;
  String email;

  User(this.id, this.firstName, this.lastName, this.email);

  User.fromJson(Map<String,dynamic> json){
    id = json['id'];
    firstName = json['firstName'];
    lastName = json['lastName'];
    email = json['email'];
  }
}

my GET function:

Future<User> getCurrentUser() async {
    String url = 'http://10.0.2.2:80/user/current';
    final response =
        await http.get(url, headers: {"Accept": "application/json"});


    if (response.statusCode == 200) {
      return User.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  } 

my widget:

class UserPageState extends State<UserPage>{
  Future<List<dynamic>> _user;

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) => Container(
          child: FutureBuilder(
            future: getCurrentUser(),
            builder: (BuildContext context, AsyncSnapshot snapshot){
              if(snapshot.hasData ){
                return Container(
                  child: Center(child: Text(snapshot.data['firstName']),),
                );
              }else {
                return Text('NOT LOAD');
              }
            },
          ),
        ),
      ),
    );
  }
}

when i paste my url into browser it show me:

{
createdAt: 1584905291338,
updatedAt: 1584905291338,
id: 3,
firstName: "name",
lastName: "surname",
email: "[email protected]",
admin: false
}

I don't have any more idea what i can do it, PLEASE HELP ME :(

Upvotes: 0

Views: 1249

Answers (2)

Federick Jonathan
Federick Jonathan

Reputation: 2864

class User{
  int id;
  String firstName;
  String lastName;
  String email;

  // For me, it's better to use named parameter to make it easier to read
  User({this.id, this.firstName, this.lastName, this.email});

  // this doesn't return User object
  User.fromJson(Map<String,dynamic> json){
    id = json['id'];
    firstName = json['firstName'];
    lastName = json['lastName'];
    email = json['email'];
  }

  factory User.fromJson(Map<String,dynamic> json){
    return User(
      id: json['id'],
      firstName : json['firstName '],
      lastName : json['lastName '],
      email : json['email '],
    );
  }
}

Upvotes: 0

Manuel
Manuel

Reputation: 382

First of all, I would recommend, that you fetch your data from the initState in the StatefulWidget, and not within the build method. Otherwise, on every rebuild, the data is fetched newly via http.get. In your FutureBuilder widget you use then future: _user

class UserPage extends StatefulWidget {
  UserPage({Key key}) : super(key: key);

  @override
  UserPageState createState() => UserPageState();
}

class UserPageState extends State<UserPage>{
  Future<User> _user;

  @override
  void initState() {
    super.initState();
    _user = getCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    ... // your code here

To answer your question and why the user class and its data isn't filled. You have to return the data from the function User.fromJson(...), otherwise it gets lost

class User{
  int id;
  String firstName;
  String lastName;
  String email;

  User(this.id, this.firstName, this.lastName, this.email);

  factory User.fromJson(Map<String,dynamic> json){
    return User(
      json['id'],
      json['firstName'],
      json['lastName'],
      json['email'],
    );
  }
}

Upvotes: 1

Related Questions