Cannot replace a string in Dart - flutter

I'm re-writing a simple application to calculate averages, however I have a hard time with a TextField.
I set the TextField to be able to replace a comma to a period if a locale is en_US, otherwise it should replace a period to a comma if locale is different than en_US. However, replaceAll() method doesn't seem to work.
Sorry for the code quality, but I will fix it after I see where's the problem.
Code:
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
class ArithmeticAverageScreen extends StatefulWidget {
#override
_ArithmeticAverageScreenState createState() => _ArithmeticAverageScreenState();
}
class _ArithmeticAverageScreenState extends State<ArithmeticAverageScreen> {
var _grades = List<Widget>();
var _textFieldController = TextEditingController();
var _gradesList = List<String>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('arithmetic_average_title').tr(),
),
body: Container(
padding: EdgeInsets.all(16.0),
child: ListView(
children: <Widget>[
Card(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Icon(Icons.help),
title: Text('arithmetic_average_help').tr(),
subtitle: Text('arithmetic_average_help_content').tr(),
)
],
),
)
),
SizedBox(height: 16.0),
Card(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
SizedBox(height: 16.0),
Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
SizedBox(height: 16.0),
Row(
children: <Widget>[
Container(
width: 60.0,
child: TextField(
controller: _textFieldController,
inputFormatters: [ WhitelistingTextInputFormatter(RegExp("[0-9,.]")) ],
decoration: InputDecoration(
hintText: '5',
labelText: 'arithmetic_average_grade'.tr()
),
),
),
SizedBox(width: 20.0,),
RaisedButton(
onPressed: () {
if (_textFieldController.text == '') {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('arithmetic_average_type_number').tr(),
);
}
);
}
else {
String locale = Localizations.localeOf(context).toString();
if (locale == 'en_US') {
if (_textFieldController.text.contains(',')) {
print('True');
_textFieldController.text.replaceAll(',', '.');
}
}
else if (locale == 'pl_PL') {
if (_textFieldController.text.contains('.')) {
_textFieldController.text.replaceAll('.', ',');
}
}
setState(() {
_gradesList.add(_textFieldController.text);
print(_gradesList);
_grades.add(Text(_textFieldController.text));
});
}
},
color: Colors.teal[300],
textColor: Colors.white,
child: Text('arithmetic_average_add_button').tr(),
),
],
),
SizedBox(height: 16.0,),
Wrap(
children: _grades,
),
],
),
),
)
],
),
)
);
}
}

In the following line, you are not updating the text of the text field so replace the following
_textFieldController.text.replaceAll(',', '.');
with this
_textFieldController.text = _textFieldController.text.replaceAll(',', '.')

Related

Text overflow flutter

I have the next widget, which is rendered with overflow. I have tried to solve, but i don't know. Can anyone help me? The aim is to do a custom card inside listview.
I have tried to wrap with expanded buth then, the error is referenced with constraints.
import 'package:flutter/material.dart';
import '../../shared/AppTheme.dart';
class ComandaScreen extends StatefulWidget {
const ComandaScreen({Key? key}) : super(key: key);
#override
State<ComandaScreen> createState() => _ComandaScreenState();
}
class _ComandaScreenState extends State<ComandaScreen> {
bool expanded = false;
int unidades = 0;
final List<Map<String, dynamic>> _items = List.generate(
10, (index) => {'id': index, 'Nombre': 'Nuggets $index',
'isExpanded': false, "unidades": 8});
#override
Widget build(BuildContext context) {
final ButtonStyle flatButtonStyle = TextButton.styleFrom(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
);
return Scaffold(
appBar: AppBar(
title: const Text('Comanda'),
backgroundColor: AppTheme.backgroundColor,
foregroundColor: AppTheme.primaryTextColor,
elevation: 0,
),
body: SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
// expandedHeaderPadding: const EdgeInsets.all(10),
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: const Duration(milliseconds: 200),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
// backgroundColor: item['isExpanded'] == true ? Colors.cyan[100] : Colors.white,
headerBuilder: (context, isExpanded) {
return Container(
margin: const EdgeInsets.all(10),
child: Row(children: [
const CircleAvatar(
child: Text(
'1',
textAlign: TextAlign.center,
)),
const SizedBox(
width: 10,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Nuggets',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w600),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Text(
'Unidades: ${7}',
style: TextStyle(color: Colors.black),
),
Text(
'Pendientes: 400',
style: TextStyle(color: Colors.black),
),
],
),
const SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Precio: 10 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
Text(
'Total: 70 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
],
),
],
),
],
),
),
]),
);
},
body: ButtonBar(
alignment: MainAxisAlignment.spaceAround,
buttonHeight: 52.0,
buttonMinWidth: 90.0,
children: <Widget>[
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] += 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.add,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Más'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] -= 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.remove,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Menos'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.edit_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Editar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.delete_outline_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Eliminar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.card_giftcard_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Invitar'),
],
),
)
],
),
isExpanded: item['isExpanded'],
),
)
.toList(),
// Card_lineaComanda(flatButtonStyle),
),
),
);
}
}
I 've edited the code to show all screen widget.
Image of result of code before:
For desktop applications, you can prevent the resize with breakpoint, so the error won't happen. In the pubsec.yaml file, add the following dependency.
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
And in your main method before runapp add this code with min-width and min-height below which the app won't resize.
const double desktopMinWidth = 800.0;
const double desktopMinHeight = 600.0;
if (Platform.isMacOS || Platform.isWindows) {
setWindowMinSize(const Size(desktopMinWidth, desktopMinHeight));
setWindowMaxSize(Size.infinite);
}
Note: Once done restart your app.
For mobile, it is entirely a different case. You might need to restructure the design

How to usage Obx() with getx in flutter?

On my UI screen, I have 2 textfields in a column. If textFormFieldEntr is empty, hide textFormFiel. If there is a value in the textFormFieldEntr, let the other textfield be visible. After I set the bool active variable to false in the Controller class, I checked the value in the textFormFieldEntr in the showText class. I'm wrong using obx on the UI screen. The textfields are listed in the _formTextField method. Can you answer by explaining the correct obx usage on the code I shared?
class WordController extends GetxController {
TextEditingController controllerInput1 = TextEditingController();
TextEditingController controllerInput2 = TextEditingController();
bool active = false.obs();
final translator = GoogleTranslator();
RxList data = [].obs;
#override
void onInit() {
getir();
super.onInit();
}
void showText() {
if (!controllerInput1.text.isEmpty) {
active = true;
}
}
ekle(Word word) async {
var val = await WordRepo().add(word);
showDilog("Kayıt Başarılı");
update();
return val;
}
updateWord(Word word) async {
var val = await WordRepo().update(word);
showDilog("Kayıt Başarılı");
return val;
}
deleteWord(int? id) async {
var val = await WordRepo().deleteById(id!);
return val;
}
getir() async {
//here read all data from database
data.value = await WordRepo().getAll();
print(data);
return data;
}
translateLanguage(String newValue) async {
if (newValue == null || newValue.length == 0) {
return;
}
List list = ["I", "i"];
if (newValue.length == 1 && !list.contains(newValue)) {
return;
}
var translate = await translator.translate(newValue, from: 'en', to: 'tr');
controllerInput2.text = translate.toString();
//addNote();
return translate;
}
showDilog(String message) {
Get.defaultDialog(title: "Bilgi", middleText: message);
}
addNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await ekle(word);
getir();
clear();
}
clear() {
controllerInput2.clear();
controllerInput1.clear();
}
updateNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await updateWord(word);
await getir();
update();
}
}
UI:
class MainPage extends StatelessWidget {
bool _active=false.obs();
String _firstLanguage = "English";
String _secondLanguage = "Turkish";
WordController controller = Get.put(WordController());
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
controller.getir();
return Scaffold(
drawer: _drawer,
backgroundColor: Colors.blueAccent,
appBar: _appbar,
body: _bodyScaffold,
floatingActionButton: _floattingActionButton,
);
}
SingleChildScrollView get _bodyScaffold {
return SingleChildScrollView(
child: Column(
children: [
chooseLanguage,
translateTextView,
],
),
);
}
AppBar get _appbar {
return AppBar(
backgroundColor: Colors.blueAccent,
centerTitle: true,
title: Text("TRANSLATE"),
elevation: 0.0,
);
}
get chooseLanguage => Container(
height: 55.0,
decoration: buildBoxDecoration,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
firstChooseLanguage,
changeLanguageButton,
secondChooseLanguage,
],
),
);
get buildBoxDecoration {
return BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(
width: 3.5,
color: Colors.grey,
),
),
);
}
refreshList() {
controller.getir();
}
get changeLanguageButton {
return Material(
color: Colors.white,
child: IconButton(
icon: Icon(
Icons.wifi_protected_setup_rounded,
color: Colors.indigo,
size: 30.0,
),
onPressed: () {},
),
);
}
get secondChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._secondLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get firstChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._firstLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get translateTextView => Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
child: _formTextField,
),
Container(
height: Get.height/1.6,
child: Obx(() {
return ListView.builder(
itemCount: controller.data.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding:
EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(controller.data, index),
secondText(controller.data, index),
],
),
historyIconbutton,
],
),
),
);
},
);
}),
)
],
);
get _formTextField {
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
textFormFieldEntr,
favoriIconButton,
],
),
),
textFormField //burası kapandı
],
),
);
}
get textFormFieldEntr {
return Flexible(
child: Container(
child: TextFormField(
onTap: () {
showMaterialBanner();
},
// onChanged: (text) {
// controller.translateLanguage(text);
// },
controller: controller.controllerInput1,
maxLines: 6,
validator: (controllerInput1) {
if (controllerInput1!.isEmpty) {
return "lütfen bir değer giriniz";
} else if (controllerInput1.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
hintText: "Enter",
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
);
}
void showMaterialBanner() {
ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
backgroundColor: Colors.red,
content: Padding(
padding: const EdgeInsets.only(top: 30.0),
child: Column(
children: [
TextFormField(
controller: controller.controllerInput1,
maxLines: 6,
onChanged: (text) {
controller.translateLanguage(text);
controller.showText();
},
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
suffixIcon: IconButton(onPressed: () {
FocusScope.of(Get.context!).unfocus();
closeBanner();
}, icon: Icon(Icons.clear),),
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
SizedBox(height: 80.0),
TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
],
),
),
actions: [
IconButton(
onPressed: () {
closeBanner();
},
icon: Icon(
Icons.arrow_forward_outlined,
color: Colors.indigo,
size: 36,
),
),
]));
}
void closeBanner() {
ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
}
// } controller.controllerInput1.text==""?_active=false: _active=true;
get textFormField {
return Visibility(
visible: controller.active,
child: Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
child: Container(
child: TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
),
);
}
FutureBuilder<dynamic> get historyWordList {
return FutureBuilder(
future: controller.getir(),
builder: (context, AsyncSnapshot snapShot) {
if (snapShot.hasData) {
var wordList = snapShot.data;
return ListView.builder(
itemCount: wordList.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(wordList, index),
secondText(wordList, index),
],
),
historyIconbutton,
],
),
),
);
},
);
} else {
return Center();
}
},
);
}
IconButton get historyIconbutton {
return IconButton(
onPressed: () {},
icon: Icon(Icons.history),
iconSize: 30.0,
);
}
Text firstText(wordList, int index) {
return Text(
"İngilizce: ${wordList[index].wordEn ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Text secondText(wordList, int index) {
return Text(
"Türkçe: ${wordList[index].wordTr ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
get favoriIconButton {
return IconButton(
alignment: Alignment.topRight,
onPressed: () async {
bool validatorKontrol = _formKey.currentState!.validate();
if (validatorKontrol) {
String val1 = controller.controllerInput1.text;
String val2 = controller.controllerInput2.text;
print("$val1 $val2");
await controller.addNote();
await refreshList();
}
await Obx(() => textFormField(
controller: controller.controllerInput2,
));
await Obx(() => textFormField(
controller: controller.controllerInput1,
));
},
icon: Icon(
Icons.forward,
color: Colors.blueGrey,
size: 36.0,
),
);
}
FloatingActionButton get _floattingActionButton {
return FloatingActionButton(
onPressed: () {
Get.to(WordListPage());
},
child: Icon(
Icons.app_registration,
size: 30,
),
);
}
Drawer get _drawer {
return Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
userAccountsDrawerHeader,
drawerFavorilerim,
drawersettings,
drawerContacts,
],
),
);
}
ListTile get drawerContacts {
return ListTile(
leading: Icon(Icons.contacts),
title: Text("Contact Us"),
onTap: () {
Get.back();
},
);
}
ListTile get drawersettings {
return ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Get.back();
},
);
}
ListTile get drawerFavorilerim {
return ListTile(
leading: Icon(
Icons.star,
color: Colors.yellow,
),
title: Text("Favorilerim"),
onTap: () {
Get.to(FavoriListPage());
},
);
}
UserAccountsDrawerHeader get userAccountsDrawerHeader {
return UserAccountsDrawerHeader(
accountName: Text("UserName"),
accountEmail: Text("E-mail"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.grey,
child: Text(
"",
style: TextStyle(fontSize: 40.0),
),
),
);
}
}
You can simple do it like this
class ControllerSample extends GetxController{
final active = false.obs
functionPass(){
active(!active.value);
}
}
on page
final sampleController = Get.put(ControllerSample());
Obx(
()=> Form(
key: yourkeyState,
child: Column(
children: [
TextFormField(
//some other needed
//put the function on onChanged
onChanged:(value){
if(value.isEmpty){
sampleController.functionPass();
}else{
sampleController.functionPass();
}
}
),
Visibility(
visible: sampleController.active.value,
child: TextFormField(
//some other info
)
),
]
)
)
)

Flutter - ImagePicker does not display the image selected

I am trying to use ImagePicker. When an image is selected, it is not displayed on the screen. Value seems to be null. Below, you will find the full source code. I have done some research, but I have not find what mistake I am doing. If you could point me in the right direction, it would be great and appreciated. Many thanks.
class CaptureV2 extends StatefulWidget {
CaptureV2({Key key}) : super(key: key);
#override
_CaptureV2State createState() => _CaptureV2State();
}
class _CaptureV2State extends State<CaptureV2> {
GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();
bool isOn = true;
String _valueTaskNameChanged = '';
String _valueTaskNameToValidate ='';
String _valueTaskNameSaved='';
File imageFile;
_openGallery(BuildContext context) async{
imageFile = await ImagePicker().getImage(source: ImageSource.gallery) as File;
this.setState(() {
});
}
_openCamera(BuildContext context) async {
imageFile = await ImagePicker().getImage(source: ImageSource.camera) as File;
this.setState(() {
});
}
Widget _showImageView(context){ //Even when I am selecting an image I always get null
if(imageFile ==null) {
return Text('No attachment');
}else{
return Image.file(imageFile, width: 200, height: 200,);
}
}
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
drawer: MyMenu(),
appBar: AppBar(
centerTitle: true,
title: Text('CAPTURE'),
actions: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0,22,0,0),
child: Text("On/Off"),
),
Switch(
value: isOn,
onChanged: (value) {
setState(() {
isOn = value;
});
},
activeTrackColor: Colors.green,
activeColor: Colors.green,
),
],
),
//==================
body: isOn?
SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.end,
// mainAxisAlignment: MainAxisAlignment.end,
children: [
Form(
key: _captureFormKey,
child: Column(
// crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 100,
maxLines: 3,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
),
SizedBox(
height: 50.0,
),
//########ATTACHEMENT & PHOTOS
Card(
child:
Container(
// color: Colors.red,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:[
//Attachement
FlatButton(
onPressed: () {
},
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.attach_file),
Text('Attachement'),
],
)
),
onTap: () {
_openGallery(context);
},
),
),
//Photo
FlatButton(
onPressed: () {(); },
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.add_a_photo_rounded),
Text('Photo'),
],
)
),
onTap: () {
},
),
),
//Voice Recording
FlatButton(
onPressed: () { },
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ConstrainedBox(
constraints: BoxConstraints(
minWidth: iconSize,
minHeight: iconSize,
maxWidth: iconSize,
maxHeight: iconSize,
),
child: Image.asset('assets/icons/microphone.png', fit: BoxFit.cover),
),
Text('Recording'),
],
)
),
onTap: () {
MyApp_AZERTY();
},
),
),
],
),
)
),
]
),
),
Container(
child:
_showImageView(context)
),
SizedBox(
height: 150.0,
),
//CANCEL & SAVE
Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(width: 1.0, color: Colors.grey),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
child:
FlatButton(
child: Text("Cancel",style: TextStyle(
fontSize: 18.0,fontWeight: FontWeight.bold,color: Colors.grey
)
),
onPressed: (){
final loForm = _captureFormKey.currentState;
loForm.reset();
},
),
),
Container(
child: FlatButton(
child: Text("Save",style: TextStyle(
fontSize: 18.0,fontWeight: FontWeight.bold,color: Colors.blue
)),
// Border.all(width: 1.0, color: Colors.black),
onPressed: (){}
loForm.reset();
showSimpleFlushbar(context, 'Task Saved',_valueTaskNameSaved, Icons.mode_comment);
}
loForm.reset();
},
),
),
]
),
),
],
),
) :
The problem is getImage does not return a type of file, but a type of
Future<PickedFile>
So you need to do the following.
final image = await ImagePicker().getImage(source: ImageSource.gallery);
this.setState(() {
imageFile = File(image.path);
});

How to conditionally create Text children in column, based on selected Dropdownbutton item?

I'm pretty new to flutter and Dart, started learning some two weeks ago. My first app I'm trying to build as a starters project is a simple dosage calculator tool for calculating the amount of anesthetics you have to add based on number and weight of mice.
So to my problem: I managed to create the most basics elements of the UI and created a dropdown menu for the anesthesia protocol that the user wants to use. Based on the chosen element I would like to display different text elements in a column, representing the different meds that the protocol is composed of. For example if the user chooses MMF it will display Medetomidine, Midazolam and Fentanyl.
I have looked everywhere for the conditional creation of widgets, and haven't found a solution that suits my problem yet. Maybe I'm just not searching good enough. Since I know some Python I would have imagined it should be pretty simple to set something like this up using if statements based on a variable that gets created when the selectedItem is changed. However I haven't found out how to create these variables, to then be able to use it for the implementation in the column.
Sorry for the wall of text, hope you'll be able to help me, thanks in advance!
Here's my code:
import 'package:flutter/material.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';
void main() => runApp(MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Dosierungsrechner';
Color c = const Color.fromRGBO(17, 29, 78, 1.0);
Color b = const Color.fromRGBO(223, 240, 250, 1.0);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title),
centerTitle:true,
backgroundColor: c,
),
body: Column(
children: [
Align(
alignment: Alignment.topCenter,
child: Column(
children: <Widget> [
Padding(
padding:const EdgeInsets.all(8.0),
child: Container(
height:60,
decoration:BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment:Alignment.bottomCenter,
child:MyStatefulWidget(),
),
),
),
Padding(
padding:const EdgeInsets.all(8.0),
child:Container(
height:40,
decoration:BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Anzahl der Mäuse:',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Flexible(
child: SpinBox(
min: 0,
max: 100,
value: 0,
onChanged: (value) => print(value),
),
),
],
),
),
),
Padding(
padding:const EdgeInsets.all(8.0),
child:Container(
height:40,
decoration:BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Gewicht/Maus in g:',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Flexible(
child: SpinBox(
min: 0,
max: 50,
value: 0,
onChanged: (value) => print(value),
),
),
],
),
),
),
],
),
),
Text('Anzumischende Bestandteile',
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
Padding(
padding:const EdgeInsets.all(8.0),
child: Container(
height:200,
decoration:BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment: Alignment.center,
child: Column(
children:[
Text('Midazolam 5mg/ml'),
Text('Medetomidin 5mg/ml'),
Text('Fentanyl 1mg/ml'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
),
),
),
Padding(
padding:const EdgeInsets.all(8.0),
child: Container(
height:200,
decoration:BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment: Alignment.center,
child: Text('Testausgabe2'),
),
),
),
],
),
),
);
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final List<String> items = <String>['Protokoll auswählen', 'MMF', 'MM','MMB','AA','AAN'];
String selectedItem = 'Protokoll auswählen';
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child:DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: selectedItem,
onChanged: (String string) => setState(() => selectedItem = string),
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return Text(item,
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.right,
);
}).toList();
},
items: items.map((String item) {
return DropdownMenuItem<String>(
child: Text('$item',
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.right,
),
value: item,
);
}).toList(),
),
),
);
}
}
You are looking for state management.
This is the point in the flutter journey where things can get quite complicated compared to how relatively easy and quick it is to build UI.
Here is a good tutorial on state management: https://www.youtube.com/watch?v=jdUBV7AWL2U
I've updated your code with the simplest form of state management (streamBuilder).
import 'package:flutter/material.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';
void main() => runApp(MyApp());
StreamController streamController = StreamController();
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Dosierungsrechner';
Color c = const Color.fromRGBO(17, 29, 78, 1.0);
Color b = const Color.fromRGBO(223, 240, 250, 1.0);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title),
centerTitle: true,
backgroundColor: c,
),
body: Column(
children: [
Align(
alignment: Alignment.topCenter,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 60,
decoration: BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment: Alignment.bottomCenter,
child: MyStatefulWidget(),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 40,
decoration: BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Anzahl der Mäuse:',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Flexible(
child: SpinBox(
min: 0,
max: 100,
value: 0,
onChanged: (value) => print(value),
),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 40,
decoration: BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Gewicht/Maus in g:',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Flexible(
child: SpinBox(
min: 0,
max: 50,
value: 0,
onChanged: (value) => print(value),
),
),
],
),
),
),
],
),
),
Text('Anzumischende Bestandteile',
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 200,
decoration: BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment: Alignment.center,
child: StreamBuilder(
stream: streamController.stream,
builder: (context, snapshot) {
return updateBestandteile(snapshot.data);
},
),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 200,
decoration: BoxDecoration(
color: b,
borderRadius: BorderRadius.circular(10.0)
),
child: Align(
alignment: Alignment.center,
child: Text('Testausgabe2'),
),
),
),
],
),
),
);
}
Column updateBestandteile(String i) {
switch (i) {
case "MMF":
{
return Column(
children: [
Text('Midazolam 5mg/ml'),
Text('Medetomidin 5mg/ml'),
Text('Fentanyl 1mg/ml'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);
}
break;
case "MM":
{
return Column(
children: [
Text('MM'),
Text('MM'),
Text('MM'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);
}
break;
case "MMB":
{
return Column(
children: [
Text('MMB'),
Text('MMB'),
Text('MMB'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);
}
break;
case "AA":
{
return Column(
children: [
Text('AA'),
Text('AA'),
Text('AA'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);
}
break;
case "AAN":
{
return Column(
children: [
Text('AAN'),
Text('AAN'),
Text('AAN'),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);
}
break;
default: { return Column(
children: [
Text('No choice made'),
Text(''),
Text(''),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
);}
break;
}
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final List<String> items = <String>['Protokoll auswählen', 'MMF', 'MM','MMB','AA','AAN'];
String selectedItem = 'Protokoll auswählen';
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child:DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: selectedItem,
onChanged: (String string) => setState(() {
streamController.sink.add(string);
return selectedItem = string;
}),
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return Text(item,
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.right,
);
}).toList();
},
items: items.map((String item) {
return DropdownMenuItem<String>(
child: Text('$item',
style: TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.right,
),
value: item,
);
}).toList(),
),
),
);
}
}

Flutter always needing a hot reload

I'm making an app. I'm getting data from the URL and try to show. But I need to hot reload to see.
These are my codes:
import 'package:flutter/material.dart';
import 'widgets/half_category_widget.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
var searchCat;
var baslik="Ana Sayfa";
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
home: FirstApp(),
));
createCategory();
createProduct();
}
void runCat(id){
searchCat=id+1;
searchProds();
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
home: CatProds(),
));
}
class FirstApp extends StatefulWidget {
#override
_FirstAppState createState() => _FirstAppState();
}
List<Widget> menu = new List<Widget>();
Future createCategory() async{
var url = 'https://recepabi.com/pc/getCatKafe';
http.Response response = await http.get(url);
var data = (response.body).toString().split('-');
for(var i=0;i<data.length-1;i++){
menu.add(Expanded(
child: Padding(
padding: const EdgeInsets.all(4.0),
child:
InkWell(onTap: () {
print("ID:" + i.toString());
runCat(i);
baslik=data[i];
},
child: Container(
height: 100.0,
width: 100.0,
child: Column(
children: <Widget>[
HalfCategory(Colors.blue, Icons.menu, data[i]),
],
),
),
) ,
),
));
}
}
List<Widget> products = new List<Widget>();
List<Widget> products1 = new List<Widget>();
Future createProduct() async{
var url = 'https://recepabi.com/pc/getProdKafe';
http.Response response = await http.get(url);
var data = (response.body).toString().split('ğ');
for(var i=0;i<data.length-1;i++){
var prod=data[i].split("ı");
var ad=prod[0];
var birim=prod[1];
var kategori=prod[2];
var fiyat=prod[3];
var resim=prod[4];
var myr=Row(children: <Widget>[Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 5.0, right: 5.0 ),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Image.network(
resim,
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
height: 200.0,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0,bottom: 16.0),
child: Text(
ad.toUpperCase(),
maxLines: 1,
style: TextStyle(fontSize: 25.0),
textAlign: TextAlign.center,
),
)
],
),
),
),],);
products1.add(myr);
}
}
class _FirstAppState extends State<FirstApp> {
int _index = 0;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Kafeex"),
centerTitle: true,
backgroundColor: Colors.red,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _index,
onTap: (int index) {
setState(() {
_index = index;
if(_index==0)
{
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => FirstApp()),
(Route<dynamic> route) => false,
);
}
else if(_index==1)
{
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
(Route<dynamic> route) => false,
);
}
});
},
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.fastfood),
title: new Text('Sipariş'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.shopping_cart),
title: new Text('Sepet'),
),
],
),
body: Padding(
padding: const EdgeInsets.all(2.0),
child: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
Row(
children:menu
),
SizedBox(
height: 8.0,
),
Padding(
padding: const EdgeInsets.all(6.0),
child: Row(
children: <Widget>[Expanded(
child: Text(baslik,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.start,
),
),],
),
),
SizedBox(
height: 10.0,
),
Column(
children: products1
),
],
),
)
);
}
}
class SecondRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
);
}
}
class CatProds extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Kafeex"),
centerTitle: true,
backgroundColor: Colors.red,
),
body: Padding(
padding: const EdgeInsets.all(2.0),
child: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
Row(
children:menu
),
SizedBox(
height: 8.0,
),
Padding(
padding: const EdgeInsets.all(6.0),
child: Row(
children: <Widget>[Expanded(
child: Text(baslik,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.start,
),
),],
),
),
SizedBox(
height: 10.0,
),
Column(
children: searchProd
),
],
),
)
);
}
}
List<Widget> searchProd = new List<Widget>();
Future searchProds() async{
var url = 'https://recepabi.com/pc/searchProdKafe/'+searchCat.toString();
print(url);
http.Response response = await http.get(url);
var data = (response.body).toString().split('ğ');
for(var i=0;i<data.length-1;i++){
var prod=data[i].split("ı");
var ad=prod[0];
var birim=prod[1];
var kategori=prod[2];
var fiyat=prod[3];
var resim=prod[4];
var myr2=Row(children: <Widget>[Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 5.0, right: 5.0 ),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Image.network(
resim,
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
height: 200.0,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0,bottom: 16.0),
child: Text(
ad.toUpperCase(),
maxLines: 1,
style: TextStyle(fontSize: 25.0),
textAlign: TextAlign.center,
),
)
],
),
),
),],);
searchProd.add(myr2);
searchCat=0;
}
}
For example: I get the data from URL(createCategory()). I put the data to list(menu) and try to show on the widget(_FirstAppState's widget). But first, run nothing appears. On the second run(by hot reloading) it appears.
How do I prevent this?
The problem here is u r calling createCategory(); & createProduct(); functions in main() function if u change some code in those methods u need to call main() method again which is not possible in hot reload which only changes state & some widget
so for calling main() method again u need to perform hot restart