Last active
November 18, 2020 17:37
-
-
Save kuznetsovin/876996103b11a567514cca03c1059722 to your computer and use it in GitHub Desktop.
Flutter test app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
import 'package:image_picker/image_picker.dart'; | |
void main() => runApp(MyApp()); | |
// класс основного приложения | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Товары', | |
theme: ThemeData(primarySwatch: Colors.blue), | |
home: new ListDisplay(), | |
); | |
} | |
} | |
class ListDisplay extends StatefulWidget { | |
@override | |
_ListDisplayState createState() => new _ListDisplayState(); | |
} | |
class _ListDisplayState extends State<ListDisplay> { | |
@override | |
Widget build(BuildContext context) { | |
var futureBuilder = new FutureBuilder( | |
future: fetchProducts(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
switch (snapshot.connectionState) { | |
case ConnectionState.none: | |
case ConnectionState.waiting: | |
return new Text('loading...'); | |
default: | |
if (snapshot.hasError) | |
return new Text('Error: ${snapshot.error}'); | |
else | |
return createListView(snapshot.data.products); | |
} | |
}, | |
); | |
return new Scaffold( | |
appBar: new AppBar(title: new Text("Товары")), | |
body: futureBuilder, | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
Navigator.push( | |
context, | |
MaterialPageRoute(builder: (context) => NewProductForm()), | |
); | |
}, | |
child: Icon(Icons.add), | |
), | |
); | |
} | |
} | |
Widget createListView(List items) { | |
return new ListView( | |
shrinkWrap: true, | |
primary: false, | |
children: items.map((productInfo) { | |
return ListTile( | |
leading: Tab( | |
icon: Image.network('http://127.0.0.1:8080${productInfo.img}')), | |
//загружаем картинку как иконку | |
title: Text(productInfo.name), | |
subtitle: Text('Цена: ${productInfo.price}'), | |
); | |
}).toList()); | |
} | |
Future<ProductList> fetchProducts() async { | |
final response = | |
await http.get('http://127.0.0.1:8080/api/products', headers: { | |
HttpHeaders.authorizationHeader: | |
"Bearer ohhi7Maewo9oxei1naKahfeiM1luvua5ip8ohbael8ieteigecaod0Wae1xaZahz" | |
}); | |
if (response.statusCode == 200) { | |
// If the call to the server was successful, parse the JSON | |
return ProductList.fromJson(json.decode(response.body)); | |
} else { | |
// If that call was not successful, throw an error. | |
throw Exception('Failed to load post'); | |
} | |
} | |
class Product { | |
final int id; | |
final String name; | |
final String img; | |
final String price; | |
Product({this.id, this.name, this.img, this.price}); | |
factory Product.fromJson(Map<String, dynamic> json) { | |
return Product( | |
id: json['id'], | |
name: json['name'], | |
img: json['img'], | |
price: json['price'].toString(), | |
); | |
} | |
} | |
class ProductList { | |
final List<Product> products; | |
ProductList({this.products}); | |
factory ProductList.fromJson(List<dynamic> parsedJson) { | |
List<Product> products = new List<Product>(); | |
products = parsedJson.map((i) => Product.fromJson(i)).toList(); | |
return new ProductList( | |
products: products, | |
); | |
} | |
} | |
class NewProductForm extends StatefulWidget { | |
@override | |
_NewProductFormState createState() { | |
return _NewProductFormState(); | |
} | |
} | |
class _NewProductFormState extends State<NewProductForm> { | |
final _formKey = GlobalKey<FormState>(); | |
TextEditingController nameFieldController = new TextEditingController(); | |
TextEditingController priceFieldController = new TextEditingController(); | |
File galleryFile; | |
imageSelectorGallery() async { | |
galleryFile = await ImagePicker.pickImage(source: ImageSource.gallery); | |
setState(() {}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text("Новый продукт")), | |
body: Form( | |
key: _formKey, | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.start, | |
children: <Widget>[ | |
new RaisedButton( | |
child: new Text('Выбрать фото'), | |
onPressed: imageSelectorGallery, | |
), | |
new SizedBox( | |
height: 200.0, | |
width: 300.0, | |
child: galleryFile == null | |
? new Text('Не выбрано картинки') | |
: new Image.file(galleryFile), | |
), | |
new TextFormField( | |
controller: nameFieldController, | |
decoration: const InputDecoration( | |
labelText: 'Название продукта', | |
), | |
validator: (value) { | |
if (value.isEmpty) { | |
return 'Введите название продукта'; | |
} | |
}, | |
), | |
new TextFormField( | |
controller: priceFieldController, | |
decoration: const InputDecoration( | |
labelText: 'Цена', | |
), | |
validator: (value) { | |
if (value.isEmpty) { | |
return 'Укажите цену'; | |
} | |
}, | |
), | |
new Padding( | |
padding: const EdgeInsets.symmetric(vertical: 16.0), | |
child: RaisedButton( | |
onPressed: () { | |
if (_formKey.currentState.validate()) { | |
var uri = Uri.parse("http://127.0.0.1:8080/api/products"); | |
var request = new http.MultipartRequest("POST", uri); | |
request.headers.addAll({ | |
HttpHeaders.authorizationHeader: | |
"Bearer ohhi7Maewo9oxei1naKahfeiM1luvua5ip8ohbael8ieteigecaod0Wae1xaZahz" | |
}); | |
request.fields['name'] = nameFieldController.text; | |
request.fields['price'] = priceFieldController.text; | |
request.files.add(http.MultipartFile.fromBytes( | |
'file', galleryFile.readAsBytesSync())); | |
request.send().then((response) { | |
if (response.statusCode == 201) { | |
Navigator.pop(context); | |
} else { | |
print(response.reasonPhrase); | |
} | |
}); | |
} | |
}, | |
child: Text('Сохранить'), | |
), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment