Why do I get 'data2' has not been initiliazed error here? - json

It makes no sense at this code. I am trying to grab some strings from the ALREADY INITIALIZED from the futurebuilder data, but can't do so. It gives me the data2 has not been initialized error. Here is data and data2, they are almost similiar, data works fine but data2 doesn't. Why is that?
late List<Album> data;
late List<String> data2;
Here is my code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
const List<String> list = <String>['One', 'Two', 'Three', 'Four'];
Future<List<Album>> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return (userMap['employees'] as List)
.map((e) => Album.fromJson(e))
.toList();
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Album.fromJson(Map<String, dynamic> json)
: userId = json['userId'],
id = json['id'],
title = json['title'];
Map<String, dynamic> toJson() => {
'userId': userId,
'id': id,
'title': title,
};
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
late Future<List<Album>> user;
late List<Album> data;
late List<String> data2;
#override
void initState() {
super.initState();
user = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Column(children: <Widget>[
Expanded(
child: const DropdownButtonExample(),
),
Expanded(
child: FutureBuilder<List<Album>>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
data = snapshot.data ?? [];
print('${data[4].title}');
return ListView.builder(
itemBuilder: (context, index) {
data2[index] = data[index].title;
return Column(children: [
Text(data[index].title ?? ""),
]);
},
itemCount: data.length,
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Center(
child: const CircularProgressIndicator(),
);
},
),
)
]),
),
);
}
}
class DropdownButtonApp extends StatelessWidget {
const DropdownButtonApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('DropdownButton Sample')),
body: const Center(
child: DropdownButtonExample(),
),
),
);
}
}
class DropdownButtonExample extends StatefulWidget {
const DropdownButtonExample({super.key});
#override
State<DropdownButtonExample> createState() => _DropdownButtonExampleState();
}
class _DropdownButtonExampleState extends State<DropdownButtonExample> {
String dropdownValue = list.first;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? value) {
// This is called when the user selects an item.
setState(() {
dropdownValue = value!;
});
},
items: list.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}

For RangeError issue, your data2 is empty so you can search for index and pass your value to it, just add your string to it normally it will put that in right index, so change your listview's builder to this:
return ListView.builder(
itemBuilder: (context, index) {
data2.add(data[index].title);//<--- change this
return Column(children: [
Text(data[index].title ?? ""),
]);
},
itemCount: data.length,
);

Related

unable to parse json data from local database in flutter 'an error has occurred !'

Future<List<Institute>> fetchInstitute(http.Client client) async {
final response = await client
.get(Uri.parse('http://192.168.1.5/tkydatabase/fun/anem.php'));
// Use the compute function to run parseInstitute in a separate isolate.
return compute(parseInstitute, response.body);
}
List<Institute> parseInstitute(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Institute>((json) => Institute.fromJson(json)).toList();
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Institute>>(
future: fetchInstitute(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return InstitutesList(institute: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class InstitutesList extends StatelessWidget {
const InstitutesList({super.key, required this.institute});
final List<Institute> institute;
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: institute.length,
itemBuilder: (context, index) {
return Text(institute[index].instituteName);
},
);
}
}
enter image description here
The data from JSON, so it must have a key and value
is this code help you?
var json =
'{"body":[{"id":1,"instituteName":"value","instituteWilaya":"value"},{"id":2,"instituteName":"value","instituteWilaya":"value"}]}';
var map = jsonDecode(json) as Map<String, dynamic>;
var entityList = map['body'] as List;
var result = List.generate(
entityList.length, (index) => Institute.fromJson(entityList[index]));
print(result);

Why Does my code return circularprogressindicator always, it is not fetching my data

When i run the application it doesnt fetch the data
import 'package:fakeapi/homepage.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:fakeapi/album.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.lightGreen,
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: ((context, snapshot) {
if (snapshot.hasError) {
throw Exception("ERROR");
} else if (snapshot.hasData) {
ListView.builder(
itemBuilder: ((context, index) {
return Text(snapshot.data!.title);
}),
itemCount: 1,
);
}
return Center(
child: CircularProgressIndicator(),
);
}),
future: getAlbums(),
),
);
}
}
Future<Album> getAlbums() async {
final response = await http
.get(Uri.parse("https://jsonplaceholder.typicode.com/albums/10"));
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception("hey");
}
}
// To parse this JSON data, do
//
// final album = albumFromJson(jsonString);
List<Album> albumFromJson(String str) =>
List<Album>.from(json.decode(str).map((x) => Album.fromJson(x)));
String albumToJson(List<Album> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
This is how i coded my class
class Album {
Album({
required this.userId,
required this.id,
required this.title,
});
int userId;
int id;
String title;
factory Album.fromJson(Map<String, dynamic> json) => Album(
userId: json["userId"],
id: json["id"],
title: json["title"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
};
}
I tried to fetch data and display it
import 'package:fakeapi/homepage.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:fakeapi/album.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.lightGreen,
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: ((context, snapshot) {
if (snapshot.hasError) {
throw Exception("ERROR");
} else if (snapshot.hasData) {
ListView.builder(
itemBuilder: ((context, index) {
return Text(snapshot.data!.title);
}),
itemCount: 1,
);
}
return Center(
child: CircularProgressIndicator(),
);
}),
future: getAlbums(),
),
);
}
}
Future<Album> getAlbums() async {
final response = await http
.get(Uri.parse("https://jsonplaceholder.typicode.com/albums/10"));
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception("hey");
}
}
// To parse this JSON data, do
//
// final album = albumFromJson(jsonString);
List<Album> albumFromJson(String str) =>
List<Album>.from(json.decode(str).map((x) => Album.fromJson(x)));
String albumToJson(List<Album> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Album {
Album({
required this.userId,
required this.id,
required this.title,
});
int userId;
int id;
String title;
factory Album.fromJson(Map<String, dynamic> json) => Album(
userId: json["userId"],
id: json["id"],
title: json["title"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
};
}
change your FutureBuilder to this:
builder: ((context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
default:
if (snapshot.hasError) {
throw Exception("ERROR");
} else {
return ListView.builder(
itemBuilder: ((context, index) {
return Text(snapshot.data!.title);
}),
itemCount: 1,
);
}
}
}),
How do you know it doesn't fetch the data? With your current code you always return the CircularProgressIndicator when there isn't an error.
You have to return the ListView builder. I.e.
return ListView.builder(
itemBuilder: ((context, index) {
return Text(snapshot.data!.title);
}),
itemCount: 1,
);
Your current api return a single model,
.....typicode.com/albums/10"
You wont get a list here. You can return single item from this like changing ListView to Text.
if (snapshot.hasData) {
return Text("${snapshot.data?.title}");
You can follow this widget to receive full list
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final future = getAlbums();
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Album>?>(
future: future,
builder: (context, snapshot) {
print(snapshot);
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: ((context, index) {
final model = snapshot.data![index];
return Text("${model.title}");
}),
);
}
return Center(
child: CircularProgressIndicator(),
);
}),
);
}
}
Future<List<Album>?> getAlbums() async {
final response =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/albums/"));
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as List?;
return data?.map((e) => Album.fromJson(e)).toList();
} else {
throw Exception("hey");
}
}

type 'List<dynamic>' is not a subtype of type 'List<MaintenanceInfo>' of 'function result'

I want to change List data; (List < dynamic> data) to List<MaintenanceInfo> data;
class MaintenanceInfo {
final String serial;
MaintenanceInfo({this.serial,});
factory MaintenanceInfo.fromJson(Map<String, dynamic> json) {
return new MaintenanceInfo(
serial: json['serial'], );}}
Or is there any way to extract JSON data as forEach?
I am trying to follow this example (https://stackoverflow.com/a/50569613/12908336) and am facing such a problem.
Check out this example that i have created for you :
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:convert';
//import 'package:http/http.dart' as http;
void main() => runApp(new MaterialApp(
home: new HomePage(),
debugShowCheckedModeBanner: false,
));
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController controller = new TextEditingController();
String apiData =
'''{"ResultText": "Success","ResultStatus": 0,"data": [{"serial": "sample1"},{"serial": "sample2"},{"serial": "sample3"},{"serial": "sample4"},{"serial": "sample5"},{"serial": "sample6"}]} ''';
// Get json result and convert it to model. Then add
Future<Null> getUserDetails() async {
// final response = await http.get(url);
// final responseJson = json.decode(response.body);
// this is where you apis gets hit i have taken the sample json you provided.
final maintenanceInfo = maintenanceInfoFromJson(apiData);
setState(() {
/* for (Map user in responseJson) {
_userDetails.add(UserDetails.fromJson(user));
} */
maintenanceInfo.data.forEach((element) {
_userDetails.add(element);
});
});
}
#override
void initState() {
super.initState();
getUserDetails();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),
elevation: 0.0,
),
body: new Column(
children: <Widget>[
new Container(
color: Theme.of(context).primaryColor,
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: new Card(
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
controller: controller,
decoration: new InputDecoration(
hintText: 'Search', border: InputBorder.none),
onChanged: onSearchTextChanged,
),
trailing: new IconButton(
icon: new Icon(Icons.cancel),
onPressed: () {
controller.clear();
onSearchTextChanged('');
},
),
),
),
),
),
new Expanded(
child: _searchResult.length != 0 || controller.text.isNotEmpty
? new ListView.builder(
itemCount: _searchResult.length,
itemBuilder: (context, i) {
return new Card(
child: new ListTile(
title: new Text(_searchResult[i].serial),
),
margin: const EdgeInsets.all(0.0),
);
},
)
: new ListView.builder(
itemCount: _userDetails.length,
itemBuilder: (context, index) {
return new Card(
child: new ListTile(
title: new Text(_userDetails[index].serial),
),
margin: const EdgeInsets.all(0.0),
);
},
),
),
],
),
);
}
onSearchTextChanged(String text) async {
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return;
}
_userDetails.forEach((userDetail) {
if (userDetail.serial.contains(text)) _searchResult.add(userDetail);
});
setState(() {});
}
}
List<Serials> _searchResult = [];
List<Serials> _userDetails = [];
// To parse this JSON data, do
//
// final maintenanceInfo = maintenanceInfoFromJson(jsonString);
MaintenanceInfo maintenanceInfoFromJson(String str) =>
MaintenanceInfo.fromJson(json.decode(str));
String maintenanceInfoToJson(MaintenanceInfo data) =>
json.encode(data.toJson());
class MaintenanceInfo {
MaintenanceInfo({
this.resultText,
this.resultStatus,
this.data,
});
String resultText;
int resultStatus;
List<Serials> data;
factory MaintenanceInfo.fromJson(Map<String, dynamic> json) =>
MaintenanceInfo(
resultText: json["ResultText"],
resultStatus: json["ResultStatus"],
data: List<Serials>.from(json["data"].map((x) => Serials.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"ResultText": resultText,
"ResultStatus": resultStatus,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Serials {
Serials({
this.serial,
});
String serial;
factory Serials.fromJson(Map<String, dynamic> json) => Serials(
serial: json["serial"],
);
Map<String, dynamic> toJson() => {
"serial": serial,
};
}
Let me know if it works.

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast?

here is the response
{
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground "fight clubs" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"title": "Fight Club",
}
the model
class Movies {
String title;
String overview;
Movies(
{this.title , this.overview});
factory Movies.fromJson(Map <String, dynamic> parsedJson){
return Movies(title: parsedJson['title'] , overview: parsedJson['overview']);
}
}
and
Future <List<Movies>> fetchMovies () async {
var response = await http.get(url);
var jsonData = jsonDecode(response.body) as List ;
List<Movies> movies = jsonData.map((e) => Movies.fromJson(e)).toList();
print(movies.length);
return movies;
}
I get this error (Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast) no matter what i do
You tried to cast jsonData as List but the decoder says it's of type Map (Also your response shows its of type Map)
Future <List<Movies>> fetchMovies () async {
var response = await http.get(url);
var jsonData = jsonDecode(response.body);
if(jsonData is List) //check if it's a List
return List<Movies>.from(jsonData.map(map) => Movies.fromJson(map));
else if(jsonData is Map) //check if it's a Map
return [Movies.fromJson(jsonData)]; //return a List of length 1
}
You can copy paste run full code below
You can use moviesFromJson and display with FutureBuilder
code snippet
List<Movies> moviesFromJson(String str) =>
List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));
if (response.statusCode == 200) {
return moviesFromJson(jsonString);
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
List<Movies> moviesFromJson(String str) =>
List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));
String moviesToJson(List<Movies> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Movies {
Movies({
this.overview,
this.title,
});
String overview;
String title;
factory Movies.fromJson(Map<String, dynamic> json) => Movies(
overview: json["overview"],
title: json["title"],
);
Map<String, dynamic> toJson() => {
"overview": overview,
"title": title,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<List<Movies>> _future;
Future<List<Movies>> fetchMovies() async {
String jsonString = '''
[{
"overview" : "with underground \\"fight clubs\\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion",
"title" : "Fight Club"
},
{
"overview" : "test overview",
"title" : "test title"
}
]
''';
var response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
return moviesFromJson(jsonString);
} else {
print(response.statusCode);
}
}
#override
void initState() {
_future = fetchMovies();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<Movies>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].title),
Spacer(),
Expanded(
child: Text(
snapshot.data[index].overview,
),
),
],
),
));
});
}
}
}));
}
}
Just check out he answer
[
{
"overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"title":"Fight Club"
},
{
"overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground fight clubs forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"title":"second Club"
}
]
Model
// To parse this JSON data, do
//
// final movies = moviesFromJson(jsonString);
import 'dart:convert';
List<Movies> moviesFromJson(String str) => List<Movies>.from(json.decode(str).map((x) => Movies.fromJson(x)));
String moviesToJson(List<Movies> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Movies {
Movies({
this.overview,
this.title,
});
String overview;
String title;
factory Movies.fromJson(Map<String, dynamic> json) => Movies(
overview: json["overview"],
title: json["title"],
);
Map<String, dynamic> toJson() => {
"overview": overview,
"title": title,
};
}
ui page :
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isLoading = false;
List<Movies> dataList = List();
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
#override
void initState() {
super.initState();
getData();
}
getData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadFromAssets();
final movies = moviesFromJson(jsonString);
dataList = movies;
setState(() {
_isLoading = false;
});
}
// In your case you just check out this code check out the model class
/* Future <List<Movies>> fetchMovies () async {
var response = await http.get(url);
return moviesFromJson(response.body);
} */
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: Container(
child: ListView.builder(
itemCount: dataList.length,
shrinkWrap: true,
itemBuilder: (context, i) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(dataList[i].overview),
));
}),
),
);
}
}
And on thing to tell is the value for the overview has the double quotes which is why there might be some parsing problem just check the code and let me know if it works.

Flutter: json data is not displaying in future builder on http get request

I'm trying to display items from json http get request. But It displays nothing.
This is the request function
Future<List<Products>> _getProducts() async{
var data = await http.get("http://orangecitycafe.in/app_configs/products_display.php");
var jsonData = json.decode(data.body);
List<Products> products = [];
for (var p in jsonData){
Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
price: p["product_price"],image: p["product_image"]);
products.add(product);
}
print(products);
return products;
}
NOTE: This is my custom created json file
This is my json file
And this is the php code for fetching data from database and creating a json format
$sql = "SELECT * FROM $products_table";
$result = mysqli_query($conn,$sql);
$db_data = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)){
$db_data[] = $row;
}
echo json_encode($db_data);
}
And this is the UI for Future Builder
body:
Container(
child: FutureBuilder(
future: _getProducts(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data == null){
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
}
else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
return ListTile(
title: Text(snapshot.data[index].price),
);
},
);
}
},
),
)
I don't know where actually the mistake is. Is it happens due to my custom json file or I might miss something.
You can copy paste run full code below
You can see Products class in full code
code snippet to parse json string
Future<List<Products>> _getProducts() async {
var data = await http
.get("http://orangecitycafe.in/app_configs/products_display.php");
var jsonData = json.decode(data.body);
List<Products> products = [];
products = productsFromJson(data.body);
return products;
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final products = productsFromJson(jsonString);
import 'dart:convert';
List<Products> productsFromJson(String str) =>
List<Products>.from(json.decode(str).map((x) => Products.fromJson(x)));
String productsToJson(List<Products> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Products {
String the0;
String the1;
String the2;
String the3;
String the4;
DateTime the5;
String productId;
String categId;
String productName;
String productPrice;
String productImage;
DateTime addedDate;
Products({
this.the0,
this.the1,
this.the2,
this.the3,
this.the4,
this.the5,
this.productId,
this.categId,
this.productName,
this.productPrice,
this.productImage,
this.addedDate,
});
factory Products.fromJson(Map<String, dynamic> json) => Products(
the0: json["0"],
the1: json["1"],
the2: json["2"],
the3: json["3"],
the4: json["4"],
the5: DateTime.parse(json["5"]),
productId: json["product_id"],
categId: json["categ_id"],
productName: json["product_name"],
productPrice: json["product_price"],
productImage: json["product_image"],
addedDate: DateTime.parse(json["added_date"]),
);
Map<String, dynamic> toJson() => {
"0": the0,
"1": the1,
"2": the2,
"3": the3,
"4": the4,
"5": the5.toIso8601String(),
"product_id": productId,
"categ_id": categId,
"product_name": productName,
"product_price": productPrice,
"product_image": productImage,
"added_date": addedDate.toIso8601String(),
};
}
Future<List<Products>> _getProducts() async {
var data = await http
.get("http://orangecitycafe.in/app_configs/products_display.php");
var jsonData = json.decode(data.body);
List<Products> products = [];
products = productsFromJson(data.body);
/*for (var p in jsonData){
Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
price: p["product_price"],image: p["product_image"]);
products.add(product);
}
print(products);*/
return products;
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: FutureBuilder(
future: _getProducts(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(snapshot.data[index].productName),
);
},
);
}
},
),
),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}