how to disable button in flutter - flutter

I have an elevated button, to which i want to disable it after user hits the button, api gets called here. i have tried to setState but itseems not working. what else can i do to disable button.
hint: my concept i am working is that once ther users clicks the button, again the user should not be able to click again the same button.
Here is my code:
bool isEnable = false;
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
//FocusManager.instance.primaryFocus!.unfocus();
// });
// setState(() {
// isEnable = false;
// });
}
:null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: const Text('Entry',
style: TextStyle(
color: Colors.white,
)),
),

Please make sure variable qrdata.code and isEnable are initialized outside the build method. Every time when setState is called one or both the variables are getting reset.
The problem is whenever setState is pressed it is not rebuilding the button state. so to change the button state wrap your button with StatefulBuilder.
and please call your API in try catch.
class DisableButton extends StatefulWidget {
const DisableButton({Key? key}) : super(key: key);
#override
State<DisableButton> createState() => _DisableButtonState();
}
class _DisableButtonState extends State<DisableButton> {
bool isEnable = false;
int qrdata = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StatefulBuilder(
builder:
(BuildContext context, void Function(void Function()) setState) {
return ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding: MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(
const TextStyle(fontSize: 14, color: Colors.black))),
onPressed: qrdata != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
print(">>>> Button is disabled");
try {
final data = await http.get(
Uri.parse(
'https://jsonplaceholder.typicode.com/albums/1'),
);
if (!mounted) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NextPage(
data: data.body.toString(),
),
),
);
print("Api Data >>>> $data.body");
} catch (e) {
print("Error While fetching data");
}
setState(() {
isEnable = false;
});
print(">>>> Button is enabled");
}
: null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: Text(isEnable ? "Disabled" : "Enabled",
style: const TextStyle(
color: Colors.white,
)),
);
},
),
),
);
}
}
class NextPage extends StatelessWidget {
const NextPage({Key? key, required this.data}) : super(key: key);
final String data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(child: Text("Data : $data")),
);
}
}
The problem in your code is setting isEnable to true but not resting to false.
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
//FocusManager.instance.primaryFocus!.unfocus();
// });
// setState(() { <---- Uncomment this code.
// isEnable = false;
// });
}
:null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: const Text('Entry',
style: TextStyle(
color: Colors.white,
)),
),

Apply this code bellow:
You got error on double equal.
bool variable:
bool isDisabled = false;
Widget
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isDisabled
? () async {
setState(() {
isDisabled = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
});
setState(() {
isDisabled = false;
});
}
:null,

Related

flutter close alert dialog builder after speech recognition finished

Hello friends i am working on speech recognition in flutter i made custom alert dialogue like native dialog when user click on button alert dialog appear and when user speak it show text on alert dialog my problem is that i want when user finishing his speech alert dialogue will automatically close please let me know how i can perform this task?
stt.SpeechToText speechToText = stt.SpeechToText();
bool islistening = false;
late String text = 'Example:Genesis chapter 1 verse 5';
bool complete=false;
final GlobalKey _dialogKey = GlobalKey();
ValueNotifier<bool> buttonClickedTimes =ValueNotifier(false);
_showDialog() async {
showDialog(
context:context,
barrierDismissible: true,
builder: (BuildContext context) {
return StatefulBuilder(
key: _dialogKey,
builder: (context, setState) {
return Container(
child: Dialog(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const AvatarGlow(
glowColor: Colors.blue,
endRadius: 80,
duration: Duration( milliseconds: 2500),
repeat: true,
showTwoGlows: true,
repeatPauseDuration: Duration( milliseconds: 150),
child: Material(
elevation: 5,
shape: CircleBorder(),
child: CircleAvatar(
backgroundColor: Colors.white,
child: Icon(Icons.mic, color: Colors.blue, size: 40,),
radius: 40,
),
),
),
Text(text),
const SizedBox(height: 10),
TextButton(
onPressed: () => Navigator.pop(context, false), // passing false
child: const Text('Cancel Voice'),
),
],
),
),
),
);
},
);
},
);
}
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
void _listen() async {
if (!islistening) {
bool available = await speechToText.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'),
);
if (available) {
setState(() {
islistening = true;
});
speechToText.listen(
onResult: (result) =>
setState(() {
text = result.recognizedWords;
if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted && speechToText.isListening) {
_dialogKey.currentState!.setState(() {
text =result.recognizedWords;
});}
else{
if(text.contains('Genesis')){
setState(() {
String bigSentence =text;
var voice= bigSentence.split(" ");
var bookname=voice[0];
var booknumber=1;
int chapternumber=int.parse(voice[2]);
int versenumber=int.parse(voice[4]);
if(_regExp.hasMatch(chapternumber.toString())&&_regExp.hasMatch(versenumber.toString())){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Allverse(bookname, booknumber,chapternumber, versenumber)),
);
}else{
Fluttertoast.showToast(
msg: "check chapter number or versenumber",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
});
}
}
})
);
}
} else
{
setState(() => islistening = false);
speechToText.stop();
}
}

When I tab on Icon, its color changes only for seconds and disappears in Futter

So I have problem with the changing color of an icon when it tabbed
thus, when I tab on icon it's only changes for its prober colors but for seconds and then disappears
I have used Provider as shown in the below code, and I also used isChecked = true but when I tab on one icon, all of them change as well.
So what should I do with this problem?
this this the code but my problem remains in Icon Button which's will be below it
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:note/Designs/Favorite_List.dart';
import 'package:note/Models/Favorite_List_Provider.dart';
import 'package:note/Models/Food_Models.dart';
import 'package:provider/provider.dart';
import '../Services/Fetch_Data.dart';
import 'Details_DesignOfDesignOne.dart';
class DesignOne extends StatefulWidget {
const DesignOne({super.key, required this.Image, required this.Desc});
final String Image;
final String Desc;
#override
State<DesignOne> createState() => _DesignOneState();
}
class _DesignOneState extends State<DesignOne> {
late Future<Food> futureFood;
#override
void initState() {
super.initState();
futureFood = fetchData(widget.Image, widget.Desc);
}
bool ischecked = false;
#override
Widget build(BuildContext context) {
final provider = favorite.of(context);
return Scaffold(
backgroundColor: Colors.grey.shade200,
appBar: AppBar(
title: Text('Design one'),
actions: [
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteScreen(Desc: '', Image: ''),
),
);
},
child: Icon(
Icons.list,
size: 30,
),
),
)
],
),
body: Consumer<favorite>(
builder: (BuildContext context, favorite value, child) {
return Center(
child: FutureBuilder<Food>(
future: fetchData(widget.Image, widget.Desc),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.categories.length,
itemBuilder: (contxt, index) {
final fav = snapshot.data!.categories[index];
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsDo(
Desc: snapshot.data!.categories[index]
.strCategoryDescription,
Image: snapshot
.data!.categories[index].strCategoryThumb,
),
),
);
},
child: Card(
elevation: 2,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(50),
),
child: ListTile(
title: Text(
snapshot.data!.categories[index].strCategory
.toString(),
style: GoogleFonts.montserrat(
fontSize: 20,
fontWeight: FontWeight.w600,
fontStyle: FontStyle.italic,
),
),
leading: CircleAvatar(
backgroundColor:
Color.fromARGB(213, 255, 251, 251),
child: Text(
snapshot.data!.categories[index].idCategory
.toString(),
style: GoogleFonts.montserrat(
fontSize: 20,
fontWeight: FontWeight.w600,
fontStyle: FontStyle.italic,
color: Color.fromARGB(255, 148, 148, 135)),
),
),
trailing: IconButton(
icon: (provider.isExist(fav) && ischecked)
? const Icon(Icons.favorite,
color: Colors.red)
: const Icon(Icons.favorite_border),
onPressed: () {
provider.toggleFavorite(fav);
setState(() {
ischecked = !ischecked;
});
},
),
),
),
);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
);
}),
);
}
}
and this is the specific problem with the Icon Button :
trailing: IconButton(
icon: (provider.isExist(fav) && ischecked)
? const Icon(Icons.favorite,
color: Colors.red)
: const Icon(Icons.favorite_border),
onPressed: () {
provider.toggleFavorite(fav);
setState(() {
ischecked = !ischecked;
});
},
),
And here is the problem :
Would you try this way instead of isChecked variable??
class _DesignOneState extends State<DesignOne>{
static late List<bool> isChecked;
///*** your code ****
Widgetbuild(BuildContext context){
///*** your code ***
if(snapshot.hasData){
isChecked = List.filled(snapshot.data!.categories.length,false);
/// *** your code ***
icon: (provider.isExist(fav) && isChecked[index])
/// *** your code ***
setState((){
isChecked[index] = !isChecked[index];
});
}
}
}

Flutter Agora Ui video disable by default

I have a video channel code in which users can do video calls on a channel. What I need to do is when the user comes the first time then the video is turned off till the user wants to enable it. right now its default camera is on but I need to default off
class VideoPage extends StatefulWidget {
final roomid;
const VideoPage({Key? key, this.roomid}) : super(key: key);
#override
State<VideoPage> createState() => _VideoPageState();
}
class _VideoPageState extends State<VideoPage> {
bool videoIconEnable = false;
bool enableVideo = false;
final AgoraClient client = AgoraClient(
agoraEventHandlers: (AgoraRtcEventHandlers(leaveChannel: (state) {
Get.back();
})),
// videoDisabled: true,
agoraConnectionData: AgoraConnectionData(
appId: "e0700cba7e944848a29e****",
channelName: "***",
username: "asdrere",
tempToken:
"006e0700cba7****3d9b2IACy1MhejFRYOOqTS9FVTDH+2aMwmwVbbHjpVlqMbEY1ubd/Wk0AAAAAEACGukDPURzvYgEAAQBRHO9i"),
);
#override
void initState() {
super.initState();
initAgora();
}
void initAgora() async {
await client.initialize();
}
#override
void dispose() {
// TODO: implement dispose
super.dispose();
// client.leaveChannel();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
// leading: GestureDetector(
// onTap: () {
// Get.back();
// },
// child: Icon(
// Icons.arrow_back_ios,
// color: Colors.grey,
// ),
// ),
actions: [
videoIconEnable
? GestureDetector(
onTap: () async {
setState(() {
enableVideo = true;
});
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.video_call,
color: kPrimarycolor,
size: 30,
),
),
)
: Container()
],
title: Text(
'On Call',
style: TextStyle(
color: kPrimarycolor,
fontSize: 30,
fontWeight: FontWeight.bold),
)),
body: SafeArea(
child: Stack(
children: [
TweenAnimationBuilder<Duration>(
duration: Duration(seconds: 10),
tween:
Tween(begin: Duration(seconds: 10), end: Duration.zero),
onEnd: () {
setState(() {
videoIconEnable = true;
});
print('Timer ended');
},
builder:
(BuildContext context, Duration value, Widget? child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('Video will start in$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
videoIconEnable
? AgoraVideoViewer(
client: client,
layoutType: Layout.floating,
enableHostControls:
true, // Add this to enable host controls
)
: Container(),
AgoraVideoButtons(
client: client,
),
],
),
),
),
);
}
}
All buttons are working fine disable enable video but I need to default value of video false.

Flutter Slidable SlidableAction Calling onPressed even when it has not been pressed

I am using a library called flutter_slidable . Below is my fetchItems method
static Future<List<Item>> fetchItems(String url) async {
try {
// pub spec yaml http:
// import 'package:http/http.dart' as http;
final response = await http.get(
Uri.parse(
url),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
}) /*.timeout(const Duration(seconds: Config.responseTimeOutInSeconds))*/;
final List<Item> itemsList;
if (response.statusCode == 200) {
itemsList = json
.decode(response.body)
// In event of failure return line below
//.cast<Map<String, dynamic>>()
.map<Item>((json) => Item.fromJson(json))
.toList();
} else if (response.statusCode == 401) {
itemsList = [];
} else {
itemsList = [];
}
return itemsList;
} catch (e) {
if (kDebugMode) {
Logger().wtf(
"FetchItemsException $e \n\nResponseStatusCode ${statusCode!}");
}
rethrow;
}
}
And below is the code for my page that i populate
class ClassListWithSearchOnAppBarCustomCard extends StatefulWidget {
const ClassListWithSearchOnAppBarCustomCard({Key? key}) : super(key: key);
#override
_ClassListWithSearchOnAppBarCustomCardState createState() =>
_ClassListWithSearchOnAppBarCustomCardState();
}
class _ClassListWithSearchOnAppBarCustomCardState
extends State<ClassListWithSearchOnAppBarCustomCard> {
List<Item>? itemsList;
Future populateItemsList() async {
final itemsList = await AsyncFutures.fetchItems(
"https://api.json-generator.com/templates/ueOoUwh5r44G/data");
setState(() {
this.itemsList = itemsList;
});
}
#override
void initState() {
super.initState();
populateItemsList();
}
onSearch(String searchValue) {}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.grey.shade900,
leading: IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(
Icons.arrow_back,
color: Colors.white,
)),
title: Container(
child: TextField(
onChanged: (value) => onSearch(value),
cursorHeight: 21.0,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[850],
contentPadding: EdgeInsets.all(0),
prefix: Icon(
Icons.search,
color: Colors.grey.shade500,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide.none),
hintStyle:
TextStyle(fontSize: 15, color: Colors.grey.shade500),
hintText: "Search"),
style: TextStyle(
color: Colors.white,
),
),
),
),
body: Column(children: [
Expanded(
child: Builder(
builder: (BuildContext context) {
if (itemsList == null) {
return iconProgressIndicator();
} else {
return RefreshIndicator(
// background color
backgroundColor: Colors.white,
// refresh circular progress indicator color
color: Colors.green,
onRefresh: () async {
setState(() {
populateItemsList();
});
},
child: ListView.builder(
itemCount: itemsList!.length,
itemBuilder: (BuildContext context, int index) {
// flutter_slidable: ^1.2.0
// import 'package:flutter_slidable/flutter_slidable.dart';
return Slidable(
// Specify whether the slider is dismissible
key: const ValueKey(1),
// Sliding from left to right
startActionPane: ActionPane(
// Types of Motion
// Behind Motion, Drawer Motion, Scroll Motion , Stretch Motion
motion: const DrawerMotion(),
// dismissible: DismissiblePane(onDismissed: () {
// onDismissedRemoveItem(
// itemsList![index].id ?? "");
// }),
children: [
// Start this side with delete action if you have already implemented dismissible
// If Start with other slidable action create a new method for the slidable with a build context
SlidableAction(
onPressed: deleteSlidableAction(
context, itemsList![index].id ?? ""),
backgroundColor: Colors.red.shade500,
foregroundColor: Colors.white,
icon: Icons.delete,
label: 'Delete',
),
SlidableAction(
onPressed: dialogSlidableAction(
context, itemsList![index].id ?? ""),
backgroundColor: Colors.blueAccent.shade400,
foregroundColor: Colors.white,
icon: Icons.check_box_outline_blank,
label: 'Dialog',
),
],
),
child: myCustomCardWidget(
itemsList![index].id ?? "",
itemsList![index].title ?? "",
itemsList![index].subTitle ?? '',
itemsList![index].imageUrl ??
Config.nullNetworkImage),
);
},
));
}
},
),
)
]));
}
deleteSlidableAction(BuildContext context, String? itemId) {
setState(() {
itemsList!.removeWhere((item) => item.id == itemId);
});
}
dialogSlidableAction(BuildContext context, String? itemId) {
print(itemId);
}
void onDismissedRemoveItem(String itemId) {
setState(() {
itemsList!.removeWhere((item) => item.id == itemId);
});
}
}
The problem i am having is that onPressed of SlidableAction for both Delete and Dialog are being called even before they are pressed and the populated list items are all removed
SlidableAction(
// An action can be bigger than the others.
onPressed: (BuildContext context){
_yesPost(forMeList[i]["postID"]);
},
backgroundColor: Colors.green,
foregroundColor: Colors.white,
icon: Icons.check_circle_outline,
label: 'Yes',
),
try to add BuildContext.
that worked for me.

Waiting time to charge shared preferences is too long

I have a user profile class on my app:
class Perfil extends StatefulWidget {
const Perfil({Key? key}) : super(key: key);
#override
_PerfilState createState() => _PerfilState();
}
class _PerfilState extends State<Perfil> {
final _util_preferences = UtilidadPreferences();
var _estado_autenticacion = false;
String _id = "";
String _email = "";
String _imagen = "";
String _token_firebase = "";
String _nombre = "";
String _apellidos = "";
bool _verificada = false;
bool _activa = false;
#override
void initState() {
// TODO: implement initState
super.initState();
getEstadoAutenticacion();
}
void getEstadoAutenticacion() {
var estado =
_util_preferences.recibirEstadoAutenticacion().then((value) async {
value == null
? _estado_autenticacion = false
: _estado_autenticacion = value as bool;
print(
"valor autenticacion en perfil:" + _estado_autenticacion.toString());
if (_estado_autenticacion == false) {}
_estado_autenticacion = _estado_autenticacion;
_id = await _util_preferences.recibirUsuarioId();
_email = await _util_preferences.recibirUsuarioEmail();
_nombre = await _util_preferences.recibirUsuarioNombre();
_apellidos = await _util_preferences.recibirUsuarioApellidos();
_imagen = await _util_preferences.recibirUsuarioImagen();
_token_firebase = await _util_preferences.recibirUsuarioTokenFB();
_verificada = await _util_preferences.recibirUsuarioVerificado();
_activa = await _util_preferences.recibirUsuarioActivo();
setState(() {});
});
}
#override
Widget build(BuildContext context) {
localizationsDelegates:
context.localizationDelegates;
supportedLocales:
context.supportedLocales;
locale:
context.locale;
var _esp = false;
var _en = false;
var _ca = false;
int count;
//idioma actual
var actual = EasyLocalization.of(context)?.locale;
if (actual?.languageCode == "es") {
_en = false;
_esp = true;
_ca = false;
}
if (actual?.languageCode == "en") {
_en = true;
_esp = false;
_ca = false;
}
if (actual?.languageCode == "ca") {
_en = false;
_esp = false;
_ca = true;
}
;
print("Idioma actual bool esp:" + _esp.toString());
print("Idioma actual bool en:" + _en.toString());
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
body: Center(
//perfil si no esta logeado
child: _estado_autenticacion == false
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
child: Text('IniciarSesion'.tr()),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(
builder: (context) => LoginPage()))
.then((value) {
setState(() {
print("estoy de vuelta en perfil");
getEstadoAutenticacion();
});
});
},
style: ElevatedButton.styleFrom(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
primary: Colors.red,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 20),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
),
ElevatedButton(
child: Text('CrearCuenta'.tr()),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => SignupPage()));
},
style: ElevatedButton.styleFrom(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
primary: Colors.red,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 20),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 8.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ChoiceChip(
selected: _en,
shadowColor: Colors.teal,
elevation: 10,
pressElevation: 5,
backgroundColor: Colors.black54,
selectedColor: Colors.red,
label: Text('English',
style: TextStyle(color: Colors.white)),
onSelected: (bool selected) {
setState(() {
context.setLocale(Locale('en', 'EN'));
});
},
),
ChoiceChip(
selected: _esp,
shadowColor: Colors.teal,
elevation: 10,
pressElevation: 5,
label: Text('Español',
style: TextStyle(color: Colors.white)),
backgroundColor: Colors.black54,
selectedColor: Colors.red,
onSelected: (bool selected) {
setState(() {
context.setLocale(Locale('es', 'ES'));
});
},
),
ChoiceChip(
selected: _ca,
shadowColor: Colors.teal,
elevation: 10,
pressElevation: 5,
label: Text('Català',
style: TextStyle(color: Colors.white)),
backgroundColor: Colors.black54,
selectedColor: Colors.red,
onSelected: (bool selected) {
setState(() {
context.setLocale(Locale('ca', 'CA'));
});
},
),
],
)
],
)
:
// perfil si esta logeado,
Column(
children: [
Text(_id),
Text(_imagen),
Text(_nombre),
Text(_apellidos),
Text(_token_firebase),
Text(_verificada.toString()),
Text(_activa.toString()),
],
)),
),
);
}
}
At this moment it is working fine, but I am experiencing a small issue.
When the class is shown, it should detect if the user is logged in or not.
Depending on this state, the class should show a column or another.
The small issue I am talking about is that during the time that all shared preferences values are been received, the class is showing the first column, it takes only a fraction of a second, but it is not very nice to see.
What should I do to avoid showing the first column while shared preferences are loading?