Reputation: 21
I am trying to make some http requests to an API. The first is to get data and display it in a list view and the second one is some more data but I want to display it on a new page. The code I have currently is returning null for the second Total request. If I run the total code separately it works fine and displays the data in a list view.
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'Product.dart';
import 'Total.dart';
void main() => runApp(MyApp(
products: fetchProducts(),
total: fetchTotal(),
));
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response =
await http.get('http://10.0.0.102:9000/all/aF63z0R0jlQR7sfOgBAgOCOsQgv1');
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception("Unable to access Server.");
}
}
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
final Future<List<Total>> total;
MyApp({Key key, this.products, this.total}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Product Navigation demo home page',
products: products,
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
final Future<List<Product>> products;
final Future<List<Total>> total;
MyHomePage({Key key, this.title, this.products, this.total})
: super(key: key);
// final items = Product.getProducts();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ProductBoxList(items: snapshot.data)
// return the ListView widget :
: Center(child: CircularProgressIndicator());
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => TotalPage()));
},
child: Icon(Icons.navigation),
backgroundColor: Colors.green,
),
);
}
}
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
class ProductPage extends StatelessWidget {
ProductPage({Key key, this.item}) : super(key: key);
final Product item;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.item.pName),
),
body: Center(
child: Container(
padding: EdgeInsets.all(0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.pName,
style: TextStyle(fontWeight: FontWeight.bold)),
Text("Price: " + this.item.price),
Text("Barcode: " + this.item.barcode.toString()),
],
)))
]),
),
),
);
}
}
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.item}) : super(key: key);
final Product item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.pName,
style: TextStyle(fontWeight: FontWeight.bold)),
Text("Price: " + this.item.price),
Text("Barcode: " + this.item.barcode.toString()),
],
)))
]),
));
}
}
List<Total> parseTotal(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Total>((json) => Total.fromJson(json)).toList();
}
Future<List<Total>> fetchTotal() async {
final response = await http.get('http://10.0.0.102:8000/testData.json');
if (response.statusCode == 200) {
return parseTotal(response.body);
} else {
throw Exception("Unable to access Server.");
}
}
class TotalPage extends StatelessWidget {
final String title;
final Future<List<Total>> total;
TotalPage({Key key, this.title, this.total}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Total>>(
future: total,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
print(snapshot.data);
return snapshot.hasData
? TotalBoxList(items: snapshot.data)
// return the ListView widget :
: Center(child: CircularProgressIndicator());
},
),
),
);
}
}
class TotalBoxList extends StatelessWidget {
final List<Total> items;
TotalBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: TotalDisplay(item: items[index]),
);
},
);
}
}
class TotalDisplay extends StatelessWidget {
TotalDisplay({Key key, this.item}) : super(key: key);
final Total item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.total.toString(),
style: TextStyle(fontWeight: FontWeight.bold)),
],
)))
]),
));
}
}
total.dart
import 'package:flutter/foundation.dart';
class Total {
final double total;
Total(this.total);
factory Total.fromJson(Map<String, dynamic> data) {
return Total(
data['total'],
);
}
}
Upvotes: 1
Views: 612
Reputation: 54367
You can copy paste run full code below
You forgot to pass total
Step 1: MyHomePage
MyHomePage(
title: 'Product Navigation demo home page',
products: products,
total: total, //here
),
Step 2: FloatingActionButton
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TotalPage(
total: total,
))); //here
},
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp(
products: fetchProducts(),
total: fetchTotal(),
));
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
Future<List<Product>> fetchProducts() async {
/*final response =
await http.get('http://10.0.0.102:9000/all/aF63z0R0jlQR7sfOgBAgOCOsQgv1');*/
String jsonString = '''
[
{
"pName":"1",
"price":"2",
"barcode": 3
},
{
"pName":"4",
"price":"5",
"barcode": 6
}
]
''';
final response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception("Unable to access Server.");
}
}
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
final Future<List<Total>> total;
MyApp({Key key, this.products, this.total}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Product Navigation demo home page',
products: products,
total: total, //here
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
final Future<List<Product>> products;
final Future<List<Total>> total;
MyHomePage({Key key, this.title, this.products, this.total})
: super(key: key);
// final items = Product.getProducts();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ProductBoxList(items: snapshot.data)
// return the ListView widget :
: Center(child: CircularProgressIndicator());
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TotalPage(
total: total,
))); //here
},
child: Icon(Icons.navigation),
backgroundColor: Colors.green,
),
);
}
}
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
class ProductPage extends StatelessWidget {
ProductPage({Key key, this.item}) : super(key: key);
final Product item;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.item.pName),
),
body: Center(
child: Container(
padding: EdgeInsets.all(0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.pName,
style: TextStyle(fontWeight: FontWeight.bold)),
Text("Price: " + this.item.price),
Text("Barcode: " + this.item.barcode.toString()),
],
)))
]),
),
),
);
}
}
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.item}) : super(key: key);
final Product item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.pName,
style: TextStyle(fontWeight: FontWeight.bold)),
Text("Price: " + this.item.price),
Text("Barcode: " + this.item.barcode.toString()),
],
)))
]),
));
}
}
List<Total> parseTotal(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
List<Total> a = parsed.map<Total>((json) => Total.fromJson(json)).toList();
return a;
}
Future<List<Total>> fetchTotal() async {
print("fetchTotal");
//final response = await http.get('http://10.0.0.102:8000/testData.json');
String jsonString = '''
[
{
"total":124.4
},
{
"total":123.1
}
]
''';
final response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
return parseTotal(response.body);
} else {
throw Exception("Unable to access Server.");
}
}
class TotalPage extends StatelessWidget {
final String title;
final Future<List<Total>> total;
TotalPage({Key key, this.title, this.total}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Total>>(
future: total,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? TotalBoxList(items: snapshot.data)
// return the ListView widget :
: Center(child: CircularProgressIndicator());
},
),
),
);
}
}
class TotalBoxList extends StatelessWidget {
final List<Total> items;
TotalBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: TotalDisplay(item: items[index]),
);
},
);
}
}
class TotalDisplay extends StatelessWidget {
TotalDisplay({Key key, this.item}) : super(key: key);
final Total item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.total.toString(),
style: TextStyle(fontWeight: FontWeight.bold)),
],
)))
]),
));
}
}
class Total {
final double total;
Total(this.total);
factory Total.fromJson(Map<String, dynamic> data) {
return Total(
data['total'],
);
}
}
class Product {
String pName;
String price;
int barcode;
Product({this.pName, this.price, this.barcode});
factory Product.fromJson(Map<String, dynamic> data) {
return Product(
pName: data["pName"], price: data["price"], barcode: data["barcode"]);
}
}
Upvotes: 1