How to parse and json to websocket data in flutter
StreamBuilder(
stream: _channel.stream,
builder: (context, snapshot) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.hashCode.bitLength,
scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index){
// final List documents = snapshot.data.hashCode.bitLength as List;
// final Map<String, dynamic> doc = snapshot.data.hashCode.bitLength as Map<String, dynamic>;
// final course = snapshot.data!.hashCode.bitLength;
return Card(
child: Container(
child: Column(
children: [
Text('Recieve'),
Text(snapshot.hasData ? '${snapshot.data}' : '')
],
),
),
);
});
},
),
i have get data and show in list inside screen but how to parse these data to websocket using json to the server
First of all you can use this package to send and get data
web_socket_channel: ^2.1.0
https://pub.dev/packages/web_socket_channel
Plus For parsing json data you can read this document
https://docs.flutter.dev/development/data-and-backend/json
Related
I'm working on a app that you can read quran and bible from it and I'm pulling quran surahs and bible books from firebase and write that data to api so that I get all of chapters at once so I have quran and bible apis for it I take care of bible part but with quran json data has array that I want to retrieve all that array and data under that array but I come of to this error while doing it what I'm doing wrong ? if you can help me I really appreciate it thank you very much
my api code:
Future getQuran(String surah) async {
var uri = Uri.https(
'ajith-holy-bible.p.rapidapi.com',
'/${surah}',
);
var response = await http.get(uri, headers: {
'X-RapidAPI-Key': 'd88d0a8158mshb8b539da6b34179p137959jsn31258093d5c2',
'X-RapidAPI-Host': 'al-quran1.p.rapidapi.com'
});
print(response.statusCode);
print(response.body);
Map<String, dynamic> map = jsonDecode(response.body);
List myData = [];
for (var item in map["verses"]) {
myData.add(item);
}
return myData;
}
this is what api looks like:
id:114
surah_name:"AL-NĀS"
surah_name_ar:"الناس"
translation:"HUMANS"
type:"meccan"
total_verses:6
description:"The surah that opens with the mention of God as the Lord of Humans and teaches one to seek refuge in Him from the whisperings of Satan and those of evil jinn and people. It takes its name from the word “people” or “mankind” (al-nās) which recurs throughout the surah. This is another surah commonly used as an invocation against evil.The surah is also known as: All People, Humankind, Mankind, People, The Men."
▶
verses:{} 6 keys
▶
1:{} 4 keys
id:1.114
content:"قُل أَعوذُ بِرَبِّ النّاسِ"
translation_eng:"Say, ‘I seek the protection of the Lord of humans,"
transliteration:"qul ʾaʿūdhu bi-rabbi n-nāsi"
▶
2:{} 4 keys
id:2.114
content:"مَلِكِ النّاسِ"
translation_eng:"Sovereign of humans,"
transliteration:"maliki n-nāsi"
this is surahs page:
stream: FirebaseFirestore.instance.collection("quran").snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
final quran = snapshot.data!.docs[index];
return Padding(
padding: const EdgeInsets.all(4.0),
child: Card(
borderOnForeground: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SurahReading(
surah: quran["chapter"],
book: quran["surah"],
)));
},
child: Text(quran["surah"]),
),
],
),
),
);
});
this surahs reading page:
child: SingleChildScrollView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
child: Column(
children: [
SingleChildScrollView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
child: FutureBuilder(
future: Api().getQuran(widget.surah),
builder: (context, snapshot) {
final quran = snapshot.data;
if (snapshot.hasData) {
return Container(
child: ListView.builder(
itemCount: quran.length,
itemBuilder: (context, index) {
return Row(
children: [
Center(
child: Text(
quran[index]["content"],
style: TextStyle(fontSize: 15),
),
),
Center(
child: Text(
quran[index]["translation_eng"],
style: TextStyle(fontSize: 15),
),
),
],
);
},
),
);
}
return Center(
child: CircularProgressIndicator(),
);
}),
),
I did try to get all surahs all ayet from api but I come up to a error and I couldn't fix it
Ok ı figured it out if anyone come up to this error change for to foreach
map["verses"].forEach((key, value) {
myData.add(value);
});
a sample of what i have in mind
var url = 'https://www.googleapis.com/books/v1/volumes?q=egg';
Future<BookResponse> getData() async {
var response = await http.get(url);
var responseBody = jsonDecode(response.body);
// print(responseBody);
return BookResponse.fromJson(responseBody);
}
-----
FutureBuilder<BookResponse>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) print(snapshot.error);
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.items.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title:
Text(snapshot.data.items[index].volumeInfo.title),
));
});
} else
return Center(child: CircularProgressIndicator());
},
)
im trying to create a method that will convert json map into a List<widgets> so i can use it to display items.
i can't find a way to display items as rows and columns.
is it possible to have multiple widgets using FutureBuilder? (one row of books and another row to show authors for example)
if so i will avoid converting it to List<widgets>
Convert JSON data to objects and:
Row(
children: entities.map((entity) => Text(entity.text)).toList();
),
It creates a list with widgets.
I am having difficulty with data get. I am very new to Flutter and although I read the articles, I could not overcome this problem. I was able to get the data individually, but I couldn't put it in a loop. The codes are below.
Future<List<Post>> getPosts() async {
var jsonData = await http.get("https://example.com/api/posts.php");
final jsonResponse = json.decode(jsonData.body);
Match postList= Post.fromJsonMap(jsonResponse);
return (jsonResponse as List)
.map((postList) => Post.fromJsonMap(postList))
.toList();
//print("post" + postList.result[1].home);
}
When I run the print method, I can print the data. However, when I send it to futurebuilder, the data is not coming.
body: FutureBuilder(
future: getPosts(),
builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
if (snapshot.hasData) {
print("test");
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index].result[index].home),
subtitle: Text(snapshot.data[index].result[index].title),
leading: CircleAvatar(
child: Text(
snapshot.data[index].result[index].id.toString()),
),
);
});
} else {
return Center(child: CircularProgressIndicator());
}
}),
Note: The codes I used as an example: https://github.com/emrealtunbilek/flutter_json_http/blob/master/lib/remote_api.dart
Try add additional if branch like this
} else if (snapshot.hasError) {
print(snapshot.error);
} else {
You can use JsonToDart for parse data and cast to your model
I am working on a flutter app and I found obstacles on how to read product_name and price from Firebase and display them in list
I tried this code but it returns the whole JSON tree as a Text
class _BeveragesProductsState extends State<BeveragesProducts> {
var _firebaseRef = FirebaseDatabase().reference().child('Products');
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(' Beverages Products'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: StreamBuilder(
stream: _firebaseRef.onValue,
builder: (context, snap) {
if (snap.hasData &&
!snap.hasError &&
snap.data.snapshot.value != null) {
Map data = snap.data.snapshot.value;
List item = [];
print("data $data");
data.forEach(
(index, data) => item.add({"key": index, ...data}));
print(item);
return ListView.builder(
reverse: true,
itemCount: item.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Text("$data"),
],
);
});
}
},
),
),
],
),
);
}
}
enter image description here
I've been trying to retreive data from my database using REST API. There are not error in my code but there is no data shown in my emulator and it keeps showing circular progress indicator (that means no data)
Is this because of token that I want to get from shared preferences? or something else?
This is my getToken code :
String token;
Future<String> getToken() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("token");
return token;
}
This is my ShowPost code :
Future<List<Post>> showPosts() async {
String token = await getToken();
var data = await http.get(
"https://api-wisapedia.herokuapp.com/posts?sortBy=createdAt:desc",
headers: {HttpHeaders.authorizationHeader: 'Bearer $token'},
);
var dataDecoded = json.decode(data.body);
List<Post> posts = List();
dataDecoded.forEach((post) {
post.add(post["destination"], post["owner"], post["image"]);
});
return posts;
}
And this is my body code :
FutureBuilder(
future: showPosts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
color: Color(0xFFE1F5FE),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Image(
image: AssetImage('lib/images/pantai.jpg')),
title: Text(snapshot.data[index].title),
subtitle: Text(snapshot.data[index].destination),
),
ButtonTheme.bar(
// make buttons use the appropriate styles for cards
child: ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('DETAILS'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return DetailPost();
}),
);
},
),
FlatButton(
child: const Text('JOIN'),
onPressed: () {
/* ... */
},
),
],
),
),
],
),
);
});
} else {
return Align(
alignment: FractionalOffset.center,
child: CircularProgressIndicator(),
);
}
})
How can I solve this?
remove the () in the future parameter of the future builder
future : showPosts not future :showPosts().
Edit :
replace FutureBuilder with FutureBuilder<List<Post>> and AsyncSnapshot with AsyncSnapshot<List<Post>> to specify the data type of the incoming data.