Posts

Cara membuat Input and Selection pada Flutter

Bismillahirahmanirrahim

Postingan kali ini akan membahas tentang cara membuat Input and Selection pada Flutter

Berikut langkah – langkah membuat Input and Selection pada Flutter :

  • Buatlah projek yang akan ditambahkan Input and Selection
  • Buat dart.file untuk input Selection
  • Masukkan codingan berikut kedalam dart.file yang baru dibuat
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_day3/contact.dart';
import 'package:flutter_app_day3/contact_service.dart';
import 'package:intl/intl.dart';

class InputSelection extends StatefulWidget {
@override
_InputSelectionState createState() => _InputSelectionState();
}

class _InputSelectionState extends State<InputSelection> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
final GlobalKey<FormState> formKey = new GlobalKey<FormState>();

List<String> _colors = <String> ['', 'red', 'green', 'blue', 'orange'];
String _color = '';
TextEditingController _controller = new TextEditingController();
Contact newContact = new Contact();

Future<Null> _chooseDate(
BuildContext context, String initalDateString) async{
var now = new DateTime.now();
var initialDate = convertToDate(initalDateString) ?? now;
initialDate = (initialDate.year >= 1900 && initialDate.isBefore(now)
? initialDate
: now);
var result = await showDatePicker(context: context,
initialDate: initialDate,
firstDate: new DateTime(1900),
lastDate: new DateTime.now());

if (result == null) return;
setState(() {
_controller.text = new DateFormat.yMd().format(result);
});
}
bool isValidate(String dob){
if (dob.isEmpty) return true;
var d = convertToDate(dob);
return d != null && d.isBefore(new DateTime.now());
}

DateTime convertToDate(String input){
try{
var d = new DateFormat.yMd().parseStrict(input);
return d;
}catch (e){
return null;
}
}
bool isValidEmail(String input){
final RegExp regExp = new RegExp(r"^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)$");
return regExp.hasMatch(input);
}

showMessege(String messege, [MaterialColor color = Colors.red]){
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: Text(messege),
backgroundColor: color,
));
}

_submitForm(){
final FormState form = formKey.currentState;
if(!form.validate()){
showMessege('Form is not valid! plis review and correct');
}else{
form.save();
print('form save called, newContact is now up to date');
print('Name : ${newContact.name}');
print('Dob : ${newContact.dob}');
print('Email : ${newContact.email}');
print('Favorite Color : ${newContact.favoriteColor}');
print('================================================');
print('Subbmiting to back end.....');
var contactService = new ContactService();
contactService.createAccount(newContact).then((value)=> showMessege('new contact create for ${value.name}!', Colors.blue));
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: SafeArea(
bottom: false,
top: false,
child: Form(
key: formKey,
child: ListView(
padding: EdgeInsets.all(16),
children: <Widget>[
TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.person),
hintText: 'Enter your firs and latname',
labelText: 'name'
),
inputFormatters: [
new LengthLimitingTextInputFormatter(30)
],
validator: (val) => val.isEmpty ? 'name is require' : null,
onSaved: (val) => newContact.name = val,
),
Row(
children: <Widget>[
Expanded(child: TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.calendar_today),
hintText: 'Enter your date of birt',
labelText: 'dob'
),
controller: _controller,
validator: (val) => isValidate(val) ? null: 'Not a valid date',
onSaved: (val) => newContact.dob = convertToDate(val),
)),
IconButton(
icon: Icon(Icons.more_horiz),
onPressed: (){
_chooseDate(context, _controller.text);
},
)
],
),
TextFormField(
decoration: InputDecoration(
icon: Icon(Icons.email),
hintText: 'Enter in email address',
labelText: 'email'
),
inputFormatters: [
new LengthLimitingTextInputFormatter(30)
],
validator: (val) => isValidEmail(val)
? null
: 'plis enter a valid email address',
onSaved: (val) => newContact.email = val,
),
FormField<String>(
builder: (FormFieldState<String> state){
return InputDecorator(
decoration: InputDecoration(
icon: Icon(Icons.color_lens),
labelText: 'color',
errorText: state.hasError ? state.errorText : null,
),
isEmpty: _color == '',
child: DropdownButtonHideUnderline(child: DropdownButton(
value: _color,
items: _colors.map((String value){
return DropdownMenuItem(
value: value,
child: Text(value)
);
}).toList(),
onChanged: (String newValue){
newContact.favoriteColor = newValue;
_color = newValue;
state.didChange(newValue);
}),
),
);
},
validator: (val){
return val != '' ? null : 'please select a color';
},
),
Container(
padding: EdgeInsets.only(left: 40, top: 20),
child: RaisedButton(
child: Text('SUBMIT'), onPressed: _submitForm),
)
],
),
)
),
);
}
}
  • Panggil Inpu and Selection tersebut di main.dart
bottom: TabBar(
tabs: <Widget> [
Tab(
text: 'Input and Selection',
),
Tab(
text: 'Json Beranak',
),
Tab(
text: 'Portal Berita',
),
Tab(
text: 'Array',
),
],
controller: _tabController,
),
),
drawer: Drawer(

),
body: TabBarView(children: <Widget>[
InputSelection(),
JsonBeranak(),
PortalBerita(),
ListArray(),
],
controller: _tabController,
),
  • berikut tampilan ketika telah dijalankan

Sekian Postingan kali ini, semoga bermanfaat

1 Comment :

  1. Jaelani March 2, 2020 at 10:13 am

    Terima kasih banyak gan untuk tutorialnya, sangat bermanfaat.
    Ketika testing error file contact dan contact_service tidak ditemukan.

    Jika boleh tau isi file yang dibutuhkan tersebut seperti apa ya gan?

    Reply

Leave a Reply :

* Your email address will not be published.