Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

api - export data outside of function dart

Hello im pretty new to flutter and dart and i wanted to do something with my database

i have this code to get a post

makePostRequest(int id, String type, String api) async {
  final uri = 'url';
  final headers = {'Content-Type': 'application/x-www-form-urlencoded'};
  String body = "id=" + id.toString() + "&api=" + api + "&type=" + type;
  final encoding = Encoding.getByName('utf-8');

  Response response = await post(
    uri,
    headers: headers,
    body: body,
    encoding: encoding,
  );

  int statusCode = response.statusCode;
  String responseBody = response.body;
  print(statusCode);
  //print(responseBody);
  return responseBody;
}

and in initState i want to get it out to put it inside of my widget but i dont know how to do thats

Map<String, dynamic> reponseJson;
  @override
  void initState() {
    makePostRequest(
            widget.id, 'get-one', 'api_key')
        .then((value) {
      //print(value.toString());
      String jsonTxt = value;
      Map<String, dynamic> valueDBB = jsonDecode(jsonTxt);
      //print(ValueDBB['name']);
      reponseJson = valueDBB;
      print(reponseJson);
      return valueDBB;
      //i get the value here
    });
    //but not here
    super.initState();
  }

please help i locked on it more of 1 days

question from:https://stackoverflow.com/questions/65886550/export-data-outside-of-function-dart

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

1 Answer

0 votes
by (71.8m points)

Use FutureBuilder. This widget allows you display some 'placeholder' widget while passed Future is in progress. Then, after Future si completed, builder will give you its return data and you can do whatever you want with them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...