Latihan Flutter
onboarding screen
pubspec.yaml
name: flutter_intro_layout
description: A new Flutter application.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_swiper: any
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
color_pallete.dart
import 'package:flutter/material.dart';
class ColorPallete{
static const dotColor = Color(0xffe8e8e8);
static const dotActiveColor = Color(0xffff3800);
static const titleColor = Color(0xff1c1a1a);
static const descriptionColor = Color(0xff707070);
}
model/intro.dart
class Intro{
String image;
String title;
String description;
Intro({this.image, this.title, this.description});
}
screens/intro_view.dart
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_intro_layout/model/intro.dart';
import 'package:flutter_intro_layout/color_palette.dart';
class IntroPage extends StatefulWidget{
@override
_IntroPageState createState() => _IntroPageState();
}
class _IntroPageState extends State<IntroPage>{
final List<Intro> introList = [
Intro(
image: "assets/images/icon_search.png",
title: "Search",
description: "Discover Restaurants offering the best fast food food near you on Foodwa",
),
Intro(
image: "assets/images/icon_hamburger.png",
title: "Order",
description: "Our veggie plan is filled with delicious seasonal vegetables, whole grains, beautiful cheeses and vegetarian proteins",
),
Intro(
image: "assets/images/icon_otw.png",
title: "Eat",
description: "Food delivery or pickup from local restaurants, Explore restaurants that deliver near you.",
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Swiper.children(
index: 0,
autoplay: false,
loop: false,
pagination: SwiperPagination(
margin: EdgeInsets.only(bottom: 20.0),
builder: DotSwiperPaginationBuilder(
color: ColorPallete.dotColor,
activeColor: ColorPallete.dotActiveColor,
size: 10.0,
activeSize: 10.0,
),
),
control: SwiperControl(
iconNext: null,
iconPrevious: null,
),
children: _buildPage(context),
),
);
}
List<Widget> _buildPage(BuildContext context){
List<Widget> widgets = [];
for(int i=0; i<introList.length; i++){
Intro intro = introList[i];
widgets.add(
Container(
padding: EdgeInsets.only(
top: MediaQuery.of(context).size.height/6,
),
child: ListView(
children: <Widget>[
Image.asset(
intro.image,
height: MediaQuery.of(context).size.height/3.5,
),
Padding(
padding: EdgeInsets.only(
top: MediaQuery.of(context).size.height/12.0,
),
),
Center(
child: Text(
intro.title,
style: TextStyle(
color: ColorPallete.titleColor,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
),
Padding(
padding: EdgeInsets.only(
top: MediaQuery.of(context).size.height/20.0,
),
),
Container(
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.height/20.0,
),
child: Text(
intro.description,
style: TextStyle(
color: ColorPallete.descriptionColor,
fontSize: 14.0,
),
textAlign: TextAlign.center,
),
),
],
),
),
);
}
return widgets;
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_intro_layout/screens/intro_view.dart';
void main(){
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Intro Layout',
home: IntroPage(),
));
}
screen
Navigation Drawer
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: "Navigation Drawer",
debugShowCheckedModeBanner: false,
home: _HomePage(),
));
}
class _HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<_HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Navigation Drawer'),
),
body: Center(
child: Text('Flutter Navigation Drawer'),
),
drawer: _buildDrawer(),
endDrawer: _buildDrawer(),
);
}
Widget _buildDrawer() {
return SizedBox(
width: MediaQuery.of(context).size.width/1.2,
child: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("Codingtive"),
accountEmail: Text("codingtive@gmail.com"),
decoration: BoxDecoration(
color: Colors.blue,
),
),
_buildListTile(Icons.apps, "Applications", null),
_buildListTile(Icons.notifications, "Notifications", null),
_buildListTile(Icons.subscriptions, "Subscribe", null),
_buildListTile(Icons.bookmark_border, "Wishlist", null),
Divider(
height: 2.0,
),
_buildListTile(Icons.person, "Account", null),
_buildListTile(Icons.settings, "Settings", null),
Divider(
height: 2.0,
),
_buildListTile(null, "About Codingtive", null),
_buildListTile(null, "Logout", Icons.input),
],
),
),
);
}
Widget _buildListTile(
IconData iconLeading,
String title,
IconData iconTrailing,
) {
return ListTile(
leading: Icon(iconLeading),
title: Text(title),
trailing: Icon(iconTrailing),
onTap: () {},
);
}
}
ListView Builder
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListView Builder',
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text(
'ListView Builder',
style: TextStyle(color: Colors.white),
),
),
body: _PageList(),
),
);
}
}
class _PageList extends StatefulWidget {
@override
_PageListState createState() => _PageListState();
}
class _PageListState extends State<_PageList> {
List languages = [
"Dart",
"Kotlin",
"Java",
"PHP",
"Swift",
"Javascript",
];
@override
Widget build(BuildContext context) {
return Container(
color: Colors.grey[300],
child: ListView.builder(
itemCount: languages.length,
itemBuilder: (BuildContext context, int index) {
final number = index + 1;
final language = languages[index].toString();
return Card(
child: ListTile(
leading: Text(number.toString()),
title: Text(language),
trailing: Icon(Icons.check)),
);
},
),
);
}
}
Navigator
main.dart
import 'package:flutter/material.dart';
void main(){
runApp(MaterialApp(
title: 'Navigation Basics',
home: Page1(),
));
}
class Page1 extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 1'),
),
body: Center(
child: RaisedButton(
child: Text('Page 2'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context)=> Page2()),
);
}
),
),
);
}
}
class Page2 extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 2'),
),
body: Center(
child: RaisedButton(
child: Text('Kembali'),
onPressed: () {
Navigator.pop(context);
}
),
),
);
}
}
To Page
Navigator.push(
context,
MaterialPageRoute(builder: (context)=> Page2()),
);
History Back
Navigator.pop(context);
Page 1 Page 2
http request
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(DigitalQuran());
}
class DigitalQuran extends StatefulWidget {
DigitalQuranState createState() => DigitalQuranState();
}
class DigitalQuranState extends State<DigitalQuran> {
final String url = 'https://api.banghasan.com/quran/format/json/surat';
List data;
Future<String> getData() async {
var res = await http.get(Uri.encodeFull(url), headers: { 'accept':'application/json' });
setState(() {
var content = json.decode(res.body);
data = content['hasil'];
});
return 'success!';
}
Widget build(context) {
return MaterialApp(
title: 'Digital Quran',
home: Scaffold(
appBar: AppBar(
title: Text('Digital Quran')
),
body: Container(
margin: EdgeInsets.all(10.0),
child: ListView.builder(
itemCount: data == null ? 0:data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,children: <Widget>[
ListTile(
leading: Text(data[index]['nomor'], style: TextStyle(fontSize: 30.0),),
title: Text(data[index]['nama'], style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold),),
trailing: Image.asset(data[index]['type'] == 'mekah' ? 'mekah.jpg':'madinah.png', width: 32.0, height: 32.0,),
subtitle: Column(children: <Widget>[
Row(
children: <Widget>[
Text('Arti : ', style: TextStyle(fontWeight: FontWeight.bold),),
Text(data[index]['arti'], style: TextStyle(fontStyle: FontStyle.italic, fontSize: 15.0),),
],
),
Row(
children: <Widget>[
Text('Jumlah Ayat : ', style: TextStyle(fontWeight: FontWeight.bold),),
Text(data[index]['ayat'])
],
),
Row(
children: <Widget>[
Text('Diturunkan : ', style: TextStyle(fontWeight: FontWeight.bold),),
Text(data[index]['type'])
],
),
],),
),
ButtonTheme.bar(
child: ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('LIHAT DETAIL'),
onPressed: () { /* ... */ },
),
FlatButton(
child: const Text('DENGARKAN'),
onPressed: () { /* ... */ },
),
],
),
),
],),
)
);
},
),
)
),
);
}
@override
void initState() {
// TODO: implement initState
super.initState();
this.getData();
}
}
pubspec.yaml
name: daengweb_http
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# Read more about versioning at semver.org.
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
http: 0.12.0+2
flutter_html: ^0.8.2
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- madinah.png
- mekah.jpg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.io/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.io/custom-fonts/#from-packages
External Package
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
english_words: ^3.1.0
pubspec.yaml
main.dart
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
final wordPair = new WordPair.random();
return new MaterialApp(
title: "Package Word",
home: new Scaffold(
appBar: new AppBar(
title: const Text("Package Word Pair"),
),
body: new Center(
child: new Text(wordPair.asCamelCase)
),
),
);
}
}
Stateful Widget
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Package Word",
home: new Scaffold(
appBar: new AppBar(
title: const Text("Package Word Pair"),
),
body: new Center(
child: new RandomWords(),
),
),
);
}
}
class RandomWords extends StatefulWidget{
@override
RandomWordsState createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords>{
@override
Widget build(BuildContext context) {
final WordPair wordPair = new WordPair.random();
return new Text(wordPair.asUpperCase);
}
}
Basic ListView
import 'package:flutter/material.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "ListView",
home: new Scaffold(
appBar: new AppBar(
title: const Text("ListView"),
),
body: new Center(
child: _sampleList(),
),
),
);
}
}
Widget _sampleList(){
return new ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
),
],
);
}
ListView Builder
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "ListView Builder",
home: new Scaffold(
appBar: new AppBar(
title: const Text("ListView Builder"),
),
body: new Center(
child: _sampleListBuilder(),
),
),
);
}
}
Widget _sampleListBuilder() {
final items = List<String>.generate(100, (i) => "Item ke-$i");
return new ListView.builder(
itemCount: items.length,
itemBuilder: (context,index){
final item = items[index];
return ListTile(
title: Text(item),
);
}
);
}
Divider
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "ListView Builder",
home: new Scaffold(
appBar: new AppBar(
title: const Text("ListView Builder"),
),
body: new Center(
child: _sampleListBuilder(),
),
),
);
}
}
Widget _sampleListBuilder() {
final items = List<String>.generate(20, (i) => "Item ke-${i~/2}");
return new ListView.builder(
itemCount: items.length,
itemBuilder: (context,index){
final item = items[index];
if(index.isOdd){
return new Divider();
}else{
return ListTile(
title: Text(item),
);
}
}
);
}
Infinity ListView
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Startup Name Generator",
home: new RandomWords(),
);
}
}
class RandomWords extends StatefulWidget{
@override
RandomWordsState createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords>{
final List<WordPair> _suggestions = <WordPair>[];
final TextStyle _biggerFont = const TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Startup Name Generator'),
),
body: _buildSuggestions(),
);
}
Widget _buildSuggestions(){
return new ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (BuildContext _context, int i){
if(i.isOdd){
return const Divider();
}
final int index = i ~/ 2;
if(index >= _suggestions.length){
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
}
);
}
Widget _buildRow(WordPair pair){
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
);
}
}
ListView + Icon
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Startup Name Generator",
home: new RandomWords(),
);
}
}
class RandomWords extends StatefulWidget{
@override
RandomWordsState createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords>{
final List<WordPair> _suggestions = <WordPair>[];
final Set<WordPair> _saved = new Set<WordPair>();
final TextStyle _biggerFont = const TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Startup Name Generator'),
),
body: _buildSuggestions(),
);
}
Widget _buildSuggestions(){
return new ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (BuildContext _context, int i){
if(i.isOdd){
return const Divider();
}
final int index = i ~/ 2;
if(index >= _suggestions.length){
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
}
);
}
Widget _buildRow(WordPair pair){
final bool alreadySaved = _saved.contains(pair);
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: new Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: (){
setState(() {
if(alreadySaved){
_saved.remove(pair);
}else{
_saved.add(pair);
}
});
},
);
}
}
Routing
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(
MyApp()
);
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Startup Name Generator",
home: new RandomWords(),
);
}
}
class RandomWords extends StatefulWidget{
@override
RandomWordsState createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords>{
final List<WordPair> _suggestions = <WordPair>[];
final Set<WordPair> _saved = new Set<WordPair>();
final TextStyle _biggerFont = const TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Startup Name Generator'),
actions: <Widget>[
new IconButton(
icon: const Icon(Icons.list),
onPressed: _pushSaved
),
],
),
body: _buildSuggestions(),
);
}
void _pushSaved(){
Navigator.of(context).push(
new MaterialPageRoute<void>(
builder: (BuildContext context){
final Iterable<ListTile> tiles = _saved.map(
(WordPair pair){
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
);
},
);
final List<Widget> divided = ListTile.divideTiles(
tiles: tiles,
context: context,
).toList();
return new Scaffold(
appBar: new AppBar(
title: const Text('Saved Suggestions'),
),
body: new ListView(children:divided),
);
},
),
);
}
Widget _buildSuggestions(){
return new ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (BuildContext _context, int i){
if(i.isOdd){
return const Divider();
}
final int index = i ~/ 2;
if(index >= _suggestions.length){
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
}
);
}
Widget _buildRow(WordPair pair){
final bool alreadySaved = _saved.contains(pair);
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: new Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: (){
setState(() {
if(alreadySaved){
_saved.remove(pair);
}else{
_saved.add(pair);
}
});
},
);
}
}
UI Theme
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Startup Name Generator",
home: new RandomWords(),
theme: new ThemeData(
primaryColor: Colors.white,
),
);
}
}
fetch from internet
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: '>=0.11.3+12'
pubspec.yaml
json :
https://jsonplaceholder.typicode.com/posts/1
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}
ListView + API
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Photo {
final int id;
final String title;
final String thumbnailUrl;
Photo({this.id, this.title, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as int,
title: json['title'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');
// Use the compute function to run parsePhotos in a separate isolate
return compute(parsePhotos, response.body);
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'List View Internet';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
//? PhotosList(photos: snapshot.data)
? TitleList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class TitleList extends StatelessWidget {
final List<Photo> photos;
TitleList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(photos[index].title),
);
}
);
}
}
Image + API
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Photo {
final int id;
final String title;
final String thumbnailUrl;
Photo({this.id, this.title, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as int,
title: json['title'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');
// Use the compute function to run parsePhotos in a separate isolate
return compute(parsePhotos, response.body);
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'List View Internet';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data) // tambahkan baris ini
//? TitleList(photos: snapshot.data) // comment baris ini
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index].thumbnailUrl);
},
);
}
}
Tabs
import 'package:flutter/material.dart';
void main() {
runApp(TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: Text('Tabs Demo'),
),
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
Tabs + List + API
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
class Photo {
final int id;
final String title;
final String thumbnailUrl;
Photo({this.id, this.title, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as int,
title: json['title'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');
// Use the compute function to run parsePhotos in a separate isolate
return compute(parsePhotos, response.body);
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index].thumbnailUrl);
},
);
}
}
class TitleList extends StatelessWidget {
final List<Photo> photos;
TitleList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(photos[index].title),
);
}
);
}
}
void main() => runApp(TabBarDemo());
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: Text('Tabs Demo'),
),
body: TabBarView(
children: [
FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
//Icon(Icons.directions_car),
FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? TitleList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
//Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
API + POST
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class User {
final String status;
final String message;
User({this.status, this.message});
factory User.fromJson(Map<String, dynamic> json) {
return User(
status: json['status'],
message: json['message'],
);
}
}
Future<User> post(String url,var body)async{
return await http
.post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
.then((http.Response response) {
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while fetching data");
}
return User.fromJson(json.decode(response.body));
});
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Post Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Post Data Example'),
),
body: Center(
child: FutureBuilder<User>(
future: post("http://192.3.168.178/restapi/login.php",
{"username": "ira", "password": "2222"}),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.status);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}
Entry Data
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: '>=0.11.3+12'
flutter_cupertino_date_picker: ^0.3.0
pubspec.yaml
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
class EntryData extends StatefulWidget {
@override
EntryDataState createState() => new EntryDataState();
}
class EntryDataState extends State<EntryData> {
// text field
final _nomerRakController = TextEditingController();
final _namaProdukController = TextEditingController();
// dropdown category
List _category = ["Buah-buahan", "Snack", "Stationary", "Baju", "Ice Cream"];
List<DropdownMenuItem<String>> _dropDownMenuItems;
String _currentCategory;
// datepicker
String _datetime = '';
int _year = 2018;
int _month = 11;
int _date = 11;
// radio
int _radioValue1;
@override
void initState() {
super.initState();
// dropdown category
_dropDownMenuItems = getDropDownMenuItems();
_currentCategory = _dropDownMenuItems[0].value;
// datepicker
DateTime now = DateTime.now();
_year = now.year;
_month = now.month;
_date = now.day;
}
// dropdown category
List<DropdownMenuItem<String>> getDropDownMenuItems() {
List<DropdownMenuItem<String>> items = new List();
for (String kategori in _category) {
items.add(new DropdownMenuItem(
value: kategori,
child: new Text(kategori)
));
}
return items;
}
void changedDropDownItem(String selectedCategory) {
setState(() {
_currentCategory = selectedCategory;
});
}
// radio discount
void _handleRadioValueChange1(int value) {
setState(() {
_radioValue1 = value;
});
}
/// Display date picker.
void _showDatePicker() {
final bool showTitleActions = false;
DatePicker.showDatePicker(
context,
showTitleActions: true,
minYear: 2019,
maxYear: 2022,
initialYear: _year,
initialMonth: _month,
initialDate: _date,
confirm: Text(
'PILIH',
style: TextStyle(color: Colors.red),
),
cancel: Text(
'BATAL',
style: TextStyle(color: Colors.cyan),
),
locale: "en",
dateFormat: "dd-mm-yyyy",
onChanged: (year, month, date) {
//debugPrint('onChanged date: $year-$month-$date');
if (!showTitleActions) {
_changeDatetime(year, month, date);
}
},
onConfirm: (year, month, date) {
_changeDatetime(year, month, date);
},
);
}
void _changeDatetime(int year, int month, int date) {
setState(() {
_year = year;
_month = month;
_date = date;
_datetime = '$date-$month-$year';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Produk Entry'),
),
body: SafeArea(
child: ListView(
padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
children: <Widget>[
// text field
TextField(
controller: _nomerRakController,
decoration: InputDecoration(
filled: false,
labelText: 'Nomer Rak',
),
),
// spacer
SizedBox(height: 5.0),
// text field
TextField(
controller: _namaProdukController,
decoration: InputDecoration(
filled: false,
labelText: 'Nama Produk',
),
),
// Dropdown
new Container(
padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Text("Kategori: ", style: new TextStyle(fontSize: 15.0)),
new DropdownButton(
value: _currentCategory,
items: _dropDownMenuItems,
onChanged: changedDropDownItem,
)
],
),
),
// datepicker
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
RaisedButton(
child: Text('Expired Date', style: new TextStyle(fontSize: 15.0)),
onPressed: () {
_showDatePicker();
},
),
new Text(" $_datetime", style: new TextStyle(fontSize: 15.0)),
],
),
),
// Radio
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Radio(
value: 0,
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Discount',
style: new TextStyle(fontSize: 15.0),
),
new Radio(
value: 1,
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Non Discount',
style: new TextStyle(fontSize: 15.0),
),
],
),
),
// button
RaisedButton(
child: Text('SIMPAN'),
onPressed: () {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text the user has typed in using our
// TextEditingController
content: Text('Nomer Rak: ${_nomerRakController.text}\n'+
'Produk: ${_namaProdukController.text}\n'+
'Kategori: $_currentCategory\n' +
'Expired Date: $_datetime\n' +
'Radio: $_radioValue1'),
);
},
);
},
),
],
)
),
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entry Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new EntryData(),
);
}
}
Qr Scanner
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: '>=0.11.3+12'
flutter_cupertino_date_picker: ^0.3.0
barcode_scan: "^0.0.4"
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
class EntryData extends StatefulWidget {
@override
EntryDataState createState() => new EntryDataState();
}
class EntryDataState extends State<EntryData> {
// text field
final _nomerRakController = TextEditingController();
final _namaProdukController = TextEditingController();
// dropdown category
List _category = ["Buah-buahan", "Snack", "Stationary", "Baju", "Ice Cream"];
List<DropdownMenuItem<String>> _dropDownMenuItems;
String _currentCategory;
// datepicker
String _datetime = '';
int _year = 2018;
int _month = 11;
int _date = 11;
// radio
int _radioValue1;
String _scanResult = '';
// scan QR
Future _scanQR() async {
try {
String qrResult = await BarcodeScanner.scan();
setState(() {
_scanResult = qrResult;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
_scanResult = "Camera permission was denied";
});
} else {
setState(() {
_scanResult = "Unknown Error $ex";
});
}
} on FormatException {
setState(() {
_scanResult = "You pressed the back button before scanning anything";
});
} catch (ex) {
setState(() {
_scanResult = "Unknown Error $ex";
});
}
}
@override
void initState() {
super.initState();
// dropdown category
_dropDownMenuItems = getDropDownMenuItems();
_currentCategory = _dropDownMenuItems[0].value;
// datepicker
DateTime now = DateTime.now();
_year = now.year;
_month = now.month;
_date = now.day;
}
// dropdown category
List<DropdownMenuItem<String>> getDropDownMenuItems() {
List<DropdownMenuItem<String>> items = new List();
for (String kategori in _category) {
items.add(new DropdownMenuItem(
value: kategori,
child: new Text(kategori)
));
}
return items;
}
void changedDropDownItem(String selectedCategory) {
setState(() {
_currentCategory = selectedCategory;
});
}
// radio discount
void _handleRadioValueChange1(int value) {
setState(() {
_radioValue1 = value;
});
}
/// Display date picker.
void _showDatePicker() {
final bool showTitleActions = false;
DatePicker.showDatePicker(
context,
showTitleActions: true,
minYear: 2019,
maxYear: 2022,
initialYear: _year,
initialMonth: _month,
initialDate: _date,
confirm: Text(
'PILIH',
style: TextStyle(color: Colors.red),
),
cancel: Text(
'BATAL',
style: TextStyle(color: Colors.cyan),
),
locale: "en",
dateFormat: "dd-mm-yyyy",
onChanged: (year, month, date) {
//debugPrint('onChanged date: $year-$month-$date');
if (!showTitleActions) {
_changeDatetime(year, month, date);
}
},
onConfirm: (year, month, date) {
_changeDatetime(year, month, date);
},
);
}
void _changeDatetime(int year, int month, int date) {
setState(() {
_year = year;
_month = month;
_date = date;
_datetime = '$date-$month-$year';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Produk Entry'),
),
body: SafeArea(
child: ListView(
padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
children: <Widget>[
// text field
TextField(
controller: _nomerRakController,
decoration: InputDecoration(
filled: false,
labelText: 'Nomer Rak',
),
),
// spacer
SizedBox(height: 5.0),
// text field
TextField(
controller: _namaProdukController,
decoration: InputDecoration(
filled: false,
labelText: 'Nama Produk',
),
),
// Dropdown
new Container(
padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Text("Kategori: ", style: new TextStyle(fontSize: 15.0)),
new DropdownButton(
value: _currentCategory,
items: _dropDownMenuItems,
onChanged: changedDropDownItem,
)
],
),
),
// datepicker
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
RaisedButton(
child: Text('Expired Date', style: new TextStyle(fontSize: 15.0)),
onPressed: () {
_showDatePicker();
},
),
new Text(" $_datetime", style: new TextStyle(fontSize: 15.0)),
],
),
),
// QR scanner
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
RaisedButton(
child: Text(' Scan Code ', style: new TextStyle(fontSize: 15.0)),
onPressed: () {
_scanQR();
},
),
new Text(" $_scanResult", style: new TextStyle(fontSize: 15.0)),
],
),
),
// Radio
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Radio(
value: 0,
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Discount',
style: new TextStyle(fontSize: 15.0),
),
new Radio(
value: 1,
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Non Discount',
style: new TextStyle(fontSize: 15.0),
),
],
),
),
// button
RaisedButton(
child: Text('SIMPAN'),
onPressed: () {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text the user has typed in using our
// TextEditingController
content: Text('Nomer Rak: ${_nomerRakController.text}\n'+
'Produk: ${_namaProdukController.text}\n'+
'Kategori: $_currentCategory\n' +
'Expired Date: $_datetime\n' +
'Radio: $_radioValue1'),
);
},
);
},
),
],
)
),
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entry Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new EntryData(),
);
}
}
Entry Data
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Response {
final String status;
final String message;
Response({this.status, this.message});
factory Response.fromJson(Map<String, dynamic> json) {
return Response(
status: json['status'],
message: json['message'],
);
}
}
Future<Response> post(String url,var body)async{
return await http
.post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
.then((http.Response response) {
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while fetching data");
}
return Response.fromJson(json.decode(response.body));
});
}
class EntryData extends StatefulWidget {
@override
EntryDataState createState() => new EntryDataState();
}
class EntryDataState extends State<EntryData> {
// text field
final _nomerRakController = TextEditingController();
final _namaProdukController = TextEditingController();
// dropdown category
List _category = ["Buah-buahan", "Snack", "Stationary", "Baju", "Ice Cream"];
List<DropdownMenuItem<String>> _dropDownMenuItems;
String _currentCategory;
// datepicker
String _datetime = '';
int _year = 2018;
int _month = 11;
int _date = 11;
// radio
String _radioValue1;
// scanner
String _scanResult = '';
// member simpan data
String _response = '';
bool apiCall = false;
@override
void initState() {
super.initState();
// dropdown category
_dropDownMenuItems = getDropDownMenuItems();
_currentCategory = _dropDownMenuItems[0].value;
// datepicker
DateTime now = DateTime.now();
_year = now.year;
_month = now.month;
_date = now.day;
}
// widget simpan data
Widget getProperWidget(){
if(apiCall)
return AlertDialog(
content: new Column(
children: <Widget>[
CircularProgressIndicator(),
Text("Please wait")
],
)
);
else
return Center(
child: Text(
_response,
style: new TextStyle(fontSize: 15.0)
)
);
}
void _callPostAPI() {
post(
"http://192.3.168.178/restapi/addproduct.php",
{
"nomor_rak": _nomerRakController.text,
"nama_produk": _namaProdukController.text,
"kategori": _currentCategory,
"expired_date": _datetime,
"scan_code": _scanResult,
"discount": _radioValue1
}).then((response) {
setState(() {
apiCall = false;
_response = response.message;
});
},
onError: (error) {
apiCall = false;
_response = error.toString();
}
);
}
// dropdown category
List<DropdownMenuItem<String>> getDropDownMenuItems() {
List<DropdownMenuItem<String>> items = new List();
for (String kategori in _category) {
items.add(new DropdownMenuItem(
value: kategori,
child: new Text(kategori)
));
}
return items;
}
void changedDropDownItem(String selectedCategory) {
setState(() {
_currentCategory = selectedCategory;
});
}
// radio discount
void _handleRadioValueChange1(String value) {
setState(() {
_radioValue1 = value;
});
}
/// Display date picker.
void _showDatePicker() {
final bool showTitleActions = false;
DatePicker.showDatePicker(
context,
showTitleActions: true,
minYear: 2019,
maxYear: 2022,
initialYear: _year,
initialMonth: _month,
initialDate: _date,
confirm: Text(
'PILIH',
style: TextStyle(color: Colors.red),
),
cancel: Text(
'BATAL',
style: TextStyle(color: Colors.cyan),
),
locale: "en",
dateFormat: "dd-mm-yyyy",
onChanged: (year, month, date) {
//debugPrint('onChanged date: $year-$month-$date');
if (!showTitleActions) {
_changeDatetime(year, month, date);
}
},
onConfirm: (year, month, date) {
_changeDatetime(year, month, date);
},
);
}
void _changeDatetime(int year, int month, int date) {
setState(() {
_year = year;
_month = month;
_date = date;
_datetime = '$date-$month-$year';
});
}
// scan QR
Future _scanQR() async {
try {
String qrResult = await BarcodeScanner.scan();
setState(() {
_scanResult = qrResult;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
_scanResult = "Camera permission was denied";
});
} else {
setState(() {
_scanResult = "Unknown Error $ex";
});
}
} on FormatException {
setState(() {
_scanResult = "You pressed the back button before scanning anything";
});
} catch (ex) {
setState(() {
_scanResult = "Unknown Error $ex";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Produk Entry'),
),
body: SafeArea(
child: ListView(
padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
children: <Widget>[
// text field
TextField(
controller: _nomerRakController,
decoration: InputDecoration(
filled: false,
labelText: 'Nomer Rak',
),
),
// spacer
SizedBox(height: 5.0),
// text field
TextField(
controller: _namaProdukController,
decoration: InputDecoration(
filled: false,
labelText: 'Nama Produk',
),
),
// Dropdown
new Container(
padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Text("Kategori: ", style: new TextStyle(fontSize: 15.0)),
new DropdownButton(
value: _currentCategory,
items: _dropDownMenuItems,
onChanged: changedDropDownItem,
)
],
),
),
// datepicker
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
RaisedButton(
child: Text('Expired Date', style: new TextStyle(fontSize: 15.0)),
onPressed: () {
_showDatePicker();
},
),
new Text(" $_datetime", style: new TextStyle(fontSize: 15.0)),
],
),
),
// QR scanner
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
RaisedButton(
child: Text(' Scan Code ', style: new TextStyle(fontSize: 15.0)),
onPressed: () {
_scanQR();
},
),
new Text(" $_scanResult", style: new TextStyle(fontSize: 15.0)),
],
),
),
// Radio
new Container(
//padding: EdgeInsets.all(10.0),
//color: Colors.blueGrey,
child: new Row(
children: <Widget>[
new Radio(
value: "Discount",
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Discount',
style: new TextStyle(fontSize: 15.0),
),
new Radio(
value: "Non Discount",
groupValue: _radioValue1,
onChanged: _handleRadioValueChange1,
),
new Text(
'Non Discount',
style: new TextStyle(fontSize: 15.0),
),
],
),
),
// button
RaisedButton(
child: Text('SIMPAN'),
onPressed: () {
setState((){
apiCall=true; // Set state like this
});
_callPostAPI();
},
),
// POST Response
getProperWidget(),
],
)
),
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entry Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new EntryData(),
);
}
}
Entry + View
entry.dart
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Product {
final String id;
final String nomorRak;
final String namaProduk;
final String kategori;
final String expiredDate;
final String scanCode;
final String discount;
Product({this.id, this.nomorRak, this.namaProduk, this.kategori,
this.expiredDate, this.scanCode, this.discount});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
nomorRak: json['nomor_rak'],
namaProduk: json['nama_produk'],
kategori: json['kategori'],
expiredDate: json['expired_date'],
scanCode: json['scan_code'],
discount: json['discount'],
);
}
}
List<Product> parseProduct(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
Future<List<Product>> fetchProduct(http.Client client) async {
final response =
await client.get('http://192.3.168.178/restapi/getproduct.php');
// Use the compute function to run parsePhotos in a separate isolate
return compute(parseProduct, response.body);
}
class ProductListBuilder extends StatelessWidget {
final List<Product> products;
ProductListBuilder({Key key, this.products}) : super(key: key);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
"Nama Produk: ${products[index].namaProduk}\n"+
"Nomor Rak: ${products[index].nomorRak}\n"+
"Kategori: ${products[index].kategori}\n"+
"Expired Date: ${products[index].expiredDate}\n"+
"Scan code: ${products[index].scanCode}\n"+
"Discount: ${products[index].discount}\n"
),
);
}
);
}
}
class ListProduct extends StatefulWidget {
@override
ListProductState createState() => new ListProductState();
}
class ListProductState extends State<ListProduct> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Product List"),
),
body: FutureBuilder<List<Product>>(
future: fetchProduct(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ProductListBuilder(products: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'entry.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entry Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
//home: new EntryData(),
home: new ListProduct(),
);
}
}
Cupertino Ios Style
Tugas Akhir Eudeka
convert json to dart
https://db.ygoprodeck.com/api/v5/cardinfo.php?num=100
mod_card.dart
class mod_card {
String id;
String name;
String type;
String desc;
String race;
String archetype;
List<CardSets> cardSets;
List<CardImages> cardImages;
CardPrices cardPrices;
mod_card(
{this.id,
this.name,
this.type,
this.desc,
this.race,
this.archetype,
this.cardSets,
this.cardImages,
this.cardPrices});
mod_card.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
type = json['type'];
desc = json['desc'];
race = json['race'];
archetype = json['archetype'];
if (json['card_sets'] != null) {
cardSets = new List<CardSets>();
json['card_sets'].forEach((v) {
cardSets.add(new CardSets.fromJson(v));
});
}
if (json['card_images'] != null) {
cardImages = new List<CardImages>();
json['card_images'].forEach((v) {
cardImages.add(new CardImages.fromJson(v));
});
}
cardPrices = json['card_prices'] != null
? new CardPrices.fromJson(json['card_prices'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['type'] = this.type;
data['desc'] = this.desc;
data['race'] = this.race;
data['archetype'] = this.archetype;
if (this.cardSets != null) {
data['card_sets'] = this.cardSets.map((v) => v.toJson()).toList();
}
if (this.cardImages != null) {
data['card_images'] = this.cardImages.map((v) => v.toJson()).toList();
}
if (this.cardPrices != null) {
data['card_prices'] = this.cardPrices.toJson();
}
return data;
}
}
class CardSets {
String setName;
String setCode;
String setRarity;
String setPrice;
CardSets({this.setName, this.setCode, this.setRarity, this.setPrice});
CardSets.fromJson(Map<String, dynamic> json) {
setName = json['set_name'];
setCode = json['set_code'];
setRarity = json['set_rarity'];
setPrice = json['set_price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['set_name'] = this.setName;
data['set_code'] = this.setCode;
data['set_rarity'] = this.setRarity;
data['set_price'] = this.setPrice;
return data;
}
}
class CardImages {
String id;
String imageUrl;
String imageUrlSmall;
CardImages({this.id, this.imageUrl, this.imageUrlSmall});
CardImages.fromJson(Map<String, dynamic> json) {
id = json['id'];
imageUrl = json['image_url'];
imageUrlSmall = json['image_url_small'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['image_url'] = this.imageUrl;
data['image_url_small'] = this.imageUrlSmall;
return data;
}
}
class CardPrices {
String cardmarketPrice;
String tcgplayerPrice;
String ebayPrice;
String amazonPrice;
CardPrices(
{this.cardmarketPrice,
this.tcgplayerPrice,
this.ebayPrice,
this.amazonPrice});
CardPrices.fromJson(Map<String, dynamic> json) {
cardmarketPrice = json['cardmarket_price'];
tcgplayerPrice = json['tcgplayer_price'];
ebayPrice = json['ebay_price'];
amazonPrice = json['amazon_price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['cardmarket_price'] = this.cardmarketPrice;
data['tcgplayer_price'] = this.tcgplayerPrice;
data['ebay_price'] = this.ebayPrice;
data['amazon_price'] = this.amazonPrice;
return data;
}
}
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:tugasakhir/model/mod_card.dart';
List<mod_card> parseCards(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<mod_card>((json) => mod_card.fromJson(json)).toList();
}
Future<List<mod_card>> fetchCards(http.Client client) async {
final response =
await client.get('https://db.ygoprodeck.com/api/v5/cardinfo.php?num=100');
return compute(parseCards, response.body);
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'List Card';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<mod_card>>(
future: fetchCards(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
// ? TitleList(cards: snapshot.data)
? PhotosList(cards: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class TitleList extends StatelessWidget {
final List<mod_card> cards;
TitleList({Key key, this.cards}) : super(key: key);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: cards.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(cards[index].name),
trailing: new Image.network(cards[index].cardImages[0].imageUrlSmall),
);
}
);
}
}
class PhotosList extends StatelessWidget {
final List<mod_card> cards;
PhotosList({Key key, this.cards}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: cards.length,
itemBuilder: (context, index) {
return Image.network(cards[index].cardImages[0].imageUrlSmall);
},
);
}
}
Latihan Flutter
By Maulana Ilham
Latihan Flutter
Latihan Flutter
- 1,220