Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
        },
      ),
    ),
  ),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...