main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:http_get_post/product.dart';
import 'http_service.dart';
void main() => runApp(
App(),
);
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: ProductPage(),
);
}
}
class ProductPage extends StatelessWidget {
final HttpService httpService = HttpService();
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.pink,
title: Text("Products"),
),
backgroundColor: Colors.blueGrey,
body: FutureBuilder(
future: httpService.fetchProducts(),
builder: (BuildContext context, AsyncSnapshot<List<Product>> snapshot) {
if (snapshot.hasData) {
List<Product> posts = snapshot.data;
return ListView(
children: posts
.map((Product product) => Container(
padding: EdgeInsets.all(4),
height: 130,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Card(
child:
Image.network(product.image, width: 130)),
Expanded(
child: Container(
padding: EdgeInsets.all(6),
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
product.name,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Text(
product.description,
style: TextStyle(
fontSize: 15,
),
),
Row(
children: [
Text(
"Price:",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
SizedBox(
width: 4,
),
Icon(
Icons.monetization_on,
color: Colors.green,
),
Text(
product.price.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
],
),
// RatingBox(),
],
)))
]),
)))
.toList(),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
product.dart
class Product {
final String name;
final String description;
final int price;
final String image;
Product(this.name, this.description, this.price, this.image);
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
json['name'],
json['description'],
json['price'],
json['image'],
);
}
}
http_service.dart
import 'dart:convert';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http_get_post/product.dart';
class HttpService {
final String postsURL = "https://www.rrtutors.com/uploads/myproducts.json";
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromMap(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get(postsURL);
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception('Unable to fetch products from the REST API');
}
}
}
0 Comments