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
296 views
in Technique[技术] by (71.8m points)

flutter - Adding data from API as new entry to ListView

I'm getting data from an API productObject and display them in the build widget as follows:

  Widget build(BuildContext context) {
    if (_sharedText != null) {
      return Scaffold(
        appBar: AppBar(
          title: Text("Thank you"),
          backgroundColor: Colors.blueGrey.shade900,
        ),
        backgroundColor: Colors.blueGrey.shade400,
        body: Center(
          child: FutureBuilder<ProductInformationModel>(
              future: productObject(),
              builder: (BuildContext context, AsyncSnapshot<ProductInformationModel> snapshot) {
                if (snapshot.hasData) {
                  return
                    ListView.builder(
                        itemCount: 2, //just a number to display at least the result
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            //height: 75,
                            child: Center(
                              child: midView(snapshot),
                            ),
                          );
                        }
                    );
                } else if (snapshot.hasError) {
                  return Container(child:
                  Text("${snapshot.error}"));
                } else {
                  return Container(
                    child: Center(child: CircularProgressIndicator(),),
                  );

This is ok so far, but what I want is that every time the API is called again the present displayed API output will remain displayed on the screen and the new called API output will be visible below the present output. So each API call should be one list entry without deleting the former data from the API.

An example of the productObject:

  Future<ProductInformationModel> productObject({String urlName}) async {
    try {
      return new Network().getProductInformation(urlName: _sharedText);

    } catch (e) {
      print("Image not found: $e");
    }
  }

And I call the API like this:

if (response.statusCode == 200) {
      model (ProductInformationModel from product_information_model.dart
      print("image data: ${response.body}");
      return ProductInformationModel.fromJson(json.decode(response.body));
    }else {
      throw Exception("Error getting image info");
    }
Widget midView(AsyncSnapshot<ProductInformationModel> snapshot) {
  var productName = snapshot.data.objects[0].title;
  var productImage = snapshot.data.objects[0].images[0].url;
  var api_type = snapshot.data.request.api;
  var pageUrl_type = snapshot.data.request.pageUrl;
  Container midView = Container(
    child: Padding(
      padding: const EdgeInsets.all(14.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[Text("$productName, $productImage",
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 18,
          color: Colors.black87
        ),),

I think I need the setState() but where do I set it? Do I need to create an empty list before?

Thanks a lot, I'm new to flutter and struggle with this.

question from:https://stackoverflow.com/questions/65845445/adding-data-from-api-as-new-entry-to-listview

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

1 Answer

0 votes
by (71.8m points)

There are some issues that I can see, but I can't offer you a complete solution without seeing the rest of the code (midView Widget). You have your ListView.builder with a fixed itemCount of 2 but then you are passing the whole snapshot to the midView Widget. I would actually have expected that the snapshot's data was a list, and you would cycle through the list using the index provided by the builder. That would also mean that you would set the itemCount not as a fixed value but as the length of the list coming from your snapshot. The following code assumes that your snapshot is a List:

ListView.builder(
  itemCount: snapshot.data['objects'].length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      child: Center(
        child: midView(snapshot.data['objects'][index]),
      ),
    );
  }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...