【问题标题】:Flutter how can i show data of api responseFlutter如何显示api响应的数据
【发布时间】:2020-12-10 23:21:29
【问题描述】:

我做了一个简单的屏幕显示列表的静态数据,但现在我尝试在列表中显示 API 响应但不知道如何显示它

这是我的代码

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

您可以在代码中看到我正在显示 _events 的静态数据列表我已经从 api 调用数据,它工作得非常好并打印数据您可以在代码print(eventData["Data"]); 中看到这一行但问题是我是否喜欢这个final List _events = eventData["Data"]显示api数据不是静态数据它显示错误我认为api在数据显示之前调用。

当我使用答案时显示错误

【问题讨论】:

  • 尝试删除final List _events变量的final,然后使用setState((){_events = eventData["Data"]; });
  • @Vitor 我尝试但显示错误错误:没有为类“_EventsState”定义吸气剂“_events”。似乎数据调用晚了,我之前调用了 _events

标签: flutter dart


【解决方案1】:

你可以用这个。

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

 

【讨论】:

  • 试试你的答案,但不知道它在 setState 上显示了一些错误,我添加了有问题的错误截图
  • 再次检查代码,让我知道。更改 setState 函数是我的错误
  • 尝试显示此错误 A RenderViewport 需要一个 RenderSliv​​er 类型的子级,但收到了一个 RenderErrorBox 类型的子级。
猜你喜欢
  • 1970-01-01
  • 2021-10-14
  • 2021-06-20
  • 2021-10-16
  • 1970-01-01
  • 2021-06-17
  • 2021-03-30
  • 1970-01-01
  • 2019-01-01
相关资源
最近更新 更多