简体   繁体   English

Flutter 如何显示 api 响应的数据

[英]Flutter how can i show data of api response

I have made a simple screen which show the static data of list but now I try to show the API response in the list but don't know how to show it我做了一个简单的屏幕,显示列表的 static 数据,但现在我尝试在列表中显示 API 响应但不知道如何显示它

This is my code这是我的代码

 class _EventsState extends State<Events> {
  dynamic _events = [];
  dynamic isloader = false;
  @override
  initState() {
    // TODO: implement initState

    super.initState();
    doSomeAsyncStuff();
  }


  Future<void> doSomeAsyncStuff() async {

    setState((){isloader = true;});
    final storage = new FlutterSecureStorage();
    String value = await storage.read(key: 'token');
    print(value);

    String url = 'http://sublimeapi.netcodesolution.com/api/NewsAndEvents/';

    String token = value;
    final response = await http.get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });
    print('Token : ${token}');
    dynamic eventData = json.decode(response.body);
    print(eventData["Data"]); // this is the data need to show
    setState((){
      isloader = true;
      var _event = eventData["Data"];
      });
  }


  @override
  Widget build(BuildContext context) {
    double statusBarHeight = MediaQuery
        .of(context)
        .padding
        .top;
    return Expanded(
      child: Container(
        child: new CustomScrollView(
          scrollDirection: Axis.vertical,
          slivers: <Widget>[
            new SliverAppBar(
              backgroundColor: Colors.white,
              expandedHeight: statusBarHeight * 5,
              flexibleSpace: new FlexibleSpaceBar(
                title: const Text(
                  'Event Lists',
                  textAlign: TextAlign.left,
                  style: TextStyle(fontSize: 20, color: Color(0xff343A40)),
                ),
              ),
            ),
            isloader ? CircularProgressIndicator() : // user loader there
            new SliverPadding(
                padding: const EdgeInsets.symmetric(vertical: 2.0),
                sliver: new SliverFixedExtentList(
                  itemExtent: 280.0,
                  delegate: new SliverChildBuilderDelegate(
                          (builder, index) => _buildListItem(index),
                      childCount: _events.length),
                )),
          ],
        ),
      ),
    );
  }

  Widget _buildListItem(int index) {
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return GestureDetector(
      child: Center(
        child: Card(
          margin: EdgeInsets.zero,
          clipBehavior: Clip.antiAlias,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          elevation: 30,
          child: Container(
            child: Stack(
              children: <Widget>[
                Container(
                  width: width * 0.6,
                  height: height * 0.17,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        'assets/images/61.jpg',
                      ),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: height * 0.17),
                  child: Container(
                    height: height * 0.15,
                    color: Colors.white,
                    width: MediaQuery.of(context).size.width * 0.6,
                    child: Padding(
                      padding: const EdgeInsets.only(
                          top: 30, bottom: 7, left: 15, right: 15),
                      child: Row(
                        children: <Widget>[
                          Flexible(
                            child: Text(
                              _events[index]['Description'],
                              style: TextStyle(
                                  color: Color(0xff343A40),
                                  fontFamily: 'OpenSans',
                                  fontWeight: FontWeight.bold,
                                  fontSize: 15),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Positioned.fill(
                  child: Align(
                      alignment: Alignment.centerLeft,
                      child: Container(
                        margin: EdgeInsets.only(left: width * 0.02),
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(12)),
                          child: Container(
                            height: height * 0.08,
                            width: width * 0.4,
                            color: Color(0xff343A40),
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    _events[index]['CreatedOn']
                                        .substring(0, 10),
                                    style: TextStyle(
                                        fontSize: 20,
                                        color: Color(0xffFFFFFF),
                                        fontFamily: 'OpenSans',
                                        fontWeight: FontWeight.bold),
                                  ),
                                ]),
                          ),
                        ),
                      )),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

You can see in code i am showing static data list of _events I have call the data from api which is working absolutely fine and printing the data you can see this line in code print(eventData["Data"]);您可以在代码中看到我正在显示 static 数据列表 _events 我已经从 api 调用数据,它工作得非常好,打印数据你可以在代码print(eventData["Data"]); But issue is if i do it like this final List _events = eventData["Data"] to show the api data not static data its showing error I think api is calling before the data showing.但问题是,如果我像这个final List _events = eventData["Data"]那样显示 api 数据而不是 static 数据,它的显示错误我认为 Z8A5DA52ED126447D359E70C05721A8 之前显示数据。

Showing error when I use the answer使用答案时显示错误在此处输入图像描述

you can use this.你可以用这个。

dynamic _events = [];
dynamic isloader = false;


Future<void> doSomeAsyncStuff() async {

setState((){isloader = true});
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'token');
print(value);

String url = 'http://sublimeapi.netcodesolution.com/api/NewsAndEvents/';

String token = value;
final response = await http.get(url, headers: {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer $token',
});
print('Token : ${token}');
dynamic eventData = json.decode(response.body);
 print(eventData["Data"]); // this is the data need to show
 setState((){isloader = true,
  _event = eventData["Data"];
});
}


 @override
   Widget build(BuildContext context) {
double statusBarHeight = MediaQuery.of(context).padding.top;
return Expanded(
  child: Container(
    child: new CustomScrollView(
      scrollDirection: Axis.vertical,
      slivers: <Widget>[
        new SliverAppBar(
          backgroundColor: Colors.white,
          expandedHeight: statusBarHeight * 5,
          flexibleSpace: new FlexibleSpaceBar(
            title: const Text(
              'Event Lists',
              textAlign: TextAlign.left,
              style: TextStyle(fontSize: 20, color: Color(0xff343A40)),
            ),
          ),
        ),
    isLoader?  CircularProgressIndicator()   :         // user loader there
            new SliverPadding(
               padding: const EdgeInsets.symmetric(vertical: 2.0),
            sliver: new SliverFixedExtentList(
              itemExtent: 280.0,
              delegate: new SliverChildBuilderDelegate(
                  (builder, index) => _buildListItem(index),
                  childCount: _events.length),
            )),
        ],
      ),
    ),
  );
  }

 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在 Flutter 的 api 响应数据上方向 listViewbuilder 显示保存的收藏夹项目? - How i can show a saved fav items to listViewbuilder above the api response data in Flutter? 我如何在 flutter 中显示来自 get api 的所有数据 - how i can show all data from get api in flutter Flutter:如何从响应 API 显示数据 HTML 结果? - Flutter : How to show data HTML result from response API? 如何以及在何处存储 api 响应数据,以便在 flutter 中需要时可以使用我? - How and where to store api response data so that i can be used whenever needed in flutter? Flutter 如何检查 api 响应是否错误 - Flutter how can i check api response is error or not 如何从 flutter 中的 API 响应中获取标头 - How can I get the headers from the API response in flutter 如何从 flutter 中的 JSON 响应中获取特定数据? - How can I reach a specific data from JSON response in flutter? 如何将卡片轮播的硬编码数据更改为来自 api 响应的动态数据 -Flutter - How can change my hardcoded data of a card carousel to dynamic data from api response -Flutter 如何在Flutter中将嵌套的JSON API响应显示为网格视图? - How to show a nested JSON api response as a grid view in flutter? 如何显示从 flutter 中的 API 响应中获取的 pdf? - how to show a pdf fetched from an API response in flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM