How to set future String to 'initial value' of TextFormField - string

Hello Everyone i'm a beginner. I am facing a problem. Below is my code. I want to set Future String as initial value of TextFormField. I successfully did it for only one TextFormField but now i have multiple TextFormField and i tried to fetch data from every field of firebase document and set as initial value of corresponding TextFormField.
If i assign the value to TextFormField 'label' it shows correctly but when i assign the same value to 'initial value' it doesnot show.
Sorry for poor conversation
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:shop_app/components/custom_surfix_icon.dart';
import 'package:shop_app/components/default_button.dart';
import 'package:shop_app/components/form_error.dart';
import 'package:shop_app/size_config.dart';
import '../../../../../../constants.dart';
class EditProfileForm extends StatefulWidget {
#override
_EditProfileFormState createState() => _EditProfileFormState();
}
class _EditProfileFormState extends State<EditProfileForm> {
final _formKey = GlobalKey<FormState>();
final List<String> errors = [];
String name;
String phoneNo;
String gender;
String address;
String about;
String education;
String specialities;
String languages;
String work;
String storeName;
String storePhoneNo;
String storeGender;
String storeAddress;
String storeAbout;
String storeEducation;
String storeSpecialities;
String storeLanguages;
String storeWork;
static const menuItems = <String>[
'Male',
'Female',
'Other',
];
final List<DropdownMenuItem<String>> popUpMenuItem = menuItems
.map((String value) => DropdownMenuItem<String>(
value: value,
child: Text(value),
))
.toList();
void addError({String error}) {
if (!errors.contains(error))
setState(() {
errors.add(error);
});
}
void removeError({String error}) {
if (errors.contains(error))
setState(() {
errors.remove(error);
});
}
// #override
// void initState() {
// super.initState();
// getData();
// }
getData() {
getName();
getPhoneNo();
getAddress();
getAbout();
getEducation();
getSpecialities();
getLanguages();
getWork();
}
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
getNameFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getGenderFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getPhoneNoFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getAddressFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getAboutFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getEducationFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getSpecialitiesFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getLanguagesFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
getWorkFormField(),
FormError(errors: errors),
SizedBox(height: getProportionateScreenHeight(40)),
DefaultButton(
text: "Update Profile",
press: () async {
if (_formKey.currentState.validate()) {
print(storeName);
}
},
),
],
),
);
}
///////////////////////////////////////////////////////////////////////////////
Widget getNameFormField() {
return FutureBuilder(
future: getName(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
storeName = snapshot.data;
return TextFormField(
initialValue: storeName,
onSaved: (newValue) => name = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kNamelNullError);
}
name = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kNamelNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: storeName,
hintText: "Enter your name",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getName() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getName = document['Name'];
return getName;
}
///////////////////////////////////////////////////////////////////////////////
Widget getPhoneNoFormField() {
return FutureBuilder(
future: getPhoneNo(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot1) {
storePhoneNo = snapshot1.data;
return TextFormField(
initialValue: storePhoneNo,
onSaved: (newValue) => phoneNo = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kPhoneNumberNullError);
}
phoneNo = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kPhoneNumberNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Phone No",
hintText: "Enter Phone No",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Phone.svg"),
),
);
},
);
}
Future<String> getPhoneNo() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getPhoneNo = document['Phone Number'];
return getPhoneNo;
}
///////////////////////////////////////////////////////////////////////////////
DropdownButtonFormField getGenderFormField() {
return DropdownButtonFormField(
onSaved: (newValue) {
gender = newValue;
},
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kNamelNullError);
}
gender = value;
print(gender);
},
validator: (value) {
if (value.isEmpty) {
addError(error: kNamelNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Gender",
hintText: "Select your gender",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/gender.svg"),
),
items: popUpMenuItem,
);
}
Future<String> getGender() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getGender = document['Gender'];
return getGender;
}
///////////////////////////////////////////////////////////////////////////////
Widget getAddressFormField() {
return FutureBuilder(
future: getAddress(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot2) {
storeAddress = snapshot2.data;
return TextFormField(
initialValue: storeAddress,
onSaved: (newValue) => address = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kAddressNullError);
}
address = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kAddressNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Address",
hintText: "Enter your address",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Location point.svg"),
),
);
},
);
}
Future<String> getAddress() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getName = document['Address'];
return getName;
}
///////////////////////////////////////////////////////////////////////////////
Widget getAboutFormField() {
return FutureBuilder(
future: getAbout(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot3) {
storeAbout = snapshot3.data;
return TextFormField(
initialValue: storeAbout,
onSaved: (newValue) => about = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kAboutNullError);
}
about = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kAboutNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "About",
hintText: "Describe Yourself",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getAbout() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getAbout = document['About'];
return getAbout;
}
///////////////////////////////////////////////////////////////////////////////
Widget getEducationFormField() {
return FutureBuilder(
future: getEducation(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot4) {
storeEducation = snapshot4.data;
return TextFormField(
initialValue: storeEducation,
onSaved: (newValue) => education = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kEducationNullError);
}
education = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kEducationNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Education",
hintText: "Enter your education",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getEducation() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getEducation = document['Education'];
return getEducation;
}
///////////////////////////////////////////////////////////////////////////////
Widget getSpecialitiesFormField() {
return FutureBuilder(
future: getSpecialities(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot5) {
storeSpecialities = snapshot5.data;
return TextFormField(
initialValue: storeSpecialities,
onSaved: (newValue) => specialities = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kSkillsNullError);
}
specialities = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kSkillsNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Specialities",
hintText: "Enter your specialities",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getSpecialities() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getSpecialities = document['Specialities'];
return getSpecialities;
}
///////////////////////////////////////////////////////////////////////////////
Widget getLanguagesFormField() {
return FutureBuilder(
future: getLanguages(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot6) {
storeLanguages = snapshot6.data;
return TextFormField(
initialValue: storeLanguages,
onSaved: (newValue) => languages = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kLanguagesNullError);
}
languages = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kLanguagesNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Languages",
hintText: "Enter Your Languages",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getLanguages() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getLanguages = document['Languages'];
return getLanguages;
}
///////////////////////////////////////////////////////////////////////////////
Widget getWorkFormField() {
return FutureBuilder(
future: getWork(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot7) {
storeWork = snapshot7.data;
return TextFormField(
initialValue: storeWork,
onSaved: (newValue) => work = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kWorkNullError);
}
work= value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kWorkNullError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Work",
hintText: "What you do?",
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
),
);
},
);
}
Future<String> getWork() async {
DocumentSnapshot document = await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.email)
.get();
String getWork = document['Work'];
return getWork;
}
}

you can just call the function that returns you the Future String in the initState() and after that, you can set that string as TextInput hint

Related

pagination with ant design not updating the limit

I am trying to make a pagination table using an ant table. but I am not getting the result I want. I am always getting a limited number of data. can't really update the data limit dynamically. what i am doing wrong here? I am hardcoded the limit here how to do it dynamically ?? how can i fetch the data from data base i can show only 20 data on each page. also i have to show the available buttons
backend
export const getJourneyDetails = async (req, res) => {
try {
const page = parseInt(req.query.page || 1);
const perPage = parseInt(req.query.perPage || 100);
const search = req.query.search || "";
let JourneyDetails = await journey_details
.find({
Departure_Station_Name: { $regex: search, $options: "i" },
})
.skip((page - 1) * perPage)
.limit(perPage);
if (!JourneyDetails.length) {
JourneyDetails = await journey_details.find().limit(perPage);
}
const totalpages = Math.ceil(
(await journey_details.countDocuments()) / perPage
);
res.status(200).json({ JourneyDetails, totalpages });
frontend
import { CircularProgress } from "#mui/material";
import { useEffect, useState } from "react";
import type { ColumnsType } from "antd/es/table";
import { Table } from "antd";
import axios from "axios";
interface JourneyDetail {
Departure_time: String;
Return_time: String;
Departure_Station_Id: number;
Departure_Station_Name: String;
Return_Station_Id: number;
Return_Station_Name: String;
Distance: number;
Duration: number;
}
const JourneyData: React.FC = () => {
const [journeyDetails, setJourneyDetails] = useState<JourneyDetail[]>([]);
const [totalPages, setTotalPages] = useState(1);
const [searchQuery, setSearchQuery] = useState("");
const fetchData = async (page: number) => {
const { data } = await axios.get(
`https://helisinkicitybike.onrender.com/home/journey/?page=${page}&perPage=20&search=${searchQuery}
`
);
setJourneyDetails(data.JourneyDetails);
setTotalPages(data.totalPages);
};
useEffect(() => {
fetchData(1);
}, [searchQuery]);
const columns: ColumnsType<JourneyDetail> = [
{
title: "Departure time",
dataIndex: "Departure_time",
width: 100,
fixed: "left",
},
{
title: "Departure Station Name",
dataIndex: "Departure_Station_Name",
width: 100,
fixed: "left",
},
{
title: "Return time",
dataIndex: "Return_time",
width: 100,
fixed: "left",
},
{
title: "Return Station Name ",
dataIndex: "Return_Station_Name",
width: 100,
fixed: "left",
},
{
title: " Distance ",
dataIndex: "Distance",
width: 100,
fixed: "left",
},
{
title: "Duration ",
dataIndex: "Duration",
width: 100,
fixed: "left",
},
];
if (!journeyDetails) return <CircularProgress />;
return (
<div className="container mt-5">
<div className="input-group mb-3">
<span className="input-group-text" id="inputGroup-sizing-default">
Search
</span>
<input
placeholder=" Enter Station Name"
type="text"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<Table
columns={columns}
dataSource={journeyDetails}
pagination={{
pageSize: 10,
total: totalPages,
onChange: (page) => {
fetchData(page);
},
}}
/>
<p style={{ fontSize: "10px", marginTop: "5px" }}>
#Data source Helsinki City Bike, covers the period of May to July 2021.
</p>
</div>
);
};
export default JourneyData;
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error retrieving Journey Details" });
}
};

No errors for dropdown list, but still not working on Flutter

Here's my code for my sign in page on Flutter. I have no errors, but it's still not showing the dropdown list, does anyone know why?
I've used the auto-complete search method.
Here's what I've done so far :
Edited the pubspec.yaml
Imported the unilist.json (which I'm using)
Created a Plain Old Dart Object to represent json structure
And finally, edited my sign in dart file.
I'm having no errors so far, so I believe I'm missing something..
Thanks,
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:flutter/material.dart';
import 'package:shop_app/components/custom_surfix_icon.dart';
import 'package:shop_app/components/default_button.dart';
import 'package:shop_app/components/form_error.dart';
import 'package:shop_app/screens/complete_profile/complete_profile_screen.dart';
import 'package:shop_app/screens/sign_up/components/unilist.dart';
import '../../../constants.dart';
import '../../../size_config.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
TextEditingController controller = new TextEditingController();
class UniViewModel {
static List<UniName> uni;
static Future loadUni() async {
try {
uni = new List<UniName>();
String jsonString = await rootBundle.loadString('assets/unilist.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['uni'] as List;
for (int i = 0; i < categoryJson.length; i++) {
uni.add(new UniName.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}
}
class SignUpForm extends StatefulWidget {
#override
_SignUpFormState createState() => _SignUpFormState();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: AutoComplete(),
),
);
}
}
class AutoComplete extends StatefulWidget {
#override
_AutoCompleteState createState() => new _AutoCompleteState();
}
class _AutoCompleteState extends State<AutoComplete> {
GlobalKey<AutoCompleteTextFieldState<UniName>> key = new GlobalKey();
AutoCompleteTextField searchTextField;
TextEditingController controller = new TextEditingController();
_AutoCompleteState();
void _loadData() async {
await UniViewModel.loadUni();
}
#override
void initState() {
_loadData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text('Auto Complete List Demo'),
),
body: new Center(
child: new Column(children: <Widget>[
new Column(children: <Widget>[
searchTextField = AutoCompleteTextField<UniName>(
style: new TextStyle(color: Colors.black, fontSize: 16.0),
decoration: new InputDecoration(
suffixIcon: Container(
width: 85.0,
height: 60.0,
),
contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
filled: true,
hintText: 'Search Uni Name',
hintStyle: TextStyle(color: Colors.black)),
itemSubmitted: (item) {
setState(() => searchTextField.textField.controller.text =
item.nom_court);
},
clearOnSubmit: false,
key: key,
suggestions: UniViewModel.uni,
itemBuilder: (context, item) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(item.nom_court,
style: TextStyle(
fontSize: 16.0
),),
Padding(
padding: EdgeInsets.all(15.0),
),
Text(item.localisation,
)
],
);
},
itemSorter: (a, b) {
return a.nom_court.compareTo(b.nom_court);
},
itemFilter: (item, query) {
return item.nom_court
.toLowerCase()
.startsWith(query.toLowerCase());
}),
]),
])));
}
}
class _SignUpFormState extends State<SignUpForm> {
final _formKey = GlobalKey<FormState>();
String email;
String password;
String uni;
String conform_password;
bool remember = false;
final List<String> errors = [];
void addError({String error}) {
if (!errors.contains(error))
setState(() {
errors.add(error);
});
}
void removeError({String error}) {
if (errors.contains(error))
setState(() {
errors.remove(error);
});
}
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
buildEmailFormField(),
SizedBox(height: getProportionateScreenHeight(30)),
FormError(errors: errors),
SizedBox(height: getProportionateScreenHeight(40)),
DefaultButton(
text: "Continuer",
press: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
// if all are valid then go to success screen
Navigator.pushNamed(context, CompleteProfileScreen.routeName);
}
},
),
],
),
);
}
TextFormField buildConformPassFormField() {
return TextFormField(
obscureText: true,
onSaved: (newValue) => conform_password = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kPassNullError);
} else if (value.isNotEmpty && password == conform_password) {
removeError(error: kMatchPassError);
}
conform_password = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kPassNullError);
return "";
} else if ((password != value)) {
addError(error: kMatchPassError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Confirmez le mot de passe",
hintText: "Reconfirmez le mot de passe",
// If you are using latest version of flutter then lable text and hint text shown like this
// if you r using flutter less then 1.20.* then maybe this is not working properly
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Lock.svg"),
),
);
}
TextFormField buildPasswordFormField() {
return TextFormField(
obscureText: true,
onSaved: (newValue) => password = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kPassNullError);
} else if (value.length >= 8) {
removeError(error: kShortPassError);
}
password = value;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kPassNullError);
return "";
} else if (value.length < 8) {
addError(error: kShortPassError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Mot de passe",
hintText: "Saisissez votre mot de passe",
// If you are using latest version of flutter then lable text and hint text shown like this
// if you r using flutter less then 1.20.* then maybe this is not working properly
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Lock.svg"),
),
);
}
TextFormField buildEmailFormField() {
return TextFormField(
keyboardType: TextInputType.emailAddress,
onSaved: (newValue) => email = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kEmailNullError);
} else if (emailValidatorRegExp.hasMatch(value)) {
removeError(error: kInvalidEmailError);
}
return null;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kEmailNullError);
return "";
} else if (!emailValidatorRegExp.hasMatch(value)) {
addError(error: kInvalidEmailError);
return "";
}
return null;
},
decoration: InputDecoration(
labelText: "Email",
hintText: "Enter your email",
// If you are using latest version of flutter then lable text and hint text shown like this
// if you r using flutter less then 1.20.* then maybe this is not working properly
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Mail.svg"),
),
);
}
TextFormField buildUniFormField() {
return TextFormField(
keyboardType: TextInputType.uni,
onSaved: (newValue) => uni = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kEmailNullError);
} else if (emailValidatorRegExp.hasMatch(value)) {
removeError(error: kInvalidEmailError);
}
return null;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kEmailNullError);
return "";
} else if (!emailValidatorRegExp.hasMatch(value)) {
addError(error: kInvalidEmailError);
return "";
}
return null;
},
);
}
}

AlertDialog widget not working setState function in Flutter

I started to work with DropdownButton widget and I created List of cities. I want to see AlertDialog when i choose my favorite city on the list but it can't work.
Here is codes :
import 'package:flutter/material.dart';
import './func.dart';
class ChooseCity extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return ChooseCityState();
}
}
class ChooseCityState extends State<ChooseCity> {
var cities = ["Ankara", "İzmir", "İstanbul", "Edirne", "Antalya"];
String choosenCity = "Edirne";
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
items: cities.map((String city) {
return DropdownMenuItem<String>(
child: Text(city),
value: city,
);
}).toList(),
value: choosenCity,
onChanged: (String choosen) {
setState(() {
choosenCity = choosen;});
choosen=="Antalya" ?
AlertDialog(
title:Text("ATTENTION"),
content: Text("You chose the best place!!"),
actions: [
FlatButton(child: Text("I see,I agree"),onPressed: ()=>{},)
],
)
: Text("go on");
},
),
SizedBox(
height: 60,
),
Text(
" You choosed :" + choosenCity,
textAlign: TextAlign.center,
),
],
);
}
}
View of my page :
It doesn't look like as i want. I want to see AlertDialog when i chose "Antalya" . Where is the error? Where should i put the bool function? I tried to put this bool function out of setState function but it didn't be as i want.
If you want to show alert dialog you should use 'showDialog', then in its builder use your Alert Dialog.
Like this
class ChooseCity extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return ChooseCityState();
}
}
class ChooseCityState extends State<ChooseCity> {
var cities = ["Ankara", "İzmir", "İstanbul", "Edirne", "Antalya"];
String chosenCity = "Edirne";
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
items: cities.map((String city) {
return DropdownMenuItem<String>(
child: Text(city),
value: city,
);
}).toList(),
value: chosenCity,
onChanged: (String choosen) {
chosenCity = choosen;
showAlertDialog();
setState(() {});
},
),
SizedBox(
height: 60,
),
Text(
" You choosed :" + chosenCity,
textAlign: TextAlign.center,
),
],
);
}
showAlertDialog() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("ATTENTION"),
content: Text("You chose the best place!!"),
actions: [
FlatButton(
child: Text("I see,I agree"),
onPressed: () => {},
)
],
);
},
);
}
}

getting 0x03 error when performing chart generation: please check your input data in Highchart

i am using highchart export server for generate chart in NodeJs
but when i am generating many charts it gives error like 0x03 error when performing chart generation: please check your input data
here is my code
exports.generateAllCharts = (chartData, callback) => {
highchartsExporter.initPool({
maxWorkers: 100,
initialWorkers: 40,
workLimit: 100,
queueSize: 40,
timeoutThreshold: 600000
});
var allPromises = [];
if(!chartData ||chartData.length === 0) {
return callback({
code: '4',
msg: 'Please send chartdata'
})
}
allPromises.push(exports.getStockChartImg(chartData[1]));
allPromises.push(exports.priceChartVsPeersImg(chartData[2]));
allPromises.push(exports.getPieChartImg(chartData[3]));
allPromises.push(exports.getPieChartImg(chartData[4]));
allPromises.push(exports.getPieChartImg(chartData[5]));
allPromises.push(exports.getPieChartImg(chartData[6]));
allPromises.push(exports.getPieChartImg(chartData[13]));
allPromises.push(exports.getPieChartImg(chartData[14]));
allPromises.push(exports.getPieChartImg(chartData[15]));
allPromises.push(exports.getPieChartImg(chartData[16]));
allPromises.push(exports.getPieChartImg(chartData[18]));
allPromises.push(exports.getPieChartImg(chartData[19]));
allPromises.push(exports.getPieChartImg(chartData[7]));
allPromises.push(exports.getPieChartImg(chartData[17]));
allPromises.push(exports.getPieChartImg(chartData[20]));
allPromises.push(exports.getPieChartImg(chartData[21]));
allPromises.push(exports.getPieChartImg(chartData[22]));
allPromises.push(exports.getPieChartImg(chartData[23]));
allPromises.push(exports.getPieChartImg(chartData[24]));
allPromises.push(exports.getPieChartImg(chartData[25]));
allPromises.push(exports.getPieChartImg(chartData[26]));
allPromises.push(exports.getPieChartImg(chartData[27]));
allPromises.push(exports.getPieChartImg(chartData[33]));
allPromises.push(exports.getPieChartImg(chartData[34]));
allPromises.push(exports.getGlobalOwnershipDistributionChartImg(chartData[35]));
allPromises.push(exports.getPieChartImg(chartData[36]));
allPromises.push(exports.getPieChartImg(chartData[37]));
allPromises.push(exports.getPieChartImg(chartData[38]));
allPromises.push(exports.getPieChartImg(chartData[39]));
allPromises.push(exports.getPieChartImg(chartData[40]));
allPromises.push(exports.getPieChartImg(chartData[41]));
allPromises.push(exports.getPieChartImg(chartData[42]));
allPromises.push(exports.getPieChartImg(chartData[43]));
Promise.all(allPromises)
.then(data => {
highchartsExporter.killPool();
return callback({
code: '0',
custImg: {
pc1: data[0].data,
pc2: data[1].data,
pc3: data[2].data,
pc4: data[3].data,
pc5: data[4].data,
pc6: data[5].data,
pc7: data[6].data,
pc8: data[7].data,
pc9: data[8].data,
pc10: data[9].data,
pc11: data[10].data,
pc12: data[11].data,
pc13: data[12].data,
pc14: data[13].data,
pc17: data[14].data,
pc18: data[15].data,
pc19: data[16].data,
pc20: data[17].data,
pc21: data[18].data,
pc22: data[19].data,
pc23: data[20].data,
pc24: data[21].data,
pc27: data[22].data,
pc28: data[23].data,
pc29: data[24].data,
pc30: data[25].data,
pc31: data[26].data,
pc32: data[27].data,
pc33: data[28].data,
pc34: data[29].data,
pc35: data[30].data,
pc36: data[31].data,
pc37: data[32].data,
}
})
})
.catch(err => callback({
code: '5',
msg: 'Error generating charts',
err,
}))
}
exports.getPieChartImg = (seriesData, xOrLength) => {
var chartOpts = {
colors: ['#7380D4', '#749FD4', '#74BFD4', '#74D4B6', '#99EBA8', '#FEE08B', '#FDAE61', '#F07346', '#E65433', '#C92D22'],
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
renderTo: 'container',
style: {
fontSize: '20px',
background: '#fffdcc'
},
width:650,
},
credits: {
enabled: false
},
title: {
text: null,
},
tooltip: {
pointFormat: '{series.name}: {point.percentage:.1f}%'
},
legend: {
itemStyle: {
font: 'sans-serif',
fontWeight: 'bold',
fontSize: '13px'
},
useHTML: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
labelFormatter: ()=> {
if (this.name[xOrLength] > 9) {
var words = this.name.split(/[\s]+/);
var numWordsPerLine = 1;
var str = [];
for (var word in words) {
if (parseInt(word) > 0 && parseInt(word) % numWordsPerLine == 0)
str.push('<br>');
str.push(words[word]);
}
var label = str.join(' ');
// Make legend text bold and red if most recent value is less than prior
if (this.name[1] > this.name[2]) {
return '<span style="font-weight:bold">' + label + '</span>';
} else {
return label;
}
} else {
return this.name;
}
}
},
plotOptions: {
pie: {
size: '85%',
allowPointSelect: true,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: true,
allowOverlap: false,
distance: 10,
formatter: ()=> {
return undefined;
// if (parseFloat(this.percentage.toFixed(2)) > 0.35) {
// return '' + parseFloat(this.percentage).toFixed(2) + '%';
// }
},
padding: 5,
style: { fontFamily: '\'Lato\', sans-serif', /*lineHeight: '18px',*/ fontWeight: 'normal', fontSize: '18px' }
}
},
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#6f6f6f',
style: { fontFamily: '\'Lato\', sans-serif', /*lineHeight: '18px',*/ fontWeight: 'normal', fontSize: '18px' },
format:'{point.percentage:.2f}'
},
pointWidth: 30,
cursor: 'pointer'
}
},
series: [{
name: "Value",
type: 'pie',
data: seriesData
}],
navigation: {
buttonOptions: {
enabled: false
}
},
};
var exportSettings = generateExportSettings(chartOpts, 'Stock');
return generateBase64Chart(exportSettings, 3)
}
function generateExportSettings(chartOpts, constr) {
return {
// b64: true,
instr: JSON.stringify(chartOpts),
noDownload: true,
constr,
globalOptions: {
colors: ['#7380D4', '#749FD4', '#74BFD4', '#74D4B6', '#99EBA8', '#FEE08B', '#FDAE61', '#F07346', '#E65433', '#C92D22'],
lang: {
thousandsSep: ','
}
},
scale: 2,
styledMode: false,
type: "image/png",
width: false,
};
}
function generateBase64Chart(exportSettings, number) {
return new Promise((resolve, reject) => {
//Perform an export
highchartsExporter.export(exportSettings, function (err, res) {
//The export result is now in res.
//If the output is not PDF or SVG, it will be base64 encoded (res.data).
//If the output is a PDF or SVG, it will contain a filename (res.filename).
if(err) {
Logger.error("IN ERROR: ", number);
Logger.error("ERROR: ", err);
return reject({
code: '1',
err,
msg: 'Error in stock chart',
exportSettings
})
}
return resolve({
code: '0',
msg: 'success',
data: 'data:image/png;base64,' + res.data,
})
//Kill the pool when we're done with it, and exit the application
// highchartsExporter.killPool();
// process.exit(1);
});
})
}
i am generating all charts at a time, so how can i solve this problem.
I have modified your code a little bit (and used the getPieChartImg as it is the only one available) and tried to export a big number of charts (35 in this case). I don't encounter the 0x03-error. Here is the modified code:
(test.js)
const exporter = require('./promise-based.js');
let numberOfCharts = 35;
let chartsData = [];
for (let i = 0; i < numberOfCharts; i++) {
chartsData.push([1, 2, 3, 4, 5]);
}
exporter.generateAllCharts(chartsData, results => {
if (results.code === '0') {
console.log('All charts exported!');
console.log(results);
} else {
console.log('Error #' + results.code + ': ' + results.msg);
if (results.err) {
console.log(results.err);
}
}
process.exit();
});
(promise-based.js)
const highchartsExporter = require('highcharts-export-server');
let promiseId = 0;
exports.generateAllCharts = (chartData, callback) => {
let allPromises = [];
let chartsLen = chartData.length;
highchartsExporter.logLevel(4);
highchartsExporter.initPool({
maxWorkers: 100,
initialWorkers: 50,
workLimit: 100,
queueSize: 50,
timeoutThreshold: 10000
});
if (!chartData || !chartsLen) {
highchartsExporter.killPool();
return callback({
code: '4',
msg: 'Please send chartdata'
});
}
for (let i = 0; i < chartsLen; i++) {
allPromises.push(
new Promise((resolve, reject) => {
exports.getPieChartImg(chartData[i], false, results => {
if (results.code !== '0') {
return reject(results);
}
return resolve(results);
});
})
);
}
Promise.all(allPromises)
.then(data => {
highchartsExporter.killPool();
let imagesObject = {
code: '0',
custImg: {}
};
data.forEach((image, index) => {
imagesObject.custImg['pc' + (index + 1)] = image.data;
imagesObject.custImg.promiseId = image.promiseId;
});
return callback(imagesObject);
})
.catch(err => callback({
code: '5',
msg: 'Error generating charts',
err
}));
};
exports.getPieChartImg = (seriesData, xOrLength, cb) => {
let chartOpts = {
colors: ['#7380D4', '#749FD4', '#74BFD4', '#74D4B6', '#99EBA8', '#FEE08B', '#FDAE61', '#F07346', '#E65433', '#C92D22'],
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
renderTo: 'container',
style: {
fontSize: '20px',
background: '#fffdcc'
},
width: 650,
},
credits: {
enabled: false
},
title: {
text: null,
},
tooltip: {
pointFormat: '{series.name}: {point.percentage:.1f}%'
},
legend: {
itemStyle: {
font: 'sans-serif',
fontWeight: 'bold',
fontSize: '13px'
},
useHTML: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
labelFormatter: () => {
if (this.name[xOrLength] > 9) {
let words = this.name.split(/[\s]+/);
let numWordsPerLine = 1;
let str = [];
for (let word in words) {
if (parseInt(word) > 0 && parseInt(word) % numWordsPerLine == 0)
str.push('<br>');
str.push(words[word]);
}
let label = str.join(' ');
// Make legend text bold and red if most recent value is less than prior
if (this.name[1] > this.name[2]) {
return '<span style="font-weight:bold">' + label + '</span>';
} else {
return label;
}
} else {
return this.name;
}
}
},
plotOptions: {
pie: {
size: '85%',
allowPointSelect: true,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: true,
allowOverlap: false,
distance: 10,
formatter: () => {
return undefined;
// if (parseFloat(this.percentage.toFixed(2)) > 0.35) {
// return '' + parseFloat(this.percentage).toFixed(2) + '%';
// }
},
padding: 5,
style: {
fontFamily: '\'Lato\', sans-serif',
// lineHeight: '18px',
fontWeight: 'normal',
fontSize: '18px'
}
}
},
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#6f6f6f',
style: {
fontFamily: '\'Lato\', sans-serif',
// lineHeight: '18px',
fontWeight: 'normal',
fontSize: '18px'
},
format: '{point.percentage:.2f}'
},
pointWidth: 30,
cursor: 'pointer'
}
},
series: [{
name: "Value",
type: 'pie',
data: seriesData
}],
navigation: {
buttonOptions: {
enabled: false
}
},
};
let exportSettings = generateExportSettings(chartOpts, 'Stock');
return generateBase64Chart(exportSettings, 3, cb);
};
function generateExportSettings(chartOpts, constr) {
return {
type: 'png',
constr,
b64: true,
// async: false,
noDownload: true,
scale: 2,
options: chartOpts,
globalOptions: {
colors: ['#7380D4', '#749FD4', '#74BFD4', '#74D4B6', '#99EBA8', '#FEE08B', '#FDAE61', '#F07346', '#E65433', '#C92D22'],
lang: {
thousandsSep: ','
}
}
};
}
function generateBase64Chart(exportSettings, number, cb) {
// Perform an export
highchartsExporter.export(exportSettings, function(err, res) {
// The export result is now in res.
// If the output is not PDF or SVG, it will be base64 encoded (res.data).
// If the output is a PDF or SVG, it will contain a filename (res.filename).
if (err) {
return cb({
code: '1',
msg: 'Error in stock chart',
err,
exportSettings
});
}
promiseId++;
return cb({
code: '0',
msg: 'Success',
promiseId: promiseId,
data: 'data:image/png;base64,' + res.data,
});
// Kill the pool when we're done with it, and exit the application
// highchartsExporter.killPool();
// process.exit(1);
});
}

Setting a react state in callback does not work as expected

I am making barcode reading app. I use Quaggajs and Reactjs.
Quaggajs has a function Quagga.onDetected(callback), the callback has one parameter result. The result is containing the detected barcode. I am having a react state (const [count, setCount] = useState(0);) in which I am counting the detected barcodes. The problem is that when I use setCount(count + 1) in the callback the count variable is allways it's initial value (0) so every time onDetect the setCount is setting the new value to be 1.
Here is an example of the functional react component I use(I think that there is no problem getting the count and setCount from the props of ):
const Body = ({setCount, count, ...rest }) => {
const start = () => {
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
constraints: {
facingMode: "environment",
},
area: {
top: "30%",
bottom: "30%"
}
},
locate: false,
frequency: 50,
decoder: {
readers: [
// "code_128_reader",
"ean_reader",
// "ean_8_reader",
// "code_39_reader",
// "code_39_vin_reader",
// "codabar_reader",
// "upc_reader",
// "upc_e_reader",
// "i2of5_reader"
],
debug: {
showCanvas: true,
showPatches: true,
showFoundPatches: true,
showSkeleton: true,
showLabels: true,
showPatchLabels: true,
showRemainingPatchLabels: true,
boxFromPatches: {
showTransformed: true,
showTransformedBox: true,
showBB: true
}
}
},
}, function (err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
});
Quagga.onProcessed(function (result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "green", lineWidth: 2 });
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00F", lineWidth: 2 });
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
}
}
});
Quagga.onDetected((result) => {
if (result && result.codeResult && result.codeResult.startInfo && result.codeResult.startInfo.error < 0.03) {
console.log("Sould change")
setCount(count + 1);
}
});
}
const stop = () => { Quagga.stop(); }
useEffect(() => {
start();
console.log("CHANGE BODY");
return () => {
stop();
}
}, [])
return (
<Grid container justify="center">
<div id="interactive" className="viewport" style={{ position: 'unset', width: '100vw', height: "100vh" }}>
<video src=""></video>
<canvas class="drawingBuffer"></canvas>
</div>
</Grid>
)
}

Resources