how to get access to what textformfield shows - flutter

i have textformfield i want to get access to what it shows
like when i print 10000 i want it to show and separate the int like 10,000 , i can print it with regex but i want to show it in text form field too
here us what i got in terminal (left) and what it shows in text field (right)
enter image description here
and all i wanna do is show what is in terminal to text field\
.
if you need more information please let me know
here is my code
import 'package:flutter/material.dart';
class AddTransication extends StatefulWidget {
#override
_AddTransicationState createState() => _AddTransicationState();
}
class _AddTransicationState extends State<AddTransication> {
RegExp reg_ex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]},';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test Screen"),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () {},
child: Text("Save"),
shape: CircleBorder(side: BorderSide(color: Colors.transparent)),
),
],
),
body: SafeArea(
child: Form(
child: Column(
children: [emailField(reg_ex, mathFunc)],
),
),
),
);
}
Widget emailField(reg_ex, mathFunc) {
return TextFormField(
onChanged: (str) {
String result = str.replaceAllMapped(reg_ex, mathFunc);
print(' $result');
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
hintText: 'you#example.com',
),
);
}
}

You have to use TextEditingController class.
A controller for an editable text field.
Whenever the user modifies a text field with an associated TextEditingController, the text field updates value and the controller notifies its listeners. Listeners can then read the text and selection properties to learn what the user has typed or how the selection has been updated.
Refer : https://api.flutter.dev/flutter/widgets/TextEditingController-class.html
Please check the code, below I have updated it to work as per your question.
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: AddTransication(),
);
}
}
class AddTransication extends StatefulWidget {
#override
_AddTransicationState createState() => _AddTransicationState();
}
class _AddTransicationState extends State<AddTransication> {
final _controller = TextEditingController();
RegExp regex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]},';
void initState() {
super.initState();
}
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test Screen"),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () {},
child: Text("Save"),
shape: CircleBorder(side: BorderSide(color: Colors.transparent)),
),
],
),
body: SafeArea(
child: Form(
child: Column(
children: [emailField(regex, mathFunc)],
),
),
),
);
}
Widget emailField(regex, mathFunc) {
return TextFormField(
controller: _controller,
onChanged: (str) {
String text = str.replaceAll(",", "").replaceAllMapped(regex, mathFunc);
print(' $text');
_controller.value = _controller.value.copyWith(
text: text,
selection:
TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
hintText: 'you#example.com',
),
);
}
}

Related

how to show a text field when a specific radio button is selected in flutter?

I want that when I choose home then a text field appears on the screen to input some information.
I wrapped the text field with Visibility but it didn't work.
Container(
margin: const EdgeInsets.only(top: 220,left:0),
child: RadioListTile(
title: const Text('home'),
value: place.home,
groupValue: selacted,
onChanged: (place? value) {
if(place.home==selacted) {
setState(() {
isVisible = true;
selacted= value;
});
}
}
),
),
Container(
margin: const EdgeInsets.only(top: 300,left:0),
child: Visibility(
visible:isVisible,
child:const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
),
),
It seems you are comparing the previously selected value.
This should work:
setState(() {
_place = value;
_homeFieldVisible = value == Place.home;
});
Full code sample:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
enum Place { road, home, work }
class _HomePageState extends State<HomePage> {
Place? _place;
bool _homeFieldVisible = false;
void handleSelection(Place? value) {
setState(() {
_place = value;
_homeFieldVisible = value == Place.home;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
RadioListTile(
title: const Text('on the road'),
value: Place.road,
groupValue: _place,
onChanged: handleSelection,
),
RadioListTile(
title: const Text('at home'),
value: Place.home,
groupValue: _place,
onChanged: handleSelection,
),
if (_homeFieldVisible)
const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
RadioListTile(
title: const Text('at work'),
value: Place.work,
groupValue: _place,
onChanged: handleSelection,
),
],
),
),
),
);
}
}
Your onChanged method should be changed to the following.
onChanged: (place? value) {
setState(() {
selacted = value;
if (place.home == selacted) {
isVisible = true;
}
});
}

How to use GetX on a value?

I want to make a Password TextField in which the content visibility can be controlled by the suffix icon.
The code may like this:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(TestGetX());
}
class TestGetX extends StatelessWidget {
var eyeClosed = true.obs;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Test GetX"),
),
body: Align(
alignment: Alignment.center,
child: Padding(
padding: EdgeInsets.all(20),
child: TextFormField(
obscureText: eyeClosed.value,
decoration: InputDecoration(
icon: Icon(
Icons.security,
color: Colors.purple,
),
hintText: "Your Password",
hintStyle: TextStyle(color: Colors.grey),
suffix: Obx(
() => InkWell(
child: eyeClosed.value
? Icon(Icons.visibility_off, color: Colors.grey)
: Icon(Icons.visibility, color: Colors.purple),
onTap: () {
eyeClosed.value = !eyeClosed.value;
},
),
),
),
),
),
),
),
);
}
}
The suffix icon can be controlled by the Obx(), but the obscureText doesn't work. The direct way is to use Obx() on the TextFormField, but I don't think it is the best way.
Here is the result:
You need to wrap Obx() in TextFormField
Obx(() => TextFormField(...))
Create a controller for your login screen
class LoginController extends GetxController {
RxBool hidePassword = true.obs;
final passwordTextController = TextEditingController();
}
Extends your login screen widget from GetWidget
class LoginScreen extends GetWidget<LoginController> {
final LoginController controller = Get.find<LoginController>();
#override
Widget build(BuildContext context) {
return(); //Define your widget
}
}
Wrap your textfield in Obx(()=> )
Obx(() => FormBuilderTextField(
name: 'password',
controller: controller.passwordTextController,
obscureText: controller.hidePassword.value,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: controller.hidePassword.value ? Icon(Icons.visibility_off)
: Icon(Icons.visibility),
onPressed: () {
controller.hidePassword.value = !controller.hidePassword.value;
},
),
),
),
I have tried with your code & works fine with a little bit change
class LoginPage extends GetView<LoginController>
Also wrap the whole textFormField in Obx(()=>)
i extend a controller for taking values & calling methods in Getx.i can share my full code if you need.
You should use StatefulWidget when your state is changing. Plus, you can reach the same result you want, without "Get" package.
I show you an example here:
import 'package:flutter/material.dart';
class Example extends StatefulWidget {
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
bool hidePassword = true;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextFormField(
obscureText: hidePassword, // which is true by default
decoration: InputDecoration(
hintText: "Enter Password",
suffixIcon: IconButton(
icon: hidePassword == false
? Icon(
Icons.visibility_rounded,
color: Colors.purple,
)
: Icon(
Icons.visibility_off_rounded,
color: Colors.grey,
),
onPressed: () {
setState(() {
// here we change the value
// if it's false, it gets true
// and if it's true, it gets false
hidePassword = !hidePassword;
});
},
),
),
),
),
),
);
}
}

connect to open wireless by using wifi_configuration Flutter

may i ask how to connect to an open hotspot - wireless- by using wifi_configuration package
cause i just found a method that allow to connect to encrypted wireless networks.
WifiConfiguration.connectToWifi("wirelessname","wirelesspassword","packagename");
inside WifiConfiguration class there is just one method that can be used for connecting.
is there any other library that can connect to an open hotspot or is there a way to do that by using wifi_configuration library ?
Apple mentioned that we need just two parameters to pass which is of course the ssid and the packagename
init(ssid: String)
Creates a new hotspot configuration, identified by an SSID, for an open Wi-Fi network.
i override the method connectToWifi to receive just one parameter but this didn't work.
thanks in advance
You can copy paste run full code below
You can use package https://pub.dev/packages/wifi_utils
You can call Wifi.connection and provide ssid and password
code snippet
import 'package:wifi/wifi.dart';
...
Future<Null> connection() async {
Wifi.connection(ssid, password).then((v) {
print(v);
});
}
working demo
full code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wifi/wifi.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Wifi',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _wifiName = 'click button to get wifi ssid.';
int level = 0;
String _ip = 'click button to get ip.';
List<WifiResult> ssidList = [];
String ssid = '', password = '';
#override
void initState() {
super.initState();
loadData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Wifi'),
centerTitle: true,
),
body: SafeArea(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
itemCount: ssidList.length + 1,
itemBuilder: (BuildContext context, int index) {
return itemSSID(index);
},
),
),
);
}
Widget itemSSID(index) {
if (index == 0) {
return Column(
children: [
Row(
children: <Widget>[
RaisedButton(
child: Text('ssid'),
onPressed: _getWifiName,
),
Offstage(
offstage: level == 0,
child: Image.asset(
level == 0 ? 'images/wifi1.png' : 'images/wifi$level.png',
width: 28,
height: 21),
),
Text(_wifiName),
],
),
Row(
children: <Widget>[
RaisedButton(
child: Text('ip'),
onPressed: _getIP,
),
Text(_ip),
],
),
TextField(
decoration: InputDecoration(
border: UnderlineInputBorder(),
filled: true,
icon: Icon(Icons.wifi),
hintText: 'Your wifi ssid',
labelText: 'ssid',
),
keyboardType: TextInputType.text,
onChanged: (value) {
ssid = value;
},
),
TextField(
decoration: InputDecoration(
border: UnderlineInputBorder(),
filled: true,
icon: Icon(Icons.lock_outline),
hintText: 'Your wifi password',
labelText: 'password',
),
keyboardType: TextInputType.text,
onChanged: (value) {
password = value;
},
),
RaisedButton(
child: Text('connection'),
onPressed: connection,
),
],
);
} else {
return Column(children: <Widget>[
ListTile(
leading: Image.asset('images/wifi${ssidList[index - 1].level}.png',
width: 28, height: 21),
title: Text(
ssidList[index - 1].ssid,
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
),
),
dense: true,
),
Divider(),
]);
}
}
void loadData() async {
Wifi.list('').then((list) {
setState(() {
ssidList = list;
});
});
}
Future<Null> _getWifiName() async {
int l = await Wifi.level;
String wifiName = await Wifi.ssid;
setState(() {
level = l;
_wifiName = wifiName;
});
}
Future<Null> _getIP() async {
String ip = await Wifi.ip;
setState(() {
_ip = ip;
});
}
Future<Null> connection() async {
Wifi.connection(ssid, password).then((v) {
print(v);
});
}
}

Custom Validation TextFormField Flutter

I have Form and TextFormField inside it :
new Expanded(
child: TextFormField(
style: new TextStyle(color: Colors.white),
keyboardType: TextInputType.text,
validator: (String value) {
if (value.length <= 5) {
//Show error as a Snackbar
}
},
onSaved: (String value) {},
),
)
On a Buttom press I am checking if all the fields are validate :
if (_formKey.currentState.validate()) {
_submit();
}
Now the issue is when you call validate() and don't return any text in validate() method then it will consider it return true.
I don't want to show error below the textField but as a Snackbar.
Also, I tried setting an extra flag and setting in each validator Method but it gets complex if there are multiple fields in the form.
Can anyone tell me how can I handle this situation where _formKey.currentState.validate() should return false and validator method
inside TextFormField need not to return error text.
You shouldn't be using Form widget and TextFormField for displaying error in TextField.
Do validation by controllers instead
For Example
class MyHomePage extends StatefulWidget {
#override
MyHomePageState createState() {
return new MyHomePageState();
}
}
class MyHomePageState extends State<MyHomePage> {
final _text = TextEditingController();
bool _validate = false;
#override
void dispose() {
_text.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TextField Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Error Showed if Field is Empty on Submit button Pressed'),
TextField(
controller: _text,
decoration: InputDecoration(
labelText: 'Enter the Value',
),
),
RaisedButton(
onPressed: () {
if(_text.text.length<=5){
// open dialog
}
},
child: Text('Submit'),
textColor: Colors.white,
color: Colors.blueAccent,
)
],
),
),
);
}
}

How can I configure auto-capitalization behavior in Flutter's text entry fields?

I'm experimenting with Flutter development on Windows. I have a simple test app with an InputField. I would like the first keyboard entry to be a capital letter but can't see a way of achieving that (e.g. launching the keyboard with shift pressed) that at the moment. Any ideas?
Code (a bit simplified) is:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
theme: new ThemeData.dark(),
home: new MainScreen()
));
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
leading: new IconButton(
icon: new Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null,
),
title: new Text('Test'),
),
body: new NewTest(),
);
}
}
/// Widget
class NewTest extends StatefulWidget {
#override
_NewTestInputState createState() => new _NewTestInputState();
}
/// State
class _NewTestInputState extends State<NewTest> {
InputValue _currentInput;
void _handleInputChange(InputValue input) {
if (input != _currentInput){
setState(() {
_currentInput = input;
});
}
}
void _handleInputSubmitted(InputValue input) {
setState(() {
_currentInput = const InputValue();
});
}
#override
Widget build(BuildContext context) {
InputField _widget = new InputField(
value: _currentInput,
hintText: 'Enter text',
keyboardType: TextInputType.text,
autofocus: true,
onChanged: _handleInputChange,
onSubmitted: _handleInputSubmitted,
style: new TextStyle(fontSize: 20.0),
);
Container _container = new Container(
child: _widget,
decoration: new BoxDecoration(
border: new Border.all(
color: Colors.green[300],
width: 2.0,
),
),
padding: new EdgeInsets.all(16.0),
);
return _container;
}
}
Flutter has a textCapitalization property for textfields. Set this property to TextCapitalization.sentences or any of the available values eg .characters or .words Like so:
TextField(
keyboardType: TextInputType.text,
**textCapitalization: TextCapitalization.sentences,**
style: TextStyle(
fontSize: 30.0,
color: Colors.black,
fontWeight: FontWeight.bold
),
)
The starting-lowercase was a bug in our iOS implementation of Flutter's keyboard wrapper, which has since been fixed as of today!
I filed a bug for making this configurable (so you can disable the autocapitalize sentences behavior) here: https://github.com/flutter/flutter/issues/9363
Please don't hesitate to reach out if this does not resolve your issue.