Flutter how can i show data of api response

0

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

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"]); 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.

Showing error when I use the answer enter image description here

flutter
dart
asked on Stack Overflow Aug 21, 2020 by rameez khan • edited Aug 21, 2020 by rameez khan

1 Answer

0

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

 
answered on Stack Overflow Aug 21, 2020 by Johny Saini • edited Aug 21, 2020 by Johny Saini

User contributions licensed under CC BY-SA 3.0