How to make the text field accept other language flutter - 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'));

Related

When tap on textfield, app crashes returns homepage

Hi I get an error when user focus textfield, app crashes and returns to homepage (see clip here https://www.screencast.com/t/yiJkCBsibcoY)
I've had this error for a while now and cannot seem to fix it, sometimes it happens on other textfields. I cannot replicate the issue only sent from users. Anyone experience this with flutter?
Widget searchBox() {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
border: Border.all(color: Color(0xff0F004E), width: 1.0),
),
child: SimpleAutoCompleteTextField(
key: keyAuto,
controller: textController,
suggestions: suggestions,
textChanged: (text) => searchProduct = text,
textSubmitted: (text) {
loadingBarActive = true;
_sendAnalyticsEvent(text, 'serach_food_action');
searchProduct = text.replaceAll(new RegExp(r'[^\w\s]+'), '');
print('searchProduct RegX $searchProduct');
newSearch = true;
_filterCategories(searchProduct);
_filterRecipes(searchProduct);
// reset search values to intial
usdaItems.clear();
usda!.clear();
perPage = perPageIntial;
present.value = 0;
loadingBarActive = false;
selectApi = <int, Widget>{
0: allProductTab(),
1: allProductTab(),
2: allProductTab(),
3: allProductTab(),
};
setState(() {
_loadUSDAlist = usdaFoodProductList();
_loadOpenList = openFoodProductList();
});
},
style: TextStyle(
fontFamily: 'Nunito', fontSize: 20.0, color: Color(0xff0F004E)),
decoration: InputDecoration(
border: InputBorder.none,
// contentPadding: EdgeInsets.only(top: 14.0),
hintText: 'Search',
hintStyle: TextStyle(
fontFamily: 'Nunito', fontSize: 16.0, color: Color(0xff0F004E)),
prefixIcon: Icon(Icons.search, color: Color(0xff0F004E)),
suffixIcon: IconButton(
icon: Icon(Icons.close, color: Color(0xff0F004E)),
onPressed: () {
textController.clear();
})),
),
);
}
I had exactly the same issue and was literally going crazy trying to find the solution. For me the error originated in my usage of the GetX state management library. For me the issue was solved by replacing this:
Get.to(ReservationDetails(res: Reservation.empty()))
?.then(((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
})));
with:
Navigator.push(context,
MaterialPageRoute(
builder: ((context) =>
ReservationDetails(res: Reservation.empty()))))
.then((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
}));
I suggest you have a look at how you are opening the page you are experiencing this issue.

How to set Visibility function in flutter to show or hide Text Form Field?

I want to set an option in my Trivia game to the user set a Text Field in specific question ID.
for now I trying to use Visibility widget but its only take the bool _visibleText value,
And does not get the value from void validateText.
any idea what I missing?
this is my code:
class _QuestionCardState extends State<QuestionCard> {
bool _visibleText = false;
void validateText() => setState(() {
if (widget.question.id == 1) {
_visibleText = false;
} else {
if (widget.question.id == 2) {
_visibleText = true;
}
}
});
and the widget:
Visibility(
visible: (_visibleText),
child: Container(
width: 320.0,
alignment: Alignment.center,
child: TextFormField(
textAlign: TextAlign.center,
decoration: InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide:
const BorderSide(color: Color(0xFFCBA583), width: 2.0),
borderRadius: BorderRadius.all(
Radius.circular(12),
),
),
filled: true,
fillColor: Colors.white,
hintText: widget.question.text,
hintStyle: TextStyle(
fontSize: 16.0,
color: Color(0xFF067751),
fontFamily: 'Calibri',
letterSpacing: 2,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
),
),
),
),
Solved by using this function:
bool validateText() {
if (widget.question.id == 2) {
return true;
}
return false;
}
If you need to continuously toggle visibility during the game, please use streambuilder and leave your validatetext function inside streambuilder's sink method. Then streamcontroller will continuously change your UI dynamically.
If you don't understand at all, then please mention that , I will try to add the full codebase.
Thank You.
validateText is never called.
Change the function to this :
bool validateText() {
if (widget.question.id == 1) return false;
if (widget.question.id == 2) return true;
}
And in your build method :
visible: validateText(),
The validateText function is never called. If you have a button that toggles this then call it in it's onTap event.

Flutter: TextField auto add a dot when input multiple spaces

I just implement a simple TextField, but when I input multiple spaces, it auto add a dot before that.
my-custom-flutter-textfield
Here is my custom TextField widget
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(5),
child: Column(children: [
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(bottom: 5),
child: Text(
title,
),
)),
TextField(
controller: _controller,
autocorrect: false,
decoration: InputDecoration(
isDense: true,
contentPadding: const EdgeInsets.all(10),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.black,
width: 2,
),
borderRadius: BorderRadius.circular(5),
),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.orange,
width: 2,
),
borderRadius: BorderRadius.circular(5),
),
))
]));
}
This is a standard function of the iOS keyboard and most Android keyboards. I don't think you can control that from Flutter.
I don't think that has anything to do with the app itself, but the phone. You'd need to disable that from the phone's settings.
Although, if you really need to be able to type double spaces, here is how I'd implement it.
final TextEditingController controller = TextEditingController();
TextSelection? cursor;
int length = 0;
String lastChar = '';
String currentChar = '';
String replaceCharAt(String oldString, int index, String newChar) {
// function from https://stackoverflow.com/questions/52083836/how-to-replace-only-one-character-in-a-string-in-dart
return oldString.substring(0, index) +
newChar +
oldString.substring(index + 1);
}
void removeDotOnSpace(String input) {
//save the position of the cursor
cursor = controller.selection;
lastChar = currentChar;
// if the input isn't empty and if you're not removing text
if (input.isNotEmpty && input.length > length) {
currentChar = input[input.length - 1];
// if it has at least two characters, the second to last being a dot and the "lastChar" variable not being a dot
if (input.length >= 2 &&
input[input.length - 2] == '.' &&
lastChar != '.') {
// replace the dot and set state. Because setstate resests cursor position we need to save it and give it back.
setState(() {
controller.text = replaceCharAt(input, input.length - 2, ' ');
controller.selection = cursor!;
});
}
} else {
currentChar = '';
lastChar = '';
}
length = input.length;
}
Put this inside a stateful widget and use it inside the onchanged function
TextFormField(
controller: controller,
onChanged: (value) {
removeDotOnSpace(value);
},
),
PS: Unless it's essential for your textfields to be able to have double spaces, you should just let it be.
try textCapitalization: TextCapitalization.words,
put this function onBlur in form inputs:
const handleTrimDataAndRemoveDot = () => {
const trimmedData = formData.trim();
let validatedData;
if (trimmedData.charAt(trimmedData.length - 1) === ".") {
validatedData = trimmedData.replace(
trimmedData.charAt(trimmedData.length - 1),
""
);
} else {
validatedData = trimmedData;
}
setFormData(validatedData);
};

How to add cursor For PinFieldAutoFill flutter

There is no cursor while entering OTP, How can add Cursor in pinFieldAutoFill. I am using the sms_autofill: ^1.2.5 package.
PinFieldAutoFill(
autofocus: true,
keyboardType: TextInputType.number,
decoration: UnderlineDecoration(
textStyle: TextStyle(
fontSize: 44.sp,
fontWeight: FontWeight.bold,
color: kDarkBlue),
colorBuilder: FixedColorBuilder(
Colors.grey),
),
currentCode: authService
.loginMobileOTP, // prefill with a code
onCodeSubmitted: (_) async {
authService.login(
context, _scaffoldKey);
},
onCodeChanged: (value) {
authService.loginMobileOTP =
value;
},
codeLength:
6 //code length, default 6
),
Please enable cursor option in "sms_autofill" package, class constructer "PinInputTextField".
Sharing reference code
return PinInputTextField(
pinLength: widget.codeLength,
decoration: widget.decoration,
cursor: Cursor(
width: 2,
height: 40,
color: Colors.red,
radius: Radius.circular(1),
enabled: true,
),

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