How to change text in textformfield in flutter conatct picker - flutter

I have fluttercontactpicker as suffix in my textformfield.
while selecting the contact it is not showing in textformfield.
EditTextField(
onChanged: (text) {
setState(() => _phn = text);
},
input: [FilteringTextInputFormatter.digitsOnly],
isPassword: false,
inputType: TextInputType.number,
decoration: country_code,
isSuffix: InkWell(
onTap: () async {
final PhoneContact contact =
await FlutterContactPicker
.pickPhoneContact();
if (contact != null) {
setState(() {
_phn = contact.phoneNumber!.number
.removeAllWhiteSpace()
.replaceFirst('+91', '')
.toString();
print("this is $_phn");
});
}
},
child: const Icon(
Icons.contacts,
color: t5DarkNavy,
),
),
),

You need to make use of controller for TextForm Field here is an example, you can update controller text with setState
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:fluttercontactpicker/fluttercontactpicker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) => MaterialApp(
home: MainWidget(),
);
}
class MainWidget extends StatefulWidget {
#override
_MainWidgetState createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
PhoneContact? _phoneContact;
EmailContact? _emailContact;
String? _contact;
Image? _contactPhoto;
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: kIsWeb && !FlutterContactPicker.available
? [_buildError(context)]
: _buildChildren(context),
),
);
Widget _buildError(BuildContext context) {
return RichText(
text: TextSpan(
text:
'Your browser does not support contact pickers for more information see: ',
children: [
TextSpan(
text: 'https://web.dev/contact-picker/',
style: TextStyle(
color: Colors.blue,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () => launch('https://web.dev/contact-picker/')),
TextSpan(text: ' and '),
TextSpan(
text:
'https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API#Browser_compatibility/',
style: TextStyle(
color: Colors.blue,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () => launch(
'https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API#Browser_compatibility'))
]),
);
}
List<Widget> _buildChildren(BuildContext context) {
return <Widget>[
if (_emailContact != null)
Column(
children: <Widget>[
const Text("Email contact:"),
Text("Name: ${_emailContact!.fullName}"),
Text(
"Email: ${_emailContact!.email!.email} (${_emailContact!.email!.label})")
],
),
if (_phoneContact != null)
Column(
children: <Widget>[
const Text("Phone contact:"),
TextFormField(
controller: TextEditingController()..text = '${_phoneContact!.fullName}',
onSaved: (String? value) {
debugPrint("Value Set To Be : ${_phoneContact!.fullName}");
},
),
Text(
"Phone: ${_phoneContact!.phoneNumber!.number} (${_phoneContact!.phoneNumber!.label})")
],
),
if (_contactPhoto != null) _contactPhoto!,
if (_contact != null) Text(_contact!),
ElevatedButton(
child: const Text("pick phone contact"),
onPressed: () async {
final PhoneContact contact =
await FlutterContactPicker.pickPhoneContact();
print(contact);
setState(() {
_phoneContact = contact;
});
},
),
ElevatedButton(
child: const Text("pick email contact"),
onPressed: () async {
final EmailContact contact =
await FlutterContactPicker.pickEmailContact();
print(contact);
setState(() {
_emailContact = contact;
});
},
),
ElevatedButton(
child: const Text("pick full contact"),
onPressed: () async {
final FullContact contact =
(await FlutterContactPicker.pickFullContact());
setState(() {
_contact = contact.toString();
_contactPhoto = contact.photo?.asWidget();
});
},
),
ElevatedButton(
child: const Text('Check permission'),
onPressed: () async {
final granted = await FlutterContactPicker.hasPermission();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Granted: '), content: Text('$granted')));
},
),
ElevatedButton(
child: const Text('Request permission'),
onPressed: () async {
final granted = await FlutterContactPicker.requestPermission();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Granted: '), content: Text('$granted')));
},
),
];
}
}

/// your code
TextEditingController _phn = TextEditingController();
_phn = contact.phoneNumber!.number
.removeAllWhiteSpace()
.replaceFirst('+91', '')
.toString();
/// Modify as
_phn.text = contact.phoneNumber!.number
.removeAllWhiteSpace()
.replaceFirst('+91', '')
.toString();

Related

How to refresh a listview from another widget in flutter?

I am new to flutter, and I am trying to refresh my list of files after adding a file in my PDF app. Listview and add button I am using are in different widgets. Refresh function I have used is working for the delete button which is in the same widget as listview and gives error for the add button which is in a different widget from the List view. In both instances ,I am trying to update the List view.
`
class ListFiles extends StatefulWidget {
const ListFiles({Key? key}) : super(key: key);
#override
State<ListFiles> createState() => _ListFilesState();
}
class _ListFilesState extends State<ListFiles> {
final storage = FirebaseStorage.instance;
late Future<ListResult> futureFiles;
String pathPDF = "";
final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
#override
void initState() {
super.initState();
futureFiles = FirebaseStorage.instance.ref('files').listAll();
}
#override
Widget build(BuildContext context) => SizedBox(
height: 450,
child: RefreshIndicator(
onRefresh: onRefresh,
child: FutureBuilder<ListResult>(
future: futureFiles,
builder: (context, snapshot) {
if (snapshot.hasData) {
final files = snapshot.data!.items;
return ListView.builder(
itemCount: files.length,
itemBuilder: (context, index) {
final file = files[index];
return ListTile(
title: Text(file.name),
onTap: () async {
String url = await getFirebaseDownUrl(file);
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) =>
Scaffold(
appBar: AppBar(
title: Text(file.name),
backgroundColor: Colors.red,
),
body: SfPdfViewer.network(
url,
key: _pdfViewerKey,
)
),
),
);
},
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
onPressed: () {
_dialogBuilder(context, file);
},
icon: const Icon(
Icons.delete,
color: Colors.red,
),
),
],
),
);
}
);
} else if (snapshot.hasError) {
return Column(
children: [
ListTile(
leading: const Icon(
Icons.error,
color: Colors.redAccent,
),
title: const Text('Error occurred'),
trailing: IconButton(
onPressed: () {
setState(() {
onRefresh();
});
},
icon: const Icon(
Icons.refresh,
color: Colors.blue,
),
),
),
],
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
Future<String> getFirebaseDownUrl(Reference ref) async {
print(await ref.getDownloadURL());
return ref.getDownloadURL();
}
Future downloadFile(Reference ref) async {
List<int> textBytes = utf8.encode('{$ref}');
Uint8List data = Uint8List.fromList(textBytes);
String mimeType = "application/pdf";
DocumentFileSavePlus.saveFile(data, ref.name, mimeType);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Downloaded ${ref.name} successfully')),
);
}
Future deleteFile(Reference ref) async {
// Create a reference to the file to delete
final storageRef = FirebaseStorage.instance.ref();
final deleteRef = storageRef.child(ref.fullPath);
// Delete the file
await deleteRef.delete();
// setState(() {
// futureFiles = FirebaseStorage.instance.ref('files').listAll();
// });
// build(context);
onRefresh();
// WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));
ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(content: Text('Deleted file ${ref.name}')),
SnackBar(
content: Row(
children: [
Text('${ref.name} deleted successfully'),
const Spacer(
flex: 2,
),
TextButton(
onPressed: () {
onRefresh();
},
child: const Text(
'Refresh',
style: TextStyle(color: Colors.blue),
),
),
],
),
),
);
}
Future<void> _dialogBuilder(BuildContext context, Reference file) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Warning'),
content: const Text('Are you sure you want to delete the file?'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('NO', style: TextStyle(color: Colors.green)),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
deleteFile(file);
},
child:
const Text('YES', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
Future onRefresh() async {
print('Page refreshing...');
setState(() {
futureFiles = FirebaseStorage.instance.ref('files').listAll();
print('Status updated...');
});
build(context);
// ListFiles();
print('Page refreshed...');
}
}
class AddButton extends StatefulWidget {
const AddButton({Key? key}) : super(key: key);
#override
State<AddButton> createState() => _AddButtonState();
}
class _AddButtonState extends State<AddButton> {
PlatformFile? pickedFile;
UploadTask? uploadTask;
late Future<ListResult> futureFiles;
#override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: FloatingActionButton(
backgroundColor: const Color(0xFFFF1D1D),
foregroundColor: Colors.white,
onPressed: () async {
addFile();
},
child: const Icon(Icons.add),
),
),
],
);
}
Future addFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
uploadFile();
}
Future uploadFile() async {
final path = 'files/${pickedFile!.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
final _ListFilesState Listfile = new _ListFilesState();
setState(() {
uploadTask = ref.putFile(file);
});
setState(() {
uploadTask = null;
});
if (pickedFile != null) {
addtoFirestore();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
const Text('File uploaded successfully!'),
const Spacer(
flex: 2,
),
TextButton(
onPressed: () => Listfile.onRefresh(),
child: const Text(
'Refresh',
style: TextStyle(color: Colors.blue),
),
),
],
),
),
);
}
}
`
This is the response msg I get when refresh button of the snackbar is clicked.
enter image description here
Is this implementation correct?
Thank you for your time.
add a callback function to your ListFiles class:
setStateAddedNewClient( item ) {
setState(() {
futureFiles.add(item);
});
}
then add function parameter to your AddButton class:
final Function(dynamic) callback;
const AddButton({Key? key ,required this.callback }) : super(key: key);
and send file to callback function in your addFile function.
Future addFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
callback(result.files.first);
});
uploadFile();
}
you can use a HookWidget
useEffect((() {
//request that you fetch data to listview
context.read<Cubit>().getListRequest();
return null;
}), [dependenciesFromAnotherWidgetToRefreshList]);

Flutter : how to actualize the state of a global variable in every widget?

so i have 2 pages and 1 file where i have my variable . when i run the app my variable total is update every time i enter income page or add a new income . but when i navigate back to the home page the total shows only the first value ive entered .
Home.dart
import 'package:flutter/material.dart';
import 'componets.dart';
import 'income.dart';
import 'variables.dart';
....
bottomNavigationBar: Container(
color: Colors.white,
child: Row(
children: <Widget>[
Expanded(
child: ListTile(
title: new Text("Balance:"),
subtitle: new Text("$Total"),
),
),
the variable total is shown in the bottom of home page
Income.dart
import 'package:flutter/material.dart';
import 'componets.dart';
import 'home.dart';
import 'variables.dart';
class Income extends StatefulWidget {
const Income({Key? key}) : super(key: key);
#override
State<Income> createState() => _IncomeState();
}
class _IncomeState extends State<Income> {
TextEditingController _textFieldController = TextEditingController();
List<double> transactions = [];
Future<void> _displayTextInputDialog(BuildContext context) async {
double Amount = 0;
String valueText = '';
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add income'),
content: TextField(
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: _textFieldController,
),
actions: <Widget>[
FlatButton(
color: Colors.red,
textColor: Colors.white,
child: Text('CANCEL'),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
FlatButton(
color: Colors.green,
textColor: Colors.white,
child: Text('OK'),
onPressed: () {
setState(() {
Amount = double.parse(valueText);
transactions.add(Amount);
Total = Total + Amount;
print(Amount);
Navigator.pop(context);
});
},
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Income"),
backgroundColor: Colors.deepOrange,
centerTitle: false,
elevation: 1.0,
),
body: Center(
child: FlatButton(
color: Colors.teal,
textColor: Colors.white,
onPressed: () {
_displayTextInputDialog(context);
},
child: Text('Press For Alert'),
),
),
// NavigationBar
bottomNavigationBar: Container(
color: Colors.white,
child: Row(
children: <Widget>[
Expanded(
child: ListTile(
title: Text("Balance:"),
subtitle: Text('${Total}'),
),
),
the variable in the same place as the home page
variables.dart
double Total = 0;
I have created example of updating total value using provider by refering yours
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
//Provider for updating totalvalue
class TotalValue with ChangeNotifier {
double _total = 0;
double get value => _total;
void sum(double val) {
_total += val;
notifyListeners();
}
}
//Income Page
class Income extends StatefulWidget {
const Income({Key? key}) : super(key: key);
#override
State<Income> createState() => _IncomeState();
}
class _IncomeState extends State<Income> {
TextEditingController _textFieldController = TextEditingController();
List<double> transactions = [];
Future<void> _displayTextInputDialog(BuildContext context) async {
double Amount = 0;
String valueText = '';
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add income'),
content: TextField(
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: _textFieldController,
),
actions: <Widget>[
FlatButton(
color: Colors.red,
textColor: Colors.white,
child: Text('CANCEL'),
onPressed: () {
Navigator.pop(context);
},
),
FlatButton(
color: Colors.green,
textColor: Colors.white,
child: Text('OK'),
onPressed: () {
Amount = double.parse(valueText);
transactions.add(Amount);
context.read<TotalValue>().sum(Amount);
Navigator.pop(context);
},
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
color: Colors.teal,
textColor: Colors.white,
onPressed: () {
_displayTextInputDialog(context);
},
child: Text('Press For Alert'),
),
);
}
}
//Home Page
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _selectedIndex = 0;
static TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions(BuildContext context) {
return <Widget>[
Income(),
Text(
'${context.watch<TotalValue>().value}',
style: optionStyle,
),
];
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Income'),
),
body: Center(
child: _widgetOptions(context).elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.money),
label: 'Income',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

Update the navigation menu when changing the display conditions of icons in BottomNavigationBarItem in the flutter

I have a navigation menu that I made for a test application, there are some tabs that I want to hide if I am not logged into the application. After logging in, these tabs should appear. The problem is that after logging in, I go to the desired page and I don't see all the navigation menu icons. For them to appear, I need to click on one of the available icons (only 2 icons are available for authorization) and only then the navigation menu will be updated and everything will be as it should be. All 6 icons will be visible! Can someone help me with this? Here I described the problem with the code that I am using. I would be grateful for any help.
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/object_main/Status.dart';
import 'package:flutter_app_seals/model/seals/Seals_List.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_app_seals/Setting_glob.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:flutter_app_seals/model/add_seals/JsonAddSeals.dart';
import 'package:flutter_app_seals/model/user_page/page.dart';
import 'package:flutter_app_seals/model/setting/globalvar.dart' as global;
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import 'package:flutter_aes_ecb_pkcs5/flutter_aes_ecb_pkcs5.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/foundation.dart';
void main() => runApp(Main_Page());
class Main_Page extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage());
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
var test;
class _HomePageState extends State<HomePage> {
Future<bool> _onBackPressed() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Ви впевнині?'),
content: new Text('Ви хочете вийти з додатку',
style: TextStyle(
fontSize: 20,
),
),
actions: <Widget>[
new GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child:
Text("Ні",
style: TextStyle(
fontSize: 25,
),
),
),
SizedBox(height: 40),
new GestureDetector(
onTap: () => Navigator.of(context).pop(true),
child: Text("Так",
style: TextStyle(
fontSize: 25,
),
),
),
],
),
) ??
false;
}
int _pageIndex = 0;
PageController _pageController;
List<Widget> tabPages = [
Login(),
Setting(),
UserPage(),
Status_Obj(),
Status_Seals(),
Add_Seals(),
] ;
#override
void initState(){
super.initState();
_pageController = PageController(initialPage: _pageIndex);
}
#override
void dispose() {
_pageController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPressed,
child: new Scaffold(
resizeToAvoidBottomInset: false,
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: true, // <-- HERE
showUnselectedLabels: true, // <-- AND
currentIndex: _pageIndex,
onTap: onTabTapped,
backgroundColor: Colors.blue,
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem( icon: Icon(Icons.admin_panel_settings_outlined), title: Text(" Вхід"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text("Налаштування"),backgroundColor: Colors.lightBlue),
if( global.nameUser ?.isNotEmpty == true)...[
new BottomNavigationBarItem(icon: Icon(Icons.person_pin), title: Text("Користувач"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Пломбування"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.qr_code), title: Text("Пломби"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.add_outlined), title: Text("Акт приймання"),backgroundColor: Colors.lightBlue),
]
],
),
body: PageView(
children: tabPages,
onPageChanged: onPageChanged,
controller: _pageController,
),
),
);
}
void onPageChanged(int page) {
setState(() {
this._pageIndex = page;
});
}
void onTabTapped(int index) {
this._pageController.animateToPage(index,duration: const Duration(milliseconds: 500),curve: Curves.easeInOut);
}
}
class Login extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new LoginPage(
storage: Storage()
)
);
}
}
class LoginPage extends StatefulWidget {
final Storage storage;
LoginPage({Key key, #required this.storage}) : super(key: key);
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
//Info about users
String state;
#override
void initState() {
super.initState();
widget.storage.readData().then((String value) {
setState(() {
global.urlVar = value;
});
});
}
bool _isLoading = false;
#override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.transparent));
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.white],
begin: Alignment.topCenter,
end: Alignment.bottomCenter),
),
child: _isLoading ? Center(child: CircularProgressIndicator()) : ListView(
children: <Widget>[
headerSection(),
textSection(),
buttonSection(),
],
),
),
);
}
signIn(String login, pass) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var AESLogin = login;
var AESpass = pass;
//generate a 16-byte random key
var key = '11111';
print(key);
//encrypt
var encryptLogin = await FlutterAesEcbPkcs5.encryptString(AESLogin, key);
var encryptPass = await FlutterAesEcbPkcs5.encryptString(AESpass, key);
HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
String url = global.urlVar + "/auth_user";
Map map = {
"login": encryptLogin,
"pass": encryptPass
};
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
Map jsonResponse = json.decode(responseBody);
print(jsonResponse);
if (response.statusCode == 200) {
if (jsonResponse['message'] ==
'200') { //if( jsonResponse['message'] == '200') {
setState(() {
_isLoading = false;
});
global.nameUser = jsonResponse['name'];
global.dataArea = jsonResponse['data_area'];
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => UserPage()),
);
}
else {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Error_Auth()),
);
}
}
else {
setState(() {
_isLoading = false;
});
}
}
Container buttonSection() {
return Container(
width: MediaQuery.of(context).size.width,
height: 40.0,
padding: EdgeInsets.symmetric(horizontal: 15.0),
margin: EdgeInsets.only(top: 15.0),
child: RaisedButton(
onPressed: emailController.text == "" || passwordController.text == "" ? null : () {
setState(() {
_isLoading = true;
});
signIn(emailController.text, passwordController.text);
},
elevation: 0.0,
color: Colors.purple,
child: Text("Авторизація", style: TextStyle(color: Colors.white70)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
),
);
}
final TextEditingController emailController = new TextEditingController();
final TextEditingController passwordController = new TextEditingController();
Container textSection() {
return Container(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
child: Column(
children: <Widget>[
TextFormField(
controller: emailController,
cursorColor: Colors.white,
style: TextStyle(color: Colors.white70),
decoration: InputDecoration(
icon: Icon(Icons.login, color: Colors.white70),
hintText: "Логін",
border: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white70)),
hintStyle: TextStyle(color: Colors.white70),
),
),
SizedBox(height: 30.0),
TextFormField(
controller: passwordController,
cursorColor: Colors.white,
obscureText: true,
style: TextStyle(color: Colors.white70),
decoration: InputDecoration(
icon: Icon(Icons.lock, color: Colors.white70),
hintText: "Пароль",
border: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white70)),
hintStyle: TextStyle(color: Colors.white70),
),
),
],
),
);
}
Container headerSection() {
return Container(
alignment: Alignment.topCenter,
margin: EdgeInsets.only(top: 50.0),
child: Text("Пломби",
style: TextStyle(
color: Colors.white70,
fontSize: 40.0,
fontWeight: FontWeight.bold)),
);
}
}
class Error_Auth extends StatelessWidget {
#override
Widget build(BuildContext context) {
final AlertDialog dialog = AlertDialog(
title: Text('Помилка при авторизації'),
content:
Text('Повторити спробу авторизації'),
actions: [
FlatButton(
textColor: Color(0xFF6200EE),
onPressed: () => SystemNavigator.pop(),
child: Text('Ні'),
),
FlatButton(
textColor: Color(0xFF6200EE),
onPressed: () { Navigator.push(
context,MaterialPageRoute(builder: (context) => Login()),
);
},
child: Text('Так'),
),
],
);
return Scaffold(
body:dialog
);
}
}
class Storage {
Future<String> get localPath async {
final dir = await getApplicationDocumentsDirectory();
return dir.path;
}
Future<File> get localFile async {
final path = await localPath;
return File('$path/db.txt');
}
Future<String> readData() async {
try {
final file = await localFile;
String body = await file.readAsString();
return body;
} catch (e) {
return e.toString();
}
}
Future<File> writeData(String data) async {
final file = await localFile;
return file.writeAsString("$data");
}
}
In this part of the code I am automated and if the status code is 200, then I parse the Jason and add a name for the variable global.nameUser. And in the navigation menu I check if it is not zero then show all the icons of the navigation menu. But the first time it doesn't work. I have clicked on this menu again and only then it will work.
if (response.statusCode == 200) {
if (jsonResponse['message'] ==
'200') { //if( jsonResponse['message'] == '200') {
setState(() {
_isLoading = false;
});
global.nameUser = jsonResponse['name'];
global.dataArea = jsonResponse['data_area'];
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => UserPage()),
);
}
Check the navigation menu which icons to display!
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem( icon: Icon(Icons.admin_panel_settings_outlined), title: Text(" Вхід"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text("Налаштування"),backgroundColor: Colors.lightBlue),
if( global.nameUser ?.isNotEmpty == true)...[
new BottomNavigationBarItem(icon: Icon(Icons.person_pin), title: Text("Користувач"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Пломбування"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.qr_code), title: Text("Пломби"),backgroundColor: Colors.lightBlue),
new BottomNavigationBarItem(icon: Icon(Icons.add_outlined), title: Text("Акт приймання"),backgroundColor: Colors.lightBlue),
]
],
Your page is not re built after logging in the user, that is why your nav bar is not updated. When you click on the button it refreshes and correctly displays the new elements.
Instead of using a global variable you could look into a state management package in order to make the logged-in user available throughout your app. (article for getx the simplest one out there)
If this is simply a prototype and you want some quick and dirty, I guess you could trigger a reload of your app once a user logs in by wrapping your app with a widget that exposes a rebuild method. (article)
EDIT: Example with Getx:
class UserController extends GetxController {
var nameUser = "".obs;
void setName(String str) => nameUser = str;
}
class Home extends StatelessWidget {
final UserController c = Get.put(UserController());
#override
Widget build(context)
...
Obx(() => /// You are watching your controller
...
items: <BottomNavigationBarItem>[
if( c.nameUser.isNotEmpty)...[
...
]
)))
...
class LoginPage extends StatelessWidget {
// You can ask Get to find a Controller that is being used by another page and redirect you to it.
final UserController c = Get.find();
#override
Widget build(context){
...
onPressed: () => c.setName(username);
}
}

How to show a text after onPressed function

I want to show a text after onPressed function happened, this function is a recording function and wants to show a text 'recording' when the function happening
voiceCreate.dart
import 'package:flutter/material.dart';
class VoiceCreate extends StatelessWidget {
final VoidCallback onPressed;
VoiceCreate({this.onPressed});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
body: Center(
child: IconButton(
icon: Icon(Icons.mic),
color: Colors.white,
iconSize: 70,
onPressed: onPressed),
),
),
);
}
}
**main.dart**
import 'dart:io';
import 'package:audioplayer/audioplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:record_mp3/record_mp3.dart';
import 'package:permission_handler/permission_handler.dart';
import 'regitration.dart';
import 'voiceCreate.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String statusText = "";
bool isComplete = false;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
drawer: Drawer(
elevation: 2.0,
child: ListView(
children: <Widget>[
ListTile(
title: Text('Home'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return MyApp();
},
),
);
},
),
ListTile(
title: Text('Sign up'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
);
},
),
ListTile(
title: Text('Sign in'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
);
// add sign in page
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return VoiceCreate(onPressed: startRecord);
}),
);
},
// Add your onPressed code here!
child: Icon(Icons.add),
backgroundColor: Colors.tealAccent.shade700,
),
backgroundColor: Colors.grey.shade900,
appBar: AppBar(
title: Text('Myvo'),
centerTitle: true,
backgroundColor: Colors.tealAccent.shade700,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: GestureDetector(
child: IconButton(
icon: Icon(Icons.mic),
color: Colors.white,
iconSize: 40,
onPressed: () async {
startRecord();
}),
),
),
Expanded(
child: GestureDetector(
child: IconButton(
icon: Icon(Icons.pause),
color: Colors.white,
iconSize: 40,
onPressed: () async {
pauseRecord();
}),
),
),
Expanded(
child: GestureDetector(
child: IconButton(
icon: Icon(Icons.stop),
color: Colors.white,
iconSize: 40,
onPressed: () async {
stopRecord();
}),
),
),
],
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Text(
statusText,
style: TextStyle(color: Colors.red, fontSize: 20),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
play();
},
child: Container(
margin: EdgeInsets.only(top: 30),
alignment: AlignmentDirectional.center,
width: 100,
height: 50,
child: isComplete && recordFilePath != null
? Text(
"play",
style: TextStyle(color: Colors.red, fontSize: 20),
)
: Container(),
),
),
]),
),
),
);
}
Future<bool> checkPermission() async {
if (!await Permission.microphone.isGranted) {
PermissionStatus status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
return false;
}
}
return true;
}
void startRecord() async {
bool hasPermission = await checkPermission();
if (hasPermission) {
statusText = "Recording...";
recordFilePath = await getFilePath();
isComplete = false;
RecordMp3.instance.start(recordFilePath, (type) {
statusText = "Record error--->$type";
setState(() {});
});
} else {
statusText = "No microphone permission";
}
setState(() {});
}
void pauseRecord() {
if (RecordMp3.instance.status == RecordStatus.PAUSE) {
bool s = RecordMp3.instance.resume();
if (s) {
statusText = "Recording...";
setState(() {});
}
} else {
bool s = RecordMp3.instance.pause();
if (s) {
statusText = "Recording pause...";
setState(() {});
}
}
}
void stopRecord() {
bool s = RecordMp3.instance.stop();
if (s) {
statusText = "Record complete";
isComplete = true;
setState(() {});
}
}
void resumeRecord() {
bool s = RecordMp3.instance.resume();
if (s) {
statusText = "Recording...";
setState(() {});
}
}
String recordFilePath;
void play() {
if (recordFilePath != null && File(recordFilePath).existsSync()) {
AudioPlayer audioPlayer = AudioPlayer();
audioPlayer.play(recordFilePath, isLocal: true);
}
}
int i = 0;
Future<String> getFilePath() async {
Directory storageDirectory = await getApplicationDocumentsDirectory();
String sdPath = storageDirectory.path + "/record";
var d = Directory(sdPath);
if (!d.existsSync()) {
d.createSync(recursive: true);
}
return sdPath + "/test_${i++}.mp3";
}
}
VoiceCreate function will happen on a new page when clicking on the Floating button in main.dart and recording will happen when click on mic Icon, want show the text 'recording' whine the fuction happening.
First of all, you need to have StatefulWidget to manage changes in state, then you can use two functions startRecording and stopRecording to toggle the isRecording variable. Then based on the value of isRecording you can make changes in the view, e.g., displaying a text. For displaying the text you can use a Visibility widget and set its visible parameter to isRecording.
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _isRecording = false;
_startRecording() {
this.setState(() {
_isRecording = true;
});
}
_stopRecording() {
this.setState(() {
_isRecording = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
body: Center(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.mic),
color: Colors.white,
iconSize: 70,
onPressed: () => _startRecording(),
),
IconButton(
icon: Icon(Icons.stop),
color: Colors.white,
iconSize: 70,
onPressed: () => _stopRecording(),
),
Visibility(
visible: _isRecording,
child: Text(
'recording',
style: TextStyle(
color: Colors.red
),
),
)
],
),
),
),
);
}
}
Maybe a snackbar could be useful here, something like:
class VoiceCreate extends StatefulWidget {
VoiceCreate({Key key, this.title}) : super(key: key);
final String title;
#override
_VoiceCreateState createState() => _VoiceCreateState();
}
class _VoiceCreateState extends State<VoiceCreate> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
var isRecording = false;
void showRecordingMessage(String message, [Color color = Colors.red]) {
_scaffoldKey.currentState.showSnackBar(
new SnackBar(backgroundColor: color, content: new Text(message)));
}
void setRecordingState() {
this.setState(() {
isRecording = true;
});
print("isRecording is set to $isRecording");
showRecordingMessage('Recording now!');
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.mic),
color: Colors.white,
iconSize: 70,
onPressed: () {
setRecordingState();
},
),
],
),
),
);
}
}

Flutter sharedpreferences get data after app restart

I have implemented the shared preferences which is used to store the current logged in user, i can get the username in each and every time after the user log in, however after the app is restart, the username is gone but the current user is still logged in. I attached the gif to have better explaination. Below is my code.
main.dart
Future<void> main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var usernamee = prefs.getString('yourusername');
print(usernamee);
runApp(MaterialApp(
home: usernamee == null
? LoginPage()
: MainPage(
username: username,
)));
}
String username = '';
loginpage.dart
class LoginPage extends StatefulWidget {
#override
LoginPageState createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
TextEditingController user = new TextEditingController();
TextEditingController pass = new TextEditingController();
String txtmsg = '';
#override
void initState() {
super.initState();
}
Future<bool> _onWillPop() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
) ??
false;
}
Future<List> _login() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final response =
await http.post("http://192.168.1.2/login/login.php", body: {
"username": user.text,
"password": pass.text,
});
var datauser = json.decode(response.body);
if (datauser.length == 0) {
setState(() {
txtmsg = "Username or password is wrong, please try again.";
Fluttertoast.showToast(msg: txtmsg);
});
} else {
if (datauser[0]['level'] == 'admin') {
prefs.setString('yourusername', '$username');
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext ctx) => MainPage(
username: username,
)));
}
setState(() {
username = datauser[0]['username'];
});
}
print(username);
return datauser;
}
final logo = Hero(
tag: 'hero',
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 48.0,
child: Image.asset('assets/images/ic_launcher.png'),
),
);
final forgotLabel = FlatButton(
child: Text(
'Forgot password?',
style: TextStyle(color: Colors.black54),
),
onPressed: () {},
);
#override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance =
ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
body: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
logo,
SizedBox(height: 48.0),
Center(
child: FormUI(),
)
],
),
)));
}
Widget FormUI() {
return new Column(
children: <Widget>[
TextFormField(
controller: user,
decoration: InputDecoration(
hintText: 'Username',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
),
validator: validateusername,
),
SizedBox(height: 18.0),
TextFormField(
controller: pass,
obscureText: true,
decoration: InputDecoration(
hintText: 'Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
),
validator: validatepassword,
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(40),
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
onPressed: () => _login(),
padding: EdgeInsets.all(12),
color: Colors.lightBlueAccent,
child: Text('Log In', style: TextStyle(color: Colors.white)),
),
forgotLabel,
],
);
}
String validateusername(String value) {
if (value.length == 0) {
return "Name is Required";
}
return null;
}
String validatepassword(String value) {
if (value.length == 0) {
return "Password is Required";
}
return null;
}
}
mainpage.dart
class MainPage extends StatefulWidget {
MainPage({this.username});
final String username;
#override
MainPageState createState() => MainPageState();
}
class MainPageState extends State<MainPage> {
Future<bool> _onWillPop() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
) ??
false;
}
void showWifiAlert() async {
var wifiEnabled = await getWifiStatus();
if (wifiEnabled) {
//Do stuff
} else {
AlertDialog(
title: Center(
child: Text('Alert'),
),
content: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: Text(
'Please connect to the internet',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.red,
),
),
)
],
),
actions: <Widget>[
FlatButton(
child: Text(
'Ok',
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
}
Future<bool> getWifiStatus() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
return true;
}
} on SocketException catch (_) {
print('not connected');
return false;
}
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
String username;
print(username);
showWifiAlert();
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center(
child: Text(
widget.username,
),
),
drawer: new DrawerOnly()),
);
}
}
class DrawerOnly extends StatefulWidget {
#override
DrawerOnlyState createState() => DrawerOnlyState();
}
class DrawerOnlyState extends State<DrawerOnly> {
#override
Widget build(BuildContext ctxt) {
return new Drawer(
child: new ListView(
children: <Widget>[
new UserAccountsDrawerHeader(
accountName: Text('$username'),
accountEmail: null,
currentAccountPicture: CircleAvatar(
child: FlutterLogo(size: 42.0),
backgroundColor: Colors.white,
),
),
new ListTile(
leading: Icon(Icons.library_music),
title: Text('Fragment 1'),
onTap: () {
Navigator.pop(ctxt);
Navigator.push(ctxt,
new MaterialPageRoute(builder: (ctxt) => new FirstFragment()));
},
),
new ListTile(
leading: Icon(Icons.movie),
title: Text('Fragment 2'),
onTap: () {
Navigator.pop(ctxt);
Navigator.push(ctxt,
new MaterialPageRoute(builder: (ctxt) => new SecondFragment()));
},
),
new ListTile(
leading: Icon(Icons.exit_to_app),
title: Text('Logout'),
onTap: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('yourusername');
Navigator.pushReplacement(ctxt,
MaterialPageRoute(builder: (BuildContext ctx) => LoginPage()));
/* Navigator.pop(ctxt);
Navigator.pushReplacementNamed(ctxt, '/landingpage'); */
},
),
],
));
}
}
How do i able to get the username even the app is restarted?
I've figure out, i had to add this code in the mainpage.dart. Below is the snippet.
loadUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
username = prefs.getString('yourusername');
});
}
#override
void initState() {
super.initState();
loadUsername();
}
Fetch the value on initState not in the main method.
var username;
getUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
username = prefs.getString('yourusername');
}
#override
void initState() {
getUsername()
super.initState();
}
i use it like that, on my splashscreen and it works perfectly
#override
void initState() {
super.initState();
token();
}
token() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('userToken');
Timer(Duration(milliseconds: 1000), () {
if (token == null || token == '') {
Navigator.pushNamed(context, '/login');
} else {
Navigator.pushNamed(context, '/home');
}
});
}
Use setUser() [retrieve preferences values] just before super.initState();
#override
void initState() {
setUser();
super.initState();
}
setUser() async{
preferences=await SharedPreferences.getInstance();
setState(() {
userId = preferences.getString(USERID) ?? "ak id";
userName = preferences.getString(USERNAME) ?? "ak name";
userEmail = preferences.getString(USEREMAIL) ?? "ak email";
userPhoto = preferences.getString(USERPHOTO) ?? "";
});
}