Flutter Network Image, loading the same image - flutter

I'm trying to make an app that you enter an image size as string in an input field then it gives you a random image from https://picsum.photos/,
the problem is that if I put a string lets say '200',
the app load an image, when I use '200' another time the app give me the same image until I reload the whole app.
If there is a way to make the app load different image every time I press the button.
here is some code I used:
FadeInImage.assetNetwork(
placeholder: 'lib/img/loading.gif',
image: 'https://picsum.photos/${globals.imageSize}',
),
Container(
width: 100,
child: TextField(
decoration: InputDecoration(
hintText: 'Size:',
),
onChanged: (String str) {
globals.imageSize = str;
},
),
),
RaisedButton(
child: Text(
'Search',
style: TextStyle(color: Colors.white, fontSize: 15),
),
color: Colors.lightBlueAccent,
onPressed: () {
Navigator.of(context).pushNamed('search');
},
),

Use setState to update the value.
onChanged: (String str) {
setState(() {
str = globals.imageSize;
});
},

Related

Flutter web app not showing typed password when set to show password

On my flutter webapp I am trying to show the password if the user chose to show it. If I set my bool value to false it start by showing the normal text and then if I press the button to show or hide the password it will obscure the text but it will not un-obscure the text. I added a print function in one of my try's and it does change the bool value from false to true and back to false. I have it it a setState but no luck. I tryied many different examples online but can not get it to work with the web app.
The code
#override
Widget build(BuildContext context) {
c_width = MediaQuery.of(context).size.width*0.8;
return Scaffold(
appBar: AppBar(title: Text("App"),
),
body: signUpWidget(widget.signUpValue),
);
}
Widget signUpWidget(String? rl) {
switch(rl) {
case 'User': {
return SingleChildScrollView(
child: Container (
width: c_width,
padding: const EdgeInsets.all(16.0),
child: Column(
child: Column(
children: <Widget>[
TextFormField(
obscureText: isObscure,
decoration: InputDecoration(
suffix: TextButton(
child: isPasswordObscure
? Text(
'Show',
style: TextStyle(color: Colors.grey),
)
: Text(
'Hide',
style: TextStyle(color: Colors.grey),
),
onPressed: () {
setState(() {
isObscure = !isObscure;
isPasswordObscure = !isObscure;
});
},
),
),
),
Like I say it changes the text to hide and show and if I print the bool value it changes from true to false, but it does not unObscure the text in the field to show the password. Is it something to do with web? or am I missing something?
Thank you.
Actually you dont need to have two bool,
TextFormField(
obscureText: isObscure,
decoration: InputDecoration(
suffix: TextButton(
child: isObscure //< using
? Text(
'Show',
style: TextStyle(color: Colors.grey),
)
: Text(
'Hide',
style: TextStyle(color: Colors.grey),
),
onPressed: () {
setState(() {
isObscure = !isObscure;
// isPasswordObscure = !isObscure; // here it reverse the variable isPasswordObscure
});
},
),
),
)
It might be occurring due to this problem in setState((){}).
setState(() {
// assume isObscure is true initially
isObscure = !isObscure;
// now isObscure is false
isPasswordObscure = !isObscure;
// now isPasswordObscure is true, because isObscure's value has already changed.
});
To solve this, first save isObscure to a temporary variable.
setState(() {
var temp = isObscure;
isObscure = !temp;
isPasswordObscure = !temp;
});
Or,
Entirely avoid using two bools.
setState(() {
isObscure = !isObscure;
});
It seems like this occurs only in web.
Follow these steps to fix this,
https://github.com/flutter/flutter/issues/83695#issuecomment-1083537482
Or
Upgrade to the latest Flutter version.

When tap on textfield, app crashes returns homepage

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

how to get selections from multi_select_flutter?

has to be something simple I'm not getting but have been struggling on this for way too long. If anybody can help me out I would be appreciative. I believe it has to do with some kind of type issues as when I make selections I have a print statement that then prints out what I'm getting back:
[Instance of 'MultiSelectItem', Instance of 'Analysis', Instance of 'Analysis']
Not sure how to convert the above to a List of Analysis and not able to carry out per the example for the package:
MultiSelectDialogField(
items: _animals.map((e) => MultiSelectItem(e, e.name)).toList(),
listType: MultiSelectListType.CHIP,
onConfirm: (values) {
_selectedAnimals = values;
},
),
where I also have to use a 'cast' in my code. My attempt:
MultiSelectDialogField(
items: _analyses.map((analysis) => MultiSelectItem<Analysis>(analysis, analysis.name)).toList(),
initialValue: outwardsData.outwards[widget.index].lossFeed
.map((analysis) => MultiSelectItem<Analysis>(analysis, analysis.name))
.toList(),
title: Text(
"Loss Feeds:",
style: TextStyle(color: Colors.black),
),
selectedColor: kConvexGreen,
unselectedColor: kConvexLightGreen,
backgroundColor: kConvexGreen,
decoration: BoxDecoration(
color: kConvexGreen.withOpacity(0.1),
borderRadius: BorderRadius.all(Radius.circular(5)),
border: Border.all(
color: kConvexGreen,
width: 2,
),
),
confirmText: Text(
'Submit',
style: TextStyle(color: Colors.white),
),
cancelText: Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
searchable: true,
buttonText: Text("Loss Feeds"),
onSelectionChanged: (results) {
**print(results)**;
},
onConfirm: (results) {
// this is different than what example shows; without cast it errors
// "A value of type 'List<Object?>' can't be assigned to a variable of type 'List<Analysis>'". (Documentation)
_selectedAnalyses = results.cast();
},
chipDisplay: MultiSelectChipDisplay(
chipColor: kConvexGreen,
textStyle: TextStyle(color: Colors.white),
onTap: (value) {
setState(() {
_selectedAnalyses.remove(value);
// crashes here even though both are of same type List<Analyses> (theoretically)
// this is just here for testing purposes as am through many iterations trying to get
// data into lossFeed.
outwardsData.outwards[widget.index].lossFeed =
_selectedAnalyses;
});
},
),
),
I'm sure a more experienced flutter person will understand this (maybe) but I found that I couldn't just have the initial values come from the same list type used for the item (List< Analysis> _analyses) but I actually had to map it to use the same items data (_analyses).
initialValue: outwardsData.outwards[widget.index].lossFeed.map((analysis) => _analyses[analysis.id - 1]).toList()
Had other problems with this widget such as I found I couldn't map the results from onConfirm directly to List but instead had to do the following:
_rData.lossFeed = results.toList().cast<Analysis>()
as the data came back as List< dynamic>.
Couldn't find great examples online and trust experience will be the cure-all at some point.

On web, how do I control the visibility icon that automatically appears on a focused TextFormField that has an obscureText property set to true?

Here's my code for the password field:
TextFormField(
obscureText: isObscure,
decoration: InputDecoration(
suffix: TextButton(
child: isPasswordObscure
? Text(
'Show',
style: TextStyle(color: Colors.grey),
)
: Text(
'Hide',
style: TextStyle(color: Colors.grey),
),
onPressed: () {
setState(() { isObscure = !isObscure; });
},
),
),
)
If I run it, the password field would look like this:
If you review my code, I only specified a text button and not an icon as the suffix. The visibility icon was added by Flutter Edge and when I click on it, it only changes its icon and does not unobscure or obscure the text field.
What I want to know is how do I change or remove the icon? And maybe also give it a callback so it knows what to do when I click on it.
The problem doesn't exist on mobile, only on browsers desktop Edge.
Edit:
I tried setting suffix and suffixIcon to null but the visibility icon is still showing.
Update: I've discovered that the problem only exists on MS Edge.
If you wants to turn off the visibility icon set onPressed: () {},
also if you want to remove the visibility icon form overview wrap it with opacity widget
Opacity(
opacity: 0.0,
child: textButton(),
Please find the below code sample to include the visibility option for the textField. by including a variable _isObscured in a stateful widget. we have implemented it with the auto obscure after 2 second delay.
Center(child: TextField(
obscureText: _isObscured,
decoration : InputDecoration(
suffix:InkWell(
onTap: (){
setState(() => this._isObscured =
!this._isObscured);
Future.delayed(Duration(seconds: 2), (){
setState(() => this._isObscured =
!this._isObscured);
});
},
child: Icon( Icons.visibility),
),
),
),
),
),
I found a solution:
// the magic function
void fixEdgePasswordRevealButton(FocusNode passwordFocusNode) {
passwordFocusNode.unfocus();
Future.microtask(() {
passwordFocusNode.requestFocus();
js.context.callMethod("fixPasswordCss", []);
});
}
// widget code
child: TextField(
onChanged: (_) async {
fixEdgePasswordRevealButton(passwordFocusNode);
},
focusNode: passwordFocusNode,
obscureText: true,
// end of index.html
window.fixPasswordCss = () => {
let style = document.createElement('style');
style.innerHTML = '::-ms-reveal { display: none; }';
document.head.appendChild(style);
}
</script>
</body>
Also posted on the relevant issue.

text with \n and unicode literals saved in mysql do not work when displayed

I store a text string with \n and unicode literals like \u2022 in mysql, then retrieve it with http api call on flutter. When displaying it with Text widget, these escaped symbles do not show as expected. When I directly pass the string , it works. Could anyone help me out?
child: Column(
children: <Widget>[
Text(prompt.prompt_body, //This variable is from http call which does not work
textAlign: TextAlign.left,
style:TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
)),
Divider(),
Text("You live in a room in college which you share with another student.However, there are many problems with this arrangement and you find it very difficult to work.\n\nWrite a letter to the accommodation officer at the college. In the letter,\n\n \u2022 describe the situation\n \u2022 explain your problems and why it is difficult to work\n \u2022 say what kind of accommodation you would prefer", //this part works
textAlign: TextAlign.left,
style:TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
))
],
),
emulator screenshot
In response to Gunter's query, I add the following code on api call:
class PromptModel {
int id;
String prompt_body;
String prompt_image;
PromptModel(this.id, this.prompt_body, this.prompt_image);
PromptModel.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
prompt_body = parsedJson['prompt_body'];
prompt_image = parsedJson['prompt_image'];
}
}
....
class PromptListPageState extends State<PromptListPage> {
int counter = 0;
List<PromptModel> prompts = [];
void fetchImage() async {
counter++;
var response =
await get('http://10.0.2.2:8080/TestPrompt');
var promptModel = PromptModel.fromJson(json.decode(response.body));
setState(() {
prompts.add(promptModel);
});
}
The following is the response of the api call:
{"id":1,"prompt_body":"You live in a room in college which you share with another student.However, there are many problems with this arrangement and you find it very difficult to work.\\n\\nWrite a letter to the accommodation officer at the college. In the letter,\\n\\n \\u2022 describe the situation\\n \\u2022 explain your problems and why it is difficult to work\\n \\u2022 say what kind of accommodation you would prefer","prompt_image":"http://10.0.2.2:8080/test.jpg"}
I solved the problem by inputting the string from flutter using TextFormField. directly inserting the text on database side is tricky. The code is as below:
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
controller: myController,
maxLines: 5,
validator: (val) =>
(val == null || val.isEmpty) ? "请输入商品名称" : null,
decoration: const InputDecoration(
//icon: Icon(Icons.person),
hintText: 'add the prompt here:',
labelText: 'Prompt content',
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
),
onSaved: (val) => this.content = val,
),
new Container(
margin: const EdgeInsets.only(top: 10.0),
child: new RaisedButton(
onPressed: _save,
child: new Text('Save'),
),
)
]),
),
appBar: AppBar(
title: Text('Add Essay Prompt'),
),
),
);
}
}

Categories