I have a JSON response that I intend to render in my app. However, the way the data is getting rendered is pretty unusual and nothing that I could have thought of, and this brings me to the question as to what I'm doing wrong or what I need to do to get it in the correct format. The JSON response, model and provider classes, and the widget are all below:
As you can see on the snip above, I have marked the [ symbol that gets rendered at the beginning as well as ] at the end. Also, the commas ,(that are also marked), are appearing at the end of every full stop. I was a little clueless about what was causing this but later noticed that the value of paraGraph is exactly getting rendered in the way it is in the list. Like the [] at the beginning and the end along with the , which is the basic symbol to separate every value in a list. These shouldn't be appearing.
The JSON response:
[
{
"_id": "61ed10bc5d383244bbb89d45",
"paraGraph": [
"Homeopathy, the longest established alternative medicine to come out of Europe, was created in 1796 by Samuel Hahnemann.",
"Hahnemann rejected the mainstream medicine of the late 18th century as irrational and inadvisable because it was largely ineffective and often harmful.",
"He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.",
"The term homeopathy was coined by Hahnemann and first appeared in print in 1807.",
"He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.",
"Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.",
"These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.",
"He published a collection of provings in 1805, and a second collection of 65 preparations appeared in his book, Materia Medica Pura (1810).",
"As Hahnemann believed that large doses of drugs that caused similar symptoms would only aggravate illness, he advocated for extreme dilutions.",
"A technique was devised for making dilutions that Hahnemann claimed would preserve the substance's therapeutic properties while removing its harmful effects.",
"Hahnemann believed that this process enhanced the spirit-like medicinal powers of the crude substances.",
"He gathered and published an overview of his new medical system in his book, The Organon of the Healing Art (1810), with a sixth edition published in 1921 that homeopaths still use today.",
"Homeopathy achieved its greatest popularity in the 19th century.",
"It was introduced to the United States in 1825 with the first homeopathic school opening in 1835.",
"Throughout the 19th century, dozens of homeopathic institutions appeared in Europe and the United States.",
"During this period, homeopathy was able to appear relatively successful, as other forms of treatment could be harmful and ineffective.",
"By the end of the century the practice began to wane, with the last exclusively homeopathic medical school in the US closing in 1920.",
"In the 1970s, homeopathy made a significant comeback, with sales of some homeopathic products increasing tenfold.",
"The trend corresponded with the rise of the New Age movement, and may be in part due to an irrational preference for natural products, and the longer consultation times homeopathic practitioners provided."
]
}
]
model class
import 'dart:convert';
List<History> userFromJson(String str) => List<History>.from(json.decode(str).map((x) => History.fromJson(x)));
String userToJson(List<History> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class History {
String? id;
List<String>? paraGraph;
History({this.id, this.paraGraph});
History.fromJson(Map<String, dynamic> json) {
this.id = json["_id"];
this.paraGraph = json["paraGraph"]==null ? null : List<String>.from(json["paraGraph"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["_id"] = this.id;
if(this.paraGraph != null)
data["paraGraph"] = this.paraGraph;
return data;
}
}
provider class(The class that makes the API call)
class HistoryProvider with ChangeNotifier {
List<dynamic> _data = [];
List<dynamic> get data {
return[..._data];
}
Future<void> getData() async {
final url = Uri.http('192.168.0.8:3008', '/history');
final response = await http.get(url);
List<History> history = userFromJson(response.body);
final extractedData = json.decode(response.body);
print('response $extractedData');
_data = history;
print(_data);
}
}
The widget:
class HomeScreen extends StatefulWidget {
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeScreen> {
var _loading = true;
@override
void didChangeDependencies() {
Provider.of<HistoryProvider>(context, listen: false).getData().then((_) {
setState(() {
_loading = false;
});
});
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
var history = Provider.of<HistoryProvider>(context).data;
// TODO: implement build
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: const Text('Doctor App'),
),
body: _loading ? Center(
child: CircularProgressIndicator(),
) : ListView.builder( //This is where I render the JSON response(paraGraph)
itemBuilder: (context, index) => Text(
history[index].paraGraph.toString()
),
itemCount: history.length
)
);
}
}
This is what the first print statement outputs:
response [
{_id: 61ed10bc5d383244bbb89d45, paraGraph: [Homeopathy, the longest established alternative medicine to come out of Europe,
was created in 1796 by Samuel Hahnemann., Hahnemann rejected the mainstream medicine of the late 18th century as irrational and
inadvisable because it was largely ineffective and often harmful.,
He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.,
The term homeopathy was coined by Hahnemann and first appeared in print in 1807.,
He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.,
Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.,
These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.,
He published a collection of provings in 1805, and a second col
This is the output from the second print:
I/flutter (12016): [Instance of 'History']
CodePudding user response:
This is a weird json. But you can format it like this.
class _HomeScreenState extends State<HomeScreen> {
List<String> paraGraph = [
"Homeopathy, the longest established alternative medicine to come out of Europe, was created in 1796 by Samuel Hahnemann.",
"Hahnemann rejected the mainstream medicine of the late 18th century as irrational and inadvisable because it was largely ineffective and often harmful.",
"He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.",
"The term homeopathy was coined by Hahnemann and first appeared in print in 1807.",
"He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.",
"Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.",
"These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.",
"He published a collection of provings in 1805, and a second collection of 65 preparations appeared in his book, Materia Medica Pura (1810).",
"As Hahnemann believed that large doses of drugs that caused similar symptoms would only aggravate illness, he advocated for extreme dilutions.",
"A technique was devised for making dilutions that Hahnemann claimed would preserve the substance's therapeutic properties while removing its harmful effects.",
"Hahnemann believed that this process enhanced the spirit-like medicinal powers of the crude substances.",
"He gathered and published an overview of his new medical system in his book, The Organon of the Healing Art (1810), with a sixth edition published in 1921 that homeopaths still use today.",
"Homeopathy achieved its greatest popularity in the 19th century.",
"It was introduced to the United States in 1825 with the first homeopathic school opening in 1835.",
"Throughout the 19th century, dozens of homeopathic institutions appeared in Europe and the United States.",
"During this period, homeopathy was able to appear relatively successful, as other forms of treatment could be harmful and ineffective.",
"By the end of the century the practice began to wane, with the last exclusively homeopathic medical school in the US closing in 1920.",
"In the 1970s, homeopathy made a significant comeback, with sales of some homeopathic products increasing tenfold.",
"The trend corresponded with the rise of the New Age movement, and may be in part due to an irrational preference for natural products, and the longer consultation times homeopathic practitioners provided."
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: const Text('Doctor App'),
),
body: SingleChildScrollView(
child: Column(
children: [for (String i in paraGraph) Text(i)],
),
),
);
}
}
CodePudding user response:
You only need to update the way you are serializing the paragraph property:
History.fromJson(Map<String, dynamic> json) {
this.id = json["_id"];
this.paraGraph = (json['paraGraph'] as List).map((e) => e as String).toList() ?? []; //<-- update this
}

