0

Can someone help me to fix this problem. i can't fetch data from json using flutter http request because it got this Unhandled Exception: type 'List' is not a subtype of type 'String' and want to load more data when scroll to bottom of screen. Can somebody help me please...

postData.dart file

class PostData extends StatefulWidget {
  const PostData({Key key}) : super(key: key);

  @override
  _PostDataState createState() => _PostDataState();
}

class _PostDataState extends State<PostData> {
  List<String> getData = List();
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    fetchFive();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        fetchFive();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Load Page"),
          toolbarHeight: 65,
          backgroundColor: Colors.blueAccent[700],
        ),
        body: ListView.builder(
            controller: _scrollController,
            itemCount: getData.length,
            itemBuilder: (context, index) {
              return Card(
                child: GestureDetector(
                  child: ListTile(
                    title: Text(getData[index]),
                  ),
                ),
              );
            }));
  }

  fetch() async {
    final response =
        await http.get('https://my-json-server.typicode.com/typicode/demo/posts');

    if (response.statusCode == 200) {
      setState(() {
        getData.add(json.decode(response.body));
      });
    } else {
      throw Exception('Failed to load data');
    }
  }

  fetchFive() {
    for (int i = 0; i < 5; i++) {
      fetch();
    }
  }
}

getData.dart file model json

class Users {
  final int no;
  final String nosiri;
  final String lokasi;
  final String status;
  final String pemilik;
  final String thumbnailurl;

  Users(
      {this.no,
      this.nosiri,
      this.lokasi,
      this.status,
      this.pemilik,
      this.thumbnailurl});

  factory Users.fromJson(Map<String, dynamic> json) {
    return Users(
      no: json['no'],
      nosiri: json['no_siri'],
      lokasi: json['lokasi'],
      status: json['status'],
      pemilik: json['pemilik'],
      thumbnailurl: json['thumbnailurl'],
    );
  }
}
0

3 Answers 3

1

try

List<Users> getData = [];

change

getData.add(json.decode(response.body));

to

getData.addAll(List<Users>.from(json.decode(response.body).map((x) => Users.fromJson(x))));
Sign up to request clarification or add additional context in comments.

7 Comments

but for load data when scroll is not working. Data become duplicate so many.. can't you tell why?
May be you are using add not addAll, and you fetch 5 time? Not sure that
i'm using addAll and yeah i just want to fetch only 5 data but it appear show all data and when i scroll down it fetch the duplicate data...Btw thanks
I see, try setState after you fetch data and I highly recommend you use flutter_pagewise in your case
So i need to change listview to pagewiselistview right?
|
0

As a response you are getting List<Map> and you're trying to store that in List<String>.Please change it to List<dynamic> or List<Map>

   [
      {
        "id": 1,
        "title": "Post 1"
      },
      {
        "id": 2,
        "title": "Post 2"
      },
      {
        "id": 3,
        "title": "Post 3"
      }
    ]
 

Comments

0

By checking your code your responce is List<Map> form and you declare List<String>. So you need to remove your String format from List.

List getData = List();

Then you need to convert your data into List like the below and then add it one by one in getData. And then you can add your data onto the Text.

ListTile(
  title: Text(getData[index]['title'].toString()),
),

And your fetch() method be like

  fetch() async {
    final response = await http
        .get('https://my-json-server.typicode.com/typicode/demo/posts');

    if (response.statusCode == 200) {
      setState(() {
        final data = json.decode(response.body);
        for (var i in data) {
          getData.add(i);
        }
      });
    } else {
      throw Exception('Failed to load data');
    }
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.