How to split a string from rest api?

Viewed 65

I have a list of string from rest API like this

response

I try to split it using this code e.review!.map((e) => e).join(" "),

and I get this result current result

but my expectation result is

expected result

How do I do that? Thank you

model.dart

  RatingDataModel({
    this.rating,
    this.review,
  });

  int? rating;
  List<String>? review;

  factory RatingDataModel.fromJson(Map<String, dynamic> json) =>
      RatingDataModel(
        rating: json["rating"],
        //separate the review by space

        review: json["review"] != null
            ? List<String>.from(json["review"].map((x) => x))
            : null,
      );

  Map<String, dynamic> toJson() => {
        "rating": rating,
        "review": List<dynamic>.from(
          review!.map(
            (x) => x,
          ),
        ),
      };
}
4 Answers

You need to loop through since it is a list.

enter image description here

Here is the full working code as a Tags widget

import 'package:flutter/material.dart';

class Tags extends StatelessWidget {
  const Tags({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Tag Demo'),
      ),
      body: Wrap(
        spacing: 8.0, // gap between adjacent chips
        runSpacing: 4.0, // gap between lines
        children: getChips(),
      ),
    );
  }

  List<Chip> getChips() {
    List<String> review = [
      "Tidak ramah",
      "Tidak sesuai dengan foto",
      "Tidak sesuai deskripsi",
      "Tailor terlambat",
      "Lokasi tempt tidak sesuai alamat",
      "Tempat tidak ditemukan",
      "Tailor kasar",
      "Tailor melakukan kekerasa / pelecehan",
      "Tempat tidak nyaman"
    ];

    List<Chip> tags = [];
    review.asMap().forEach((index, singleReview) {
      tags.add(
        Chip(
          avatar: CircleAvatar(
            child: Text((index + 1).toString()),
          ),
          label: Text(singleReview),
        ),
      );
    });

    return tags;
  }
}

Use ListView.builder instead of ListView.

 @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: e.review!.length,
        itemBuilder: (context, index) {
          return ChoiceChip(
                   ...
            label: Text(e.review![index]));
        });
  }

Try the following code:

ListView.builder(
  itemCount: e.review!.length,
  itemBuilder: (context, index) {
    final review = e.review![index]; // Use this

    return ......;
  },
);

You don't need to split since it's a list of strings,just iterate through with a 'listview'

 e.map((e) => e).toList()
Related