StreamBuilder TextField does not update its value when changed elsewhere - dart

I have a reactive login form following the BLOC pattern. I'm trying to programmatically clear all the values in it. In my Bloc, my submit function passes empty strings to my stream sinks:
class Bloc with Validators {
final _email = BehaviorSubject<String>();
final _password = BehaviorSubject<String>();
Stream<String> get email => _email.stream.transform(validateEmail);
Stream<String> get password => _password.stream.transform(validatePassword);
Stream<bool> get submitValid => Observable.combineLatest2(email, password, (String e, String p) {
var valid = (e != null && e.isNotEmpty)
&& (p != null && p.isNotEmpty);
print('$e && $p = $valid');
return valid;
});
Function(String) get changeEmail => _email.sink.add;
Function(String) get changePassword => _password.sink.add;
submit() {
final validEmail = _email.value;
final validPassword = _email.value;
print('final values: $validEmail && $validPassword');
changeEmail('');
changePassword('');
}
dispose() {
_email.close();
_password.close();
}
}
When I press the submit button that calls this submit() function, I get the error messages for both of the text fields, because the values of email and password have changed behind the scenes, but they are not visually updated in the TextFields. Here are my StreamBuilders for my TextFields and Submit button:
Widget emailField(Bloc bloc) {
return StreamBuilder(
stream: bloc.email,
builder: (context, snapshot) { // re-runs build function every time the stream emits a new value
return TextField(
onChanged: bloc.changeEmail,
autocorrect: false,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
icon: Icon(Icons.email),
hintText: 'email address (you#example.com)',
labelText: 'Email',
errorText: snapshot.error
)
);
}
);
}
Widget passwordField(Bloc bloc) {
return StreamBuilder(
stream: bloc.password,
builder: (context, AsyncSnapshot<String> snapshot) {
return TextField(
onChanged: bloc.changePassword,
autocorrect: false,
obscureText: true,
decoration: InputDecoration(
icon: Icon(Icons.security),
hintText: 'must be greater than 6 characters',
labelText: 'Password',
errorText: snapshot.error
)
);
}
);
}
Widget submitButton(Bloc bloc) {
return StreamBuilder(
stream: bloc.submitValid,
builder: (context, snapshot) {
return RaisedButton(
child: Text('Logins'),
color: Colors.blue,
onPressed: !snapshot.hasData || snapshot.hasError || snapshot.data == false
? null
: bloc.submit
);
}
);
}'
And here is the code I'm using for my validators in my Bloc:
class Validators {
final validateEmail = StreamTransformer<String, String>.fromHandlers(
handleData: (email, sink) {
RegExp exp = new RegExp(r"^[a-zA-Z0-9.]+#[a-zA-Z0-9]+\.[a-zA-Z]+");
var valid = exp.hasMatch(email);
if (valid) {
sink.add(email);
} else {
sink.add('');
sink.addError('Invalid email address!');
}
}
);
final validatePassword = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink) {
var valid = password.length >= 6;
if (valid) {
sink.add(password);
} else {
sink.add('');
sink.addError('Password must be at least 6 characters long!');
}
}
);
}
In my validators, I emit an empty string whenever there is an error. This makes it so the submitValid getter works when the user invalidates something that used to be valid.

I know it's been a long time, but that's my way for solving it.
First, I've created a TextEditingController for my TextField. Then I've created two methods on my BLoC: updateTextOnChanged and updateTextElsewhere. On the fisrt one I just retrieved the value (because I need it to use later). On the second one I added a sink to update the controller on TextField.
Widget:
return StreamBuilder<String>(
stream: bloc.streamText,
builder: (context, snapshot) {
_controller.text = snapshot.data;
return Expanded(
child: TextField(
controller: _controller,
onChanged: (value) => {bloc.updateTextOnChanged(value)},
),
);
}
);
Bloc:
Stream<String> get streamText => _controllerTxt.stream;
String _myText;
void updateTextElsewhere(String value) {
_controllerTxt.sink.add(value);
}
void updateTextOnChanged(String value) {
_myText = value;
}
Then you just need to call updateTextElsewhere() whenever you need to update it outside onChanged.
In you're case just add an empty string like: updateTextElsewhere("");

In submit(), you seem like reseting username and password
changeEmail('');
changePassword('');
And as you commented , 're-runs build function every time the stream emits a new value'. It re-builds UI since the value updated to empty. Maybe does it cause the problem?

Related

How to handle TextField validation in password in Flutter

I created a login page and I need to add these things to my password. How do I do it with validation alert message?
Minimum 1 Upper case
Minimum 1 lowercase
Minimum 1 Numeric Number
Minimum 1 Special Character
Common Allow Character ( ! # # $ & * ~ )
Your regular expression should look like:
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$
Here is an explanation:
r'^
(?=.*[A-Z]) // should contain at least one upper case
(?=.*[a-z]) // should contain at least one lower case
(?=.*?[0-9]) // should contain at least one digit
(?=.*?[!##\$&*~]) // should contain at least one Special character
.{8,} // Must be at least 8 characters in length
$
Match above expression with your password string. Using this method-
String? validatePassword(String value) {
RegExp regex =
RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$');
if (value.isEmpty) {
return 'Please enter password';
} else {
if (!regex.hasMatch(value)) {
return 'Enter valid password';
} else {
return null;
}
}
}
You need to use Regular Expression to validate the structure.
bool validateStructure(String value){
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value);
}
output:
Vignesh123! : true
vignesh123 : false
VIGNESH123! : false
vignesh# : false
12345678? : false
This function will validate the passed value is having the structure or not.
var _usernameController = TextEditingController();
String _usernameError;
...
#override
Widget build(BuildContext context) {
return
...
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
hintText: "Username", errorText: _usernameError),
style: TextStyle(fontSize: 18.0),
),
Container(
width: double.infinity,
height: 50.0,
child: RaisedButton(
onPressed: validate,
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
color: Theme.of(context).primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
),
),
...
}
...
validate(){
if(!validateStructure(_usernameController.text)){
setState(() {
_usernameError = emailError;
_passwordError = passwordError;
});
// show dialog/snackbar to get user attention.
return;
}
// Continue
}
You have to use TextFormField widget with validator property.
TextFormField(
validator: (value) {
// add your custom validation here.
if (value.isEmpty) {
return 'Please enter some text';
}
if (value.length < 3) {
return 'Must be more than 2 charater';
}
},
),
Take a look on official docs: https://flutter.dev/docs/cookbook/forms/validation
You can achieve this using below flutter plugin.
wc_form_validators
You can use it something like this:
TextFormField(
decoration: InputDecoration(
labelText: 'Password',
),
validator: Validators.compose([
Validators.required('Password is required'),
Validators.patternString(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$', 'Invalid Password')
]),
),
Its documentation is really good. You can read it for more util functions like this.
By using extension in dart
extension PasswordValidator on String {
bool isValidPassword() {
return RegExp(
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$')
.hasMatch(this);
}
}
You can apply this in your textfield like
TextFormField(
autovalidate: true,
validator: (input) => input. isValidPassword() ? null : "Check your password...",
)
here is the complete answer
Write a Dart program to check whether a string is a valid password. a. A password must have at least ten characters. b. A password
consists of only letters and digits. c. A password must contain at
least two digits.
import 'dart:io';
main() {
var password;
stdout.write("Enter You'r Password: ");
password=stdin.readLineSync();
if(password.length>=10 && !password.contains(RegExp(r'\W')) && RegExp(r'\d+\w*\d+').hasMatch(password))
{
print(" \n\t$password is Valid Password");
}
else
{
print("\n\t$password is Invalid Password");
}
Flutter Login Validation
///creating Username and Password Controller.
TextEditingController username=TextEditingController();
TextEditingController password=TextEditingController();
Form(
child: Builder(
builder: (context) {
return Column(
children: [
TextFormField(
controller: username,
validator: (CurrentValue){
var nonNullValue=CurrentValue??'';
if(nonNullValue.isEmpty){
return ("username is required");
}
if(!nonNullValue.contains("#")){
return ("username should contains #");
}
return null;
},
),
TextFormField(
controller: password,
validator: (PassCurrentValue){
RegExp regex=RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$');
var passNonNullValue=PassCurrentValue??"";
if(passNonNullValue.isEmpty){
return ("Password is required");
}
else if(passNonNullValue.length<6){
return ("Password Must be more than 5 characters");
}
else if(!regex.hasMatch(passNonNullValue)){
return ("Password should contain upper,lower,digit and Special character ");
}
return null;
},
),
ElevatedButton(onPressed: (){
if(Form.of(context)?.validate()?? false){
Navigator.of(context).push(MaterialPageRoute(builder: (_)=>loginpage()));
}
}, child: Text("Login"))
],
);
}
),
)
in this picture you can see when you Enter inValid username and password it will not Navigate to another page.
when you Enter Valid Username and Password it will Navigate to another Page.
this is the best regx
bool passValid = RegExp("^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##\$%^&*(),.?:{}|<>]).*").hasMatch(value);
if (value.isEmpty ||!passValid)
{
return 'error';
}

Flutter List + Pull to load more data is not waiting for data to load before it finishes causing the list / scrolling to become unstable

If you make a new Flutter project and include the dependencies and then replace your main.dart file you should be where I am on this question.
I left the original load: with Future.delayed but it doesn't seem to matter. I know partially what my problem is but am unable to come up with a better solution.
1) I don't seem to be using my snapshot.data and instead I am just making a empty List with str and then i just addAll into it and use that. So i'd love to not do that, i originally was using snapshot.data but ran into problems when I tried to "pull to load more data" which happens after you scroll to the bottom of the list.
The problem with my current method of doing this is that if you pull to load more users and then try to pull again before the users have loaded, The app breaks and doesn't wait for the data to properly load. I believe that I need to be doing that all in the load: of this library easy_refresh... but I am not sure how to rewrite my code to accomplish that.
How can I get my data to load with snapshot.data and then when I pull to refresh, I append 100 more users to that list but the UI waits for the list to update before it finishes the load. Would I be better off just putting a Blocking UI element and after the str list updates? and when new users are loaded I unblock the UI? which sorta feels hackish and not the correct way to solve this. The plugin itself should be able to do the loading and when its ready it stops the spinner under the list and says "finished".
pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_easyrefresh: ^1.2.7
http: ^0.12.0+2
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
backgroundColor: Colors.white
),
home: DuelLeaderBoards(),
);
}
}
class DuelLeaderBoards extends StatefulWidget {
#override
_DuelLeaderBoardsState createState() => _DuelLeaderBoardsState();
}
class _DuelLeaderBoardsState extends State<DuelLeaderBoards> {
List<Entry> str = [];
GlobalKey<EasyRefreshState> _easyRefreshKey = new GlobalKey<EasyRefreshState>();
GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();
GlobalKey<RefreshHeaderState> _connectorHeaderKey = new GlobalKey<RefreshHeaderState>();
GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();
GlobalKey<RefreshFooterState> _connectorFooterKey = new GlobalKey<RefreshFooterState>();
Future<LeaderBoards> getLeaderBoards(start) async {
String apiURL = 'https://stats.quake.com/api/v2/Leaderboard?from=$start&board=duel&season=current';
final response = await http.get(apiURL);
if (response.statusCode == 200) {
final responseBody = leaderBoardsFromJson(response.body);
return responseBody;
} else {
throw Exception('Failed to load Data');
}
}
void updateLeaderBoardList(e) async {
setState(() {
str.addAll(e.entries);
});
}
#override
void initState() {
getLeaderBoards(0).then((onValue) => str = onValue.entries );
super.initState();
}
#override
Widget build(BuildContext context) {
Widget header = ClassicsHeader(
key: _headerKey,
refreshText: "pullToRefresh",
refreshReadyText: "releaseToRefresh",
refreshingText: "refreshing...",
refreshedText: "refreshed",
moreInfo: "updateAt",
bgColor: Colors.transparent,
textColor: Colors.white,
);
Widget footer = ClassicsFooter(
key: _footerKey,
loadHeight: 50.0,
loadText: "pushToLoad",
loadReadyText: "releaseToLoad",
loadingText: "loading",
loadedText: "loaded",
noMoreText: "Finished",
moreInfo: "updateAt",
bgColor: Colors.transparent,
textColor: Colors.white,
);
return FutureBuilder(
future: getLeaderBoards(0),
builder:
(BuildContext context, AsyncSnapshot<LeaderBoards> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Builder(builder: (BuildContext context) {
return Center(
child: new EasyRefresh(
key: _easyRefreshKey,
behavior: ScrollOverBehavior(),
refreshHeader: ConnectorHeader(
key: _connectorHeaderKey,
header: header,
),
refreshFooter: ConnectorFooter(
key: _connectorFooterKey,
footer: footer,
),
child: CustomScrollView(
semanticChildCount: str.length,
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(<Widget>[header]),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return new Container(
height: 70.0,
child: Card(
child: new Text(
'${index+1}: ${str[index].userName}',
style: new TextStyle(fontSize: 18.0),
),
));
},
childCount: str.length,
)),
SliverList(
delegate: SliverChildListDelegate(<Widget>[footer]),
)
],
),
onRefresh: () async {
await new Future.delayed(const Duration(seconds: 0), () {
setState(() {});
});
},
loadMore: () async {
getLeaderBoards(str.length).then((onValue) => {
updateLeaderBoardList(onValue)
});
},
// loadMore: () async {
// await new Future.delayed(const Duration(seconds: 0), () {
// getLeaderBoards(str.length).then((onValue) => {
// updateLeaderBoardList(onValue)
// });
// });
// },
)
);
});
}
});
}
}
LeaderBoards leaderBoardsFromJson(String str) {
final jsonData = json.decode(str);
return LeaderBoards.fromJson(jsonData);
}
String leaderBoardsToJson(LeaderBoards data) {
final dyn = data.toJson();
return json.encode(dyn);
}
class LeaderBoards {
String boardType;
List<Entry> entries;
int totalEntries;
LeaderBoards({
this.boardType,
this.entries,
this.totalEntries,
});
factory LeaderBoards.fromJson(Map<String, dynamic> json) => new LeaderBoards(
boardType: json["boardType"] == null ? null : json["boardType"],
entries: json["entries"] == null ? null : new List<Entry>.from(json["entries"].map((x) => Entry.fromJson(x))),
totalEntries: json["totalEntries"] == null ? null : json["totalEntries"],
);
Map<String, dynamic> toJson() => {
"boardType": boardType == null ? null : boardType,
"entries": entries == null ? null : new List<dynamic>.from(entries.map((x) => x.toJson())),
"totalEntries": totalEntries == null ? null : totalEntries,
};
}
class Entry {
String userName;
int eloRating;
String profileIconId;
String namePlateId;
Entry({
this.userName,
this.eloRating,
this.profileIconId,
this.namePlateId,
});
factory Entry.fromJson(Map<String, dynamic> json) => new Entry(
userName: json["userName"] == null ? null : json["userName"],
eloRating: json["eloRating"] == null ? null : json["eloRating"],
profileIconId: json["profileIconId"] == null ? null : json["profileIconId"],
namePlateId: json["namePlateId"] == null ? null : json["namePlateId"],
);
Map<String, dynamic> toJson() => {
"userName": userName == null ? null : userName,
"eloRating": eloRating == null ? null : eloRating,
"profileIconId": profileIconId == null ? null : profileIconId,
"namePlateId": namePlateId == null ? null : namePlateId,
};
}
I looked at the documentation of loadMore. Since it says that the body of the function assigned to loadMore should be async, you do not need to use then:
loadMore: () async {
final result = await getLeaderBoards(str.length);
updateLeaderboardList(result);
},
loadMore: () async {
await getLeaderBoards(str.length).then((onValue) => {
updateLeaderboardList(onValue)
});
},
but putting "await" my loader waits for the function to complete before it finishes the animation.

Change application locale programmatically

I need to change application locale programmatically when button pressed
my code :
MaterialApp(
localizationsDelegates: [
_newLocaleDelegate,
const AppTranslationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''),
const Locale('ar', ''),
],
locale: mylocale,
title: appTitle,
home: Scaffold(
body: new MyCustomForm(),
),
debugShowCheckedModeBanner: false
);
new MaterialButton(
onPressed: () {
setState(() {
mylocale=Locale("ar","");
_newLocaleDelegate = AppTranslationsDelegate(newLocale:mylocale);
});
},
),
translation code :
AppTranslations.of(context).text("text")
AppTranslations Class:
class AppTranslations {
Locale locale;
static Map<dynamic, dynamic> _localisedValues;
AppTranslations(Locale locale) {
this.locale = locale;
_localisedValues = null;
}
static AppTranslations of(BuildContext context) {
return Localizations.of<AppTranslations>(context, AppTranslations);
}
static Future<AppTranslations> load(Locale locale) async {
AppTranslations appTranslations = AppTranslations(locale);
String jsonContent =
await rootBundle.loadString("assets/locale/localization_${locale.languageCode}.json");
_localisedValues = json.decode(jsonContent);
return appTranslations;
}
get currentLanguage => locale.languageCode;
String text(String key) {
print(key);
if(_localisedValues!=null)
return _localisedValues[key] ?? "$key";
else
return key;
}
}
my problem :
when Locale change page direction changed without translation ,
to get effect translation need to refresh page or go to another page and return back,
any help
Could you try wrapping your MaterialApp in an AnimatedSwitcher like so:
AnimatedSwitcher(
// Following two fields for your reference
// duration: const Duration(milliseconds: 500),
// transitionBuilder: (Widget child, Animation<double> animation) {
// return ScaleTransition(child: child, scale: animation);
// },
child: MaterialApp(
// As before, the same code, however:
key: ValueKey<Locale>(mylocale),
)
)
BTW, good practice to prefix private variables with an underscore, e.g. _myLocale.

Is it possible to require a Dropdown selection as part of form validation in Flutter?

I'm familiar with form validation using a TextFormField in Flutter, but is it possible to integrate a DropdownButton into a Form and require one of its value be selected before submission?
Basically, integrate DropdownButton validation into this basic Flutter validation example:
https://flutter.io/cookbook/forms/validation/
Dart Package have already the widget DropdownButtonFormField for this. Here is an example of how to use it:
List<String> typeNeg = [
"One",
"Two",
"Three",];
String dropdownValue = "One";
DropdownButtonFormField<String>(
value: dropdownValue,
hint: Text("Type of business"),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
validator: (String value) {
if (value?.isEmpty ?? true) {
return 'Please enter a valid type of business';
}
},
items: typeNeg
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onSaved: (val) => setState(() => _user.typeNeg = val),
),
The user model is as follows:
class User {
int id;
String name;
String email;
String typeNeg;
User({this.id, this.name, this.email, this.typeNeg});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return User(
id: parsedJson["id"],
name: parsedJson["name"] as String,
email: parsedJson["email"] as String,
typeNeg: parsedJson["typeNeg"] as String,
);
}
save(){
print("User saved");
}
}
To try the validator option change String dropdownValue = "One"; to String dropdownValue = null;
From text_form_field.dart file in Flutter's source code you can see that TextFormField is no more than a FormField emitting a TextField widget in its builder callback. You can write your own DropdownFormField using a similar pattern. Here's mine:
import 'package:flutter/material.dart';
class DropdownFormField<T> extends FormField<T> {
DropdownFormField({
Key key,
InputDecoration decoration,
T initialValue,
List<DropdownMenuItem<T>> items,
bool autovalidate = false,
FormFieldSetter<T> onSaved,
FormFieldValidator<T> validator,
}) : super(
key: key,
onSaved: onSaved,
validator: validator,
autovalidate: autovalidate,
initialValue: items.contains(initialValue) ? initialValue : null,
builder: (FormFieldState<T> field) {
final InputDecoration effectiveDecoration = (decoration ?? const InputDecoration())
.applyDefaults(Theme.of(field.context).inputDecorationTheme);
return InputDecorator(
decoration:
effectiveDecoration.copyWith(errorText: field.hasError ? field.errorText : null),
isEmpty: field.value == '' || field.value == null,
child: DropdownButtonHideUnderline(
child: DropdownButton<T>(
value: field.value,
isDense: true,
onChanged: field.didChange,
items: items.toList(),
),
),
);
},
);
}
The key is to bind DropdownButton's onChanged to field.didChange. Usage is pretty straightforward:
DropdownFormField<String>(
validator: (value) {
if (value == null) {
return 'Required';
}
},
onSaved: (value) {
// ...
},
decoration: InputDecoration(
border: UnderlineInputBorder(),
filled: true,
labelText: 'Demo',
),
initialValue: null,
items: [
DropdownMenuItem<String>(
value: '1',
child: Text('1'),
),
DropdownMenuItem<String>(
value: '2',
child: Text('2'),
)
],
),
I got the idea from this site. The difference is that my version of DropdownFormField is closer to Flutter's native implementation (which extends TextFormField instead of wrapping it inside a StatefulWidget).

Flutter setState() make a loop to be always recalled

I have a code like this below, the simple flow is I make a loop from a list of objects to create some widgets.
class ScoringAttribute {
int _id;
bool _isdelete;
double _scorehigh, _scorelow, _scorevalue;
String _name, _scoretype, _description, _title;
}
class HomePageState extends State<HomePage> with TickerProviderStateMixin {
List dataScoringAttributes;
List<ScoringAttribute> listScoringAttributeObjects = new List<ScoringAttribute>();
final String urlPresentation = ".../.resentations/getPresentations";
final String urlScoringAttribute = ".../.scoringattributes/getScoringattributes";
Future<String> getPresentationData() async {
var responseScoringAttribute = await http.get(
Uri.encodeFull(urlScoringAttribute),
headers: {"Accept": "application/json"}
);
var scoringAttributeJson = json.decode(responseScoringAttribute.body);
dataScoringAttributes = scoringAttributeJson['scoringattributes'];
for(int i = 0; i < dataScoringAttributes.length; i++) {
var scoringAttributeObject = new ScoringAttribute();
scoringAttributeObject._id = dataScoringAttributes[i]["id"];
scoringAttributeObject._description = dataScoringAttributes[i]["iddescription"];
scoringAttributeObject._isdelete = dataScoringAttributes[i]["isdelete"];
scoringAttributeObject._name = dataScoringAttributes[i]["name"];
scoringAttributeObject._scorehigh = double.parse(dataScoringAttributes[i]["scorehigh"].toString());
scoringAttributeObject._scorelow = double.parse(dataScoringAttributes[i]["scorelow"].toString());
scoringAttributeObject._scoretype = dataScoringAttributes[i]["scoretype"];
scoringAttributeObject._title = dataScoringAttributes[i]["title"];
scoringAttributeObject._scorevalue = double.parse(dataScoringAttributes[i]["scorelow"].toString());
listScoringAttributeObjects.add(scoringAttributeObject);
}
return "Success";
}
List<Widget> scoringAttributeList() {
List<Widget> list = new List();
for(int i = 0; i < listScoringAttributeObjects.length; i++) {
if(listScoringAttributeObjects[i]._scoretype == "slider") {
list.add(
new Container(
child: new Column(
children: <Widget>[
new Column(
children: <Widget>[
//THE SLIDER VALUE TEXT
new Text(
//CONVERT DOUBLE TYPE TO STRING WITHOUT DECIMAL POINTS
listScoringAttributeObjects[i]._scorevalue.toStringAsFixed(listScoringAttributeObjects[i]._scorevalue.truncateToDouble() == listScoringAttributeObjects[i]._scorevalue ? 0 : 0),
style: new TextStyle(
fontSize: 28.0,
),
),
//THE SLIDER
new Slider(
activeColor: Colors.blueAccent,
inactiveColor: const Color(0xFFb7d2e0),
min: double.parse(listScoringAttributeObjects[i]._scorelow.toString()),
max: double.parse(listScoringAttributeObjects[i]._scorehigh.toString()),
value: double.parse(listScoringAttributeObjects[i]._scorevalue.toString()),
onChanged: (double value) {
setState(() {
listScoringAttributeObjects[i]._scorevalue = double.parse(value.round().toString());
});
},
),
],
),
],
),
),
);
}
else if(listScoringAttributeObjects[i]._scoretype == "text_field") {
list.add(...);
}
else if(listScoringAttributeObjects[i]._scoretype == "stars") {
list.add(...);
}
else if(listScoringAttributeObjects[i]._scoretype == "thumb") {
list.add(new Container(...);
}
}
return list;
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: FutureBuilder<String> (
future: getPresentationData(),
builder: (context, snapshot) {
if(snapshot.hasData) {
return new Column(
children: <Widget>[
new Column(
children: scoringAttributeList(),
),
],
),
}
},
),
);
}
}
There are some different widgets depending on the type, and there are 4 types, and 1 type might have more than 1 widget in it, so I make the loop depend on the data that it got from DB.
The problem is I don't know why every time I use setState() inside the loop, it always processes the loop again, so it'll be an infinite loop to create a new widget, and it'll duplicate the widget from the beginning (only happen when the setState() is called).
Ex: there are 4 data inside the List, and if the setState() is called, it'll show 8 data (show the first 4 data twice)
Here's the example of how I setState() into the data inside the List
onChanged: (double value) {
setState(() {
listScoringAttributeObjects[i]._scorevalue = double.parse(value.round().toString());
});
},
I think the problem is because I setState() into some data inside the List. So when the List state is changed, it'll re-render anything that is related to the List.
Is it true?
If yes, is there any other solution how to change my code?
If not, is there any mistake in my code or my logic maybe?
Thank you. Really looking forward to some solution about this, cause I really got stuck in this, and its already been a week :(
Simple move your getPresentationData() into state variable. So that it will get triggered only once.
class HomePageState extends State<HomePage> with TickerProviderStateMixin {
Future<String> _presentationFuture;
initState() {
_presentationFuture = getPresentationData()
}
//other contents
#override
Widget build(BuildContext context) {
return new Scaffold(
body: FutureBuilder<String> (
future: _presentationFuture,
builder: (context, snapshot) {
if(snapshot.hasData) {
Reason for duplicate: we can calling setState on Slider dataChange which will re-render the HomePageState which will again trigger the network call (getPresentationData())
Note: If you want to trigger network on slider change, clear the list before making a network call
Future<String> getPresentationData() async {
listScoringAttributeObjects = new List<ScoringAttribute>(); // clear data
var responseScoringAttribute = await http.get(
Uri.encodeFull(urlScoringAttribute),
headers: {"Accept": "application/json"}
);
I don't see how this would be related to the one setState() in your code. It is only called when the slider is used.
I think the problem is caused by list.add(...); in scoringAttributeList(). You shouldn't modify data when build() is executed.
You should assume that build() can be called repeatedly and at any time.
Build your code so that this doesn't cause issues when it happens.

Resources