How to display response from the server in Flutter app screen?

604

You should try below code:

Your API Call Function

  Future<Album> fetchPost() async {
  String url =
      'https://jsonplaceholder.typicode.com/albums/1';
  var response = await http.get(Uri.parse(url), headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  });
  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Album.fromJson(json
        .decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

Declare your class

class Album {
   final int userId;
   final int id;
   final String title;

 Album({
   this.userId,
   this.id,
   this.title,
 });

 factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
    userId: json['userId'],
    id: json['id'],
    title: json['title'],
   );
 }
}

Declare your widget like below :

Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: FutureBuilder<Album>(
            future: fetchPost(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [ 
                ListTile(
                  leading: Icon(Icons.person_outlined),
                  title: Text(snapshot.data.title),
                ),
                ListTile(
                  leading: Icon(Icons.email),
                  title: Text(snapshot.data.userId.toString()),
                ),
                ListTile(
                  leading: Icon(Icons.phone),
                  title: Text(snapshot.data.id.toString()),
                ),
              ],
            );
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        },
      ),
    ),
  ),
Share:
604
Admin
Author by

Admin

Updated on December 31, 2022

Comments

  • Admin
    Admin 10 months

    i'm new to flutter, i'm trying to display response from the server on my screen. I get from the server Orders history and trying to display it on History screen, how can u do this?

    void getAllHistory() async {
        http
            .post(
                Uri.parse(
                    'https://myurlblahblah'),
                body: "{\"token\":\"admin_token\"}",
                headers: headers)
            .then((response) {
          print('Response status: ${response.statusCode}');
          print('Response body: ${response.body}');
        }).catchError((error) {
          print("Error: $error");
        });
      }
    }
    

    I don't have experience with request to server, so i don't know how to display it anywhere except "print"

    class HistoryScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: buildAppBar(),
          body: BodyLayout(),
        );
      }
    
      AppBar buildAppBar() {
        return AppBar(
          automaticallyImplyLeading: false,
          title: Row(
            children: [
              BackButton(),
              SizedBox(width: 15),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Orders history",
                    style: TextStyle(fontSize: 16),
                  ),
                ],
              )
            ],
          ),
        );
      }
    }
    

    PS "BodyLayout" is just a list view, do i need to past my response code here? I want to get all orders history when i switch to "History Screen" I would really appreciate code example