Flutter Google Address Autofill - flutter

I want an up to date example on how to add autofill addresses in flutter. I have looked at every resource I can and some people over complicate the heck out of it,or just copy and paste different messy code.
Atm I have a Google search that just shows a blue line as if Its waiting and gets no response.
TextFormField(
controller: addressController,
onTap: () async {
Prediction p = PlacesAutocomplete.show(
context: context,
apiKey: "MY_API_KEY_SECRET_SHHHHHH",
mode: Mode.fullscreen,
language: "En",
components: [new Component(Component.country, "NZ")])
as Prediction;
displayPrediction(p);
},
validator: (value) {
if (value == null || value.isEmpty) {
return "Customer must have address! cannot be blank";
}
},
decoration: InputDecoration(
hintText: "Enter Customer Address",
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.map),
),
),
and I also have displayPrediction
Future<Null> displayPrediction(Prediction p) async {
GoogleMapsPlaces _places = GoogleMapsPlaces(
apiKey: "API_KEY",
apiHeaders: await GoogleApiHeaders().getHeaders(),
);
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(p.placeId.toString());
final lat = detail.result.geometry!.location.lat;
final lng = detail.result.geometry!.location.lng;
}
Broken Search Example

So my problem was solved within the Prediction method. here is how I solved it with help from other resources.
Prediction? p = await PlacesAutocomplete.show(
context: context,
apiKey: kGoogleApiKey,
radius: 10000000,
types: [],
strictbounds: false,
mode: Mode.overlay,
decoration: InputDecoration(
hintText: 'Search',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: BorderSide(
color: Colors.white,
),
),
),
components: [Component(Component.country, "nz")],
);

Related

How to make the text field accept other language flutter

The Problem
When I try to type Arabic it just don't show. I tried to look for answer but most what I found how to make the whole app in different language.
Code
Form(
key: _formKey,
child: Container(
width: width-80,
child: TextFormField(
//for disable for the done button
controller: titleControl,
onChanged: (val) {
/*change the val of title*/
setState(() {
title = val;
});
},
/*validation*/
validator: (val) {
if (val!.isEmpty) {
return "Title should not be empty";
}
if (val.length >= 35) {
return "Create a shorter title under 36 characters.";
}
if ((val.contains("*") ||
val.contains("\\")||
val.contains("%") ||
val.contains("~") ||
val.contains("^") ||
val.contains("+") ||
val.contains("=") ||
val.contains("{") ||
val.contains("[") ||
val.contains("}") ||
val.contains("]") ||
val.contains(":") ||
val.contains(";") ||
val.contains("\\")||
val.contains("<") ||
val.contains(">") )) {
return "Title should not contain symbol. Only ',?!_-&##.";
}
return null;
},
decoration: const InputDecoration(
/*background color*/
fillColor: Palette.lightgrey,
filled: true,
contentPadding: const EdgeInsets.symmetric(
vertical: 1.0, horizontal: 10),
/*hint*/
border: OutlineInputBorder(),
hintText: "Title",
hintStyle: TextStyle(fontSize: 18.0,
color: Palette.grey,
height: 2.0,),
/*Border*/
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Palette.midgrey,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Palette.midgrey,
width: 2.0,
),
),
),
),
),
),
/*end of title*/
What I tried
I follow video to make the whole app in another language.
In pubspec.yaml:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0
#...
flutter:
generate: true
In the main:
supportedLocales: L10n.all,
Created L10n that look like this:
import 'package:flutter/material.dart';
class L10n {
static final all = [
const Locale('en'),
const Locale('ar'),
const Locale('hi'),
const Locale('es'),
const Locale('de'),
];
}
Then I realize this was not my issues I don't want to make the whole app in another language I just want to make the text filed accept Arabic.
I use translator pachege
final translator = GoogleTranslator();
final input = "Здравствуйте. Ты в порядке?";
translator.translate(input, from: 'ru', to: 'en').then(print);
// prints Hello. Are you okay?
var translation = await translator.translate("Dart is very cool!", to:
'pl');
print(translation);
// prints Dart jest bardzo fajny!
print(await "example".translate(to: 'pt'));

Flutter focusnode problem not working - only by clicking it works

iam using a device that scans barcode , I want after each read the focus to return the TextFormFiled - the code below do the work and I see the cursor is focused on the TextFormFiled but when I read next time its show nothing , I need to manually just click by my finger on the textfiled to activate the focus ,can somebody help me ( the device returned LF after each read)
TextFormField(
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
),
filled: true,
hintStyle: new TextStyle(
color: Colors.grey[800]),
hintText: "Read BarCode",
fillColor: Colors.white70),
focusNode: myFocusNode,
controller: search,
autofocus: true,
maxLines: null,
validator: (value) {
// print(value.toString().runes);
if (value.toString().contains("\n")) {
fetchProducts(value!);
search.text = "";
} else {}
},
),
Use your myFocusNode to activate the focus on textField.
void function(){
/// after scanning is complete call this
focusNode.requestFocus()
}
I pass for this and did solve it like this:
_addItem() {
final isValid = _formKey.currentState?.validate() ?? false;
if (!isValid) {
return;
}
final ean = int.parse(_eanController.text);
listaEan.add(ean);
_eanController.text = '';
setState(() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
_eanFocus.requestFocus();
});
});
}
but in physical scan device, did works fine. without use the addPostFramaCallback.

Searchbox with filter in flutter

I have a question regarding this library https://pub.dev/packages/dropdown_search. I am trying to implement dropdown with searchbox, whenever I type in any value it doesn't show in the box and nothing is being returned in dropdown. How can I set this up properly?
DropdownSearch(
mode: Mode.MENU,
dropdownSearchDecoration: InputDecoration(
fillColor: Colors.white,
filled: true,
border: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xFF01689A)),
),
),
showAsSuffixIcons: true,
showClearButton: true,
items: _countryList.map((Country item) {
return item.label;
}).toList()
),
It is because of searchDelay field. When you make it 0 seconds it will work properly and become instant search.
DropdownSearch<String>(
searchDelay: Duration(milliseconds: 0),
showSearchBox: true,
showClearButton: true,
mode: Mode.MENU,
showSelectedItems: true,
items: transactionState.drop,
label: "Cari Hesap",
hint: "Cari Hesap Girin",
selectedItem: transactionState.selecteditem,
//popupItemDisabled: (String s) => s.startsWith('I'),
onChanged: (str){
transactionState.getBakiye(str!);
transactionState.selecteditem = str;
},
),

Cannot update DropdownButtonFormField field value in flutter with getx obs

I am using getx obs with fluter and the below is json response.
[{"id":1,"designation":"Deputy General Manager"},{"id":2,"designation":"Executive Director, Technical Operations","designation_short_code":"ED, TO"},{"id":3,"designation":"Manager","designation_short_code":"M"},{"id":4,"designation":"Sr. Manager","designation_short_code":"Sr. M"}]
In controller I am using--
var listData = List<dynamic>.empty(growable: true).obs;
var designation = 1.obs;
void setDesignation(int value) {
designation.value = value;
}
I am getting the above json response based on api call under listData.
In UI I am using the below code..
Obx(() => DropdownButtonFormField<dynamic>(
decoration: InputDecoration(
hintText: 'Designation',
labelText: 'Select Designation',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
fillColor: Colors.white,
errorStyle: TextStyle(color: Colors.yellow),
),
hint: Text(
'Select Designation',
),
onChanged: (selectedValue) {
designation_controller
.setDesignation(selectedValue);
},
value:
designation_controller.designation.value.toInt(),
items: designation_controller.listData.map((map) {
return DropdownMenuItem(
child: Text(map['designation']),
value: map['id'],
);
}).toList(),
)),
My problem is whenever I select designation it is not updating though my api end point is hitting with 200 response.
Can anyone help me please.
Thanks in advnace.
I have fixed problem. My problem was in the below code
updateData(
controller.userData[0]['id'],
controller.designationEdittingTextController.text
)
I have changed controller.designationEdittingTextController.text to controller.designationEdit.value as below
updateData(
controller.userData[0]['id'],
controller.designationEdit.value
)
Thanks

Resetting TextfieldController for all textfields, using provider

I'm having a problem trying to figuring out the proper way on how to do this. Basically in my app, I want to reset all the fields for "cleanup" by the user. I can reset everything, but the TextFields. The only way that I found to solve the problem is by using the if that you can see inside the Consumer. I don't think though it's the proper way on how to handle this type of thing.
I also thought to push inside my provider class all the controller and then reset them, but I think it's still too heavy. I'm trying to find the cleanest and lightest solution, even to learn what's the best practice in these situations.
Thanks in advance!
return Provider.of<Provider_Class>(context, listen: false).fields[_label] != null ? SizedBox(
height: 57.5,
child: Consumer<Provider_Class>(builder: (context, provider, child) {
if (provider.resetted == true) {
_controller.text = "";
}
return Material(
elevation: this.elev,
shadowColor: Colors.black,
borderRadius: new BorderRadius.circular(15),
animationDuration: new Duration(milliseconds: 500),
child: new TextField(
focusNode: _focusNode,
keyboardAppearance: Brightness.light,
style: Theme.of(context).textTheme.headline5,
controller: _controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.end,
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(8),
_whichLabel(widget.label),
],
decoration: new InputDecoration(
enabledBorder: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(15),
borderSide: new BorderSide(width: 1.2, color: CliniLiliac300),
),
focusedBorder: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(15),
borderSide: new BorderSide(width: 2.5, color: CliniLiliac300),
),
filled: true,
fillColor: Colors.white,
hintText: "0.0",
hintStyle: new TextStyle(fontSize: 15, color: Colors.black, fontFamily: "Montserrat"),
),
onChanged: (val) {
var cursorPos = _controller.selection;
val = val.replaceAll(",", ".");
if (val == "") {
provider.fields[_label] = 0.0;
} else if (double.parse(val) > provider.measure[_label] &&
provider.measure[_label] != 0) {
provider.fields[_label] % 1 == 0
? _controller.text = provider.fields[_label].toString().split(".")[0]
: _controller.text = provider.fields[_label].toString();
if (cursorPos.start > _controller.text.length) {
cursorPos = new TextSelection.fromPosition(
new TextPosition(offset: _controller.text.length),
);
}
_controller.selection = cursorPos;
} else {
provider.fields[_label] = double.parse(val);
}
provider.calculateResultRA();
},
),
);
}),
) : SizedBox();
}
Use TextFormField instead of TextField. TextFormField has several callbacks like validator, onSaved, onChanged, onEditingComplete, onSubmitted, ...
You can connect all your TextFormFields by wrapping it in a Form. This form should be given a GlobalKey so that you can identify the Form and call methods on FormState.
final _form = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
// ...
return Form(
key: _form,
child: // build Material with TextFormFields
);
}
Now to call onSaved on each TextFormField, you can call _form.currentState().save(). To reset every TextFormField you can call _form.currentState().reset().
You can get more information about how to build a Form and the functions you can call on FomState here:
https://flutter.dev/docs/cookbook/forms/validation
https://api.flutter.dev/flutter/widgets/FormState-class.html