TextField value only updated when hovered - flutter

I have a Category TextField with a controller. The controller value is updated onChange of a Product Dropdown. What I expect is upon onChange the value of the categoryField should be updated. However, I can only see the update on the TextField once I hover on it.
Category TextField
var productCategory = Column(
children: [
TextField(
controller: categoryController,
enabled: false,
focusNode: categoryFocusNode,
),
const Padding(
padding: EdgeInsets.all(5.0), child: SizedBox(width: 200)),
],
);
Product Dropdown onChange
void onChange<Product>(prod) {
BlocProvider.of<InvoiceCubit>(context).updateProduct(prod);
categoryController.text = prod.category.categoryName.toString();
}

I have finally figured it out. Since I am using a rxdart stream, I created both the Product dropdown and Category on the StreamBuilder. Then I created the categoryController within the builder itself with text value from the product category. Below is my code:
var productDropdownField = StreamBuilder<Product>(
stream: BlocProvider.of<InvoiceCubit>(context).productStream,
builder: (context, snapshot) {
final categoryController = TextEditingController();
categoryController.text = snapshot.hasData
? snapshot.data!.category.categoryName
: "";
var productCategory = Column(
children: [
CustomTextField(
labelText: "Category",
controller: categoryController,
enabled: false,
),
const Padding(
padding: EdgeInsets.all(10.0),
child: SizedBox(width: 200)),
],
);
return StreamBuilder<Object>(
stream:
BlocProvider.of<InvoiceCubit>(context).priceStream,
builder: (context, snapshot) {
return Column(
children: [
BlocBuilder<ProductsCubit, ProductsState>(
builder: (context, state) {
if (state is ProductsLoaded) {
List<DropdownMenuItem<Product>>
dropDownItems = state.products
.map((e) => DropdownMenuItem<Product>(
value: e,
child: Text(
e.productName,
style: const TextStyle(
color: Colors.black,
fontWeight:
FontWeight.w900),
),
))
.toList();
if (invoiceItem == null &&
prodSelected == false) {
onChange<Product>(state.products.first);
prodSelected = true;
}
return CustomDropdown<Product>(
labelText: "Product",
value:
BlocProvider.of<InvoiceCubit>(context)
.getProduct(),
items: dropDownItems,
context: context,
onChanged: onChange,
);
}
return const SizedBox(
width: 100, child: Text("Error"));
},
),
productCategory,
],
);
});
});
categoryController won't be updated via onChange but will be updated based on the snapshot.data

Related

Flutter SwitchListTile Changing State on AllItems

I am trying to use the SwitchTileList to show all my categories and toggle them on/off however it seems to either not change state/toggle or it will toggle all of them together.
At the moment the code below the showdefault items are on as should be and the rest are off, however it will not toggle any of them at the moment.
return FutureBuilder(
future: amenityCategories,
builder:
(BuildContext context, AsyncSnapshot<AmenityCategories> snapshot) {
if (snapshot.hasData) {
return ListView(
padding: EdgeInsets.zero,
children: [
SizedBox(
height: 85.0,
child: DrawerHeader(
child: Text(
'Show/Hide Map Pins',
style: new TextStyle(fontSize: 18.0, color: Colors.white),
),
decoration: const BoxDecoration(
color: Colors.green,
),
),
),
SizedBox(
height: double.maxFinite,
child: ListView.builder(
itemCount: snapshot.data!.categories.length,
itemBuilder: (context, index) {
bool toggle = false;
if (snapshot.data!.categories[index].showbydefault == 1) {
toggle = true;
}
return SwitchListTile(
title: Text(
snapshot.data!.categories[index].categoryname),
value: toggle,
onChanged: (bool val) {
if (val != toggle) {
setState(() {
toggle = !toggle;
});
}
});
},
),
),
],
);
}
return Container();
});
}
You must use a separate variable for each individual ListTile. Give your category an additional variable isActive and work with it.
onChanged: (bool val) {
if (val != snapshot.data!.categories[index].isActive) {
setState(() {
snapshot.data!.categories[index].isActive = !snapshot.data!.categories[index].isActive;
});
}

How to add text on dropdownmenu?

I'm making an app using Flutter and I want to add text for my DropDownMenu like Select car make or something like that.
I could not find a tutorial so was hoping someone could help.
Here is my code:
new FormField(builder: (FormFieldState state) {
return InputDecorator(
decoration: InputDecoration(
),
child:FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
final album = snapshot.data;
final results = album.results;
return DropdownButtonHideUnderline(
child: DropdownButton<Results>(
isExpanded: true,
items: results.map((result) {
return DropdownMenuItem<Results>(
value: result,
child: Text('${result.modelName}'),
);
}).toList(),
onChanged: (album ) {
// selected album
setState(() {
_selected = album;
});
},
value: _selected,
));
} else
return CircularProgressIndicator();
}),
);
}),
I tried to set hinttext, but it does not work.
Here is how you can add a hint to your DropdownButton:
hint: Container(
width: 150,
child: Text(
"Select car",
style: TextStyle(color: Colors.grey),
textAlign: TextAlign.end,
),
),

how to get data in material datatable in flutter from rest api

I want to show data in material dataTable but instead of getting data in a row it makes the table head every time with the row
My design which I Want:
The design I am getting right now:
Here is the full code of my flutter application:
UI SCREEN
________________This is Ui part of my application_
import 'package:aiims/bloc/add_relatives_bloc.dart';
import 'package:aiims/models/relative.dart';
import 'package:aiims/service/api.dart';
import 'package:aiims/widgets/side_menu_widget.dart';
import 'package:flutter/material.dart';
import 'package:outline_material_icons/outline_material_icons.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
class RelativeScreen extends StatefulWidget {
#override
_RelativeScreenState createState() => _RelativeScreenState();
}
class _RelativeScreenState extends State<RelativeScreen> {
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
DataRow getDataRow(data) {
return DataRow(
cells: <DataCell>[
DataCell(Text(data["name"])),
DataCell(Text(data["age"])),
DataCell(Text(data["relation"])),
DataCell(
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.edit_outlined),
Icon(Icons.delete_outline_sharp),
],
),
),
],
);
}
#override
void initState() {
// TODO: implement initState
super.initState();
// _getDataRow(list.length);
}
// _getRelatives() {
// getRelativesList().then((Relative) {
// setState(() {
//
// });
// print("Length: ${_relative.length}");
// });
// }
// DataRow _getDataRow(list) {
// return DataRow(
// cells: <DataCell>[
// DataCell(Text(list["name"])),
// DataCell(Text(list["age"])),
// DataCell(Text(list["relation"])),
// ],
// );
// }
#override
Widget build(BuildContext context) {
final bloc = Provider.of<AddNewRelativeBloc>(context, listen: false);
return Scaffold(
drawer: NavDrawer(),
appBar: AppBar(
title: Text('Relatives'),
actions: <Widget>[
GestureDetector(
onTap: () => _add_relavitves(),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Icon(Icons.add_circle_outline_rounded),
),
),
],
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
// alignment: Alignment.center,
padding: EdgeInsets.symmetric(vertical: 20),
child: SingleChildScrollView(
child: Container(
child: FutureBuilder(
future: getRelativesList(),
// initialData: new TreatmentDetail(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
} else if (snapshot.connectionState ==
ConnectionState.done) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
return DataTable(
headingRowColor: MaterialStateColor
.resolveWith(
(states) => Color(0xffff69b4)),
// MaterialStateColor.resolveWith((states) => Colors.pink),
columns: [
DataColumn(label: Text("Name")),
DataColumn(label: Text("Age")),
DataColumn(label: Text("Relation")),
DataColumn(label: Text("Action")),
],
// rows: List.generate(
// list.length, (index) =>
// _getDataRow(list[index]),
// ));
rows: [
DataRow(
cells: [
DataCell(Text(list[index]["name"])),
DataCell(Text(list[index]["age"])),
DataCell(Text(list[index]["relation"])),
DataCell(
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.edit_outlined),
Icon(Icons.delete_outline_sharp),
],
),
),
],
),
// DataRow(cells: [
// DataCell(Text('Ajay Singh')),
// DataCell(Text('25')),
// DataCell(Text('Son')),
// DataCell(
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Icon(Icons.edit_outlined),
// Icon(Icons.delete_outline_sharp),
// ],
// ),
// ),
// ]),
],
);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}),
),
),
),
),
),
);
}
void _add_relavitves() {
final bloc = Provider.of<AddNewRelativeBloc>(context, listen: false);
// set up the buttons
// Widget cancelButton = FlatButton(
// child: Text("Cancel"),
// onPressed: () {
// Navigator.pop(context);
// },
// );
Widget cancelButton = MaterialButton(
child: Container(
height: 40,
width: 110,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Color(0xffff69b4),
),
child: Text(
"Discard",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
onPressed: () {
Navigator.pop(context);
},
);
Widget continueButton = FlatButton(
child: Text("Continue"),
onPressed: () {},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Center(
child: Text(
"Add New Relative",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
content: SingleChildScrollView(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(height: 20),
StreamBuilder<Object>(
stream: bloc.name,
builder: (context, snapshot) {
return TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintText: "Name",
labelText: "Name",
errorText: snapshot.error,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
// onChanged: (value) => bloc.changeName,
onChanged: bloc.changeName,
);
}),
SizedBox(height: 20),
StreamBuilder<Object>(
stream: bloc.age,
builder: (context, snapshot) {
return TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: "Age",
labelText: "Age",
errorText: snapshot.error,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
// onChanged: (value) => bloc.changeName,
onChanged: bloc.changeAge,
);
}),
SizedBox(height: 20),
StreamBuilder<Object>(
stream: bloc.relation,
builder: (context, snapshot) {
return TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintText: "Relation",
labelText: "Relation",
errorText: snapshot.error,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
// onChanged: (value) => bloc.changeName,
onChanged: bloc.changeRelation,
);
}),
SizedBox(height: 20),
StreamBuilder<Object>(
stream: bloc.phoneNumber,
builder: (context, snapshot) {
return TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: "Phone Number",
labelText: "Phone Number",
errorText: snapshot.error,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
// onChanged: (value) => bloc.changeName,
onChanged: bloc.changePhoneNumber,
);
}),
],
),
),
),
actions: [
cancelButton,
_saveButton(),
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Widget _saveButton() {
final bloc = Provider.of<AddNewRelativeBloc>(context, listen: false);
return StreamBuilder<Object>(
stream: bloc.isValid,
builder: (context, snapshot) {
return GestureDetector(
onTap: snapshot.hasError || !snapshot.hasData
? null
: () {
bloc.submit();
},
child: Container(
height: 40,
width: 130,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: snapshot.hasError || !snapshot.hasData
? Color(0xffff69b4)
: Colors.green,
),
child: Text(
"Save",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
);
});
}
}
//My Future for getting response from api
Future<List> getRelativesList() async {
final response =
await http.get("$baseUrl");
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> data = map["data"];
print("first id on console" + data[0]["id"].toString());
return list = data;
}
//Here is my model
class Relative {
int _code;
String _message;
List<Data> _data;
Relative({int code, String message, List<Data> data}) {
this._code = code;
this._message = message;
this._data = data;
}
int get code => _code;
set code(int code) => _code = code;
String get message => _message;
set message(String message) => _message = message;
List<Data> get data => _data;
set data(List<Data> data) => _data = data;
Relative.fromJson(Map<String, dynamic> json) {
_code = json['code'];
_message = json['message'];
if (json['data'] != null) {
_data = new List<Data>();
json['data'].forEach((v) {
_data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this._code;
data['message'] = this._message;
if (this._data != null) {
data['data'] = this._data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int _id;
int _patientId;
String _name;
String _age;
String _relation;
String _phoneNo;
Data(
{int id,
int patientId,
String name,
String age,
String relation,
String phoneNo}) {
this._id = id;
this._patientId = patientId;
this._name = name;
this._age = age;
this._relation = relation;
this._phoneNo = phoneNo;
}
enter code here
int get id => _id;
set id(int id) => _id = id;
int get patientId => _patientId;
set patientId(int patientId) => _patientId = patientId;
String get name => _name;
set name(String name) => _name = name;
String get age => _age;
set age(String age) => _age = age;
String get relation => _relation;
set relation(String relation) => _relation = relation;
String get phoneNo => _phoneNo;
set phoneNo(String phoneNo) => _phoneNo = phoneNo;
Data.fromJson(Map<String, dynamic> json) {
_id = json['id'];
_patientId = json['patient_id'];
_name = json['name'];
_age = json['age'];
_relation = json['relation'];
_phoneNo = json['phone_no'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this._id;
data['patient_id'] = this._patientId;
data['name'] = this._name;
data['age'] = this._age;
data['relation'] = this._relation;
data['phone_no'] = this._phone`enter code here`No;
return data;
}
}
You return DataTable as an item for ListView.builder, that is why you see header and row. If you want display only table then remove ListView widget and return DataTable with rows. Something like
FutureBuilder(
builder: (context, snapshot) {
return DataTable(
columns: <DataColumn>[
...
],
rows: list.map((item) {
return DataRow(
cells: <DataCell>[...]
);
}),
),
}
)

How to set the textfield value using Global key

What i am trying is to replicate "setText" in flutter without TextEditingController. Since I'm using FutureBuilder, i cannot go with manually updating state, thereby removing the choice of TextEditingController.
Bellow is the code for better understanding.
class DynamicFormBuilder {
GlobalKey<FormBuilderState> dynamicFormKey = GlobalKey<FormBuilderState>();
String getVariableData(String variable) {
return dynamicFormKey.currentState.fields[variable].currentState.value;
}
void setVariableData(String variable, String value) {
dynamicFormKey.currentState.fields[variable].currentState.didChange(value);
}
Widget workOnWidget(DynamicFormResponse widget) {
switch (widget.widget) {
case "text":
return Text(
widget.displayText,
style: TextStyle(
fontWeight: widget.style.fontWeight == "bold"
? FontWeight.bold
: FontWeight.normal,
fontSize: double.parse(widget.style.fontSize)),
);
case "editable":
return FormBuilderTextField(
attribute: widget.variable,
decoration: InputDecoration(labelText: widget.displayText),
onChanged: (val) {
if (widget.onChanged != null) {
onChangedFunctionMapper[widget.variable](val);
}
},
);
case "datepicker":
return FormBuilderDateTimePicker(
attribute: widget.variable,
inputType: InputType.date,
format: DateFormat("dd/MM/yyyy"),
decoration: InputDecoration(labelText: widget.displayText),
validators: [
FormBuilderValidators.required(),
],
);
case "divider":
return Container(
margin: EdgeInsets.fromLTRB(5, 10, 5, 10),
width: double.infinity,
height: 10,
color: accentColor,
);
case "dropdown":
return FormBuilderDropdown(
attribute: widget.variable,
items: convertDropdown(widget.options),
hint: Text(widget.hint),
decoration: InputDecoration(labelText: widget.displayText),
);
case "radioButton":
return FormBuilderRadioButton(
displayText: widget.displayText,
attribute: widget.variable,
isHorizontal: widget.isHorizontal,
onChanged: (val) {
if (val == "yes") {
visibilityMap["age"] = true;
} else {
visibilityMap["age"] = false;
}
},
options: widget.options
.map((lang) => FormBuilderFieldOption(value: lang))
.toList(growable: false),
);
default:
return Text("lol");
}
}
Widget buildForms(BuildContext context, Future<dynamic> fetchJSON) {
jsonData = new List();
dynamicFormKey = GlobalKey<FormBuilderState>();
accentColor = Theme.of(context).accentColor;
return FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none &&
snapshot.hasData == null) {
return Container(
child: Text("No Data got loaded"),
);
} else if (snapshot.connectionState == ConnectionState.done) {
for (int i = 0; i < snapshot.data.length; i++) {
jsonData.add(DynamicFormResponse.fromJson(snapshot.data[i]));
}
return ListView(
padding: EdgeInsets.all(10),
children: <Widget>[
FormBuilder(
key: dynamicFormKey,
autovalidate: false,
child: Card(
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: jsonData.map<Widget>((widget) {
print(widget.widget);
return workOnWidget(widget);
}).toList(),
),
),
),
),
],
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
future: fetchJSON,
);
}
}
So here when i do updates using setVariableData(variable, data), the variable in state is getting updated, but the same is not getting reflected in TextFields.
First of all, your question is quite confusing. However, I guess, you are looking for something to set the value to some xyz variable when you submit the data, right?
You can do this by two ways, these are:
Using onSubmitted Property: This gives the value when the user is done editing the value in the textfield
Using TextEditingController: Controls the text being edited.
Code using TextEditingController:
TextEditingController _controller = new TextEditingController();
TextField(
controller: _controller
)
//suppose you have a button which will print the data of the textfield for on onPressed
RaisedButton(
onPressed: () {
//this will print the value you've entered into the textfield
print(this._controller.text)
//change the value using setState here
setState((){
value_to_be_changed_variable = this._controller.text
})
},
child: const Text('Submit', style: TextStyle(fontSize: 20))
)
Code using onSubmitted Property:
TextField(
onSubmitted: (value) {
//do the operation here with the help of setState()
setState((){
variable_value_to_be_changed = value
})
}
)
I hope that'd suffice your needs. For more info read about Textfield Flutter Class thoroughly. It will help in you in many ways

How to pass data from alertdialog to page in flutter?

I am passing data from my alertdialog to item of listview.
Where I can find information about it?
I tried use TextEditingController, with Navigation Routes. And I used materials from this Tutorial
This is my code:
class MeasurementsScreen extends StatefulWidget {
#override
_MeasurementsScreenState createState() => _MeasurementsScreenState();
}
class _MeasurementsScreenState extends State<MeasurementsScreen> {
List<_ListItem> listItems;
String lastSelectedValue;
var name = ["Рост", "Вес"];
var indication = ["Введите ваш рост", "Введите ваш вес"];
TextEditingController customcintroller;
void navigationPageProgrammTrainingHandler() {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => ProgrammTrainingHandler()),
);
}
#override
void initState() {
super.initState();
initListItems();
}
Future<String> createAlertDialog(BuildContext context, int indexAl){
customcintroller = TextEditingController();
if(indexAl < 2){
return showDialog(context: context, builder: (context){
return AlertDialog(
title: Text(name[indexAl]),
content: TextField(
textDirection: TextDirection.ltr,
controller: customcintroller,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: indication[indexAl],
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
),
actions: <Widget>[
FlatButton(
child: const Text('ОТМЕНА'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: const Text('ОК'),
onPressed: () {
Navigator.of(context).pop(customcintroller.text.toString());
},
),
],
);
});
} else if (indexAl > 1){
navigationPageProgrammTrainingHandler();
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Color(0xff2b2b2b),
appBar: AppBar(
title: Text(
'Замеры',
style: new TextStyle(
color: Colors.white,
),),
leading: IconButton(
icon:Icon(Icons.arrow_back),
color: Colors.white ,
onPressed:() => Navigator.of(context).pop(),
),
),
body: ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: listItems.length,
itemBuilder: (BuildContext ctxt, int index){
return GestureDetector(
child: listItems[index],
onTap: () {
createAlertDialog(context, index).then((onValue){
});
}
);
},
),
);
}
void initListItems() {
listItems = [
new _ListItem(
bgName: 'assets/images/soso_growth.jpg',
name: customcintroller.text.toString().isEmpty == false ? customcintroller.text.toString() : "Рост",
detail: "Нажми, чтобы добавить свой рост"),
new _ListItem(
bgName: 'assets/images/soso_weight.jpg',
name: customcintroller.text.toString().isEmpty == false ? customcintroller.text.toString() : "Вес",
detail: "Нажми, чтобы добавить свой вес"),
new _ListItem(
bgName: 'assets/images/soso_chest.jpg',
name: "Грудь",
detail: "PRO-версия"),
new _ListItem(
bgName: 'assets/images/soso_shoulder.jpg',
name: "Плечи",
detail: "PRO-версия"),
new _ListItem(
bgName: 'assets/images/soso_biceps.jpg',
name: "Бицепс",
detail: "PRO-версия")
];
}
}
class _ListItem extends StatelessWidget {
_ListItem({this.bgName, this.name, this.detail});
// final int index;
final String bgName;
final String name;
final String detail;
#override
Widget build(BuildContext context) {
return Container(
height: 180.0,
margin: const EdgeInsets.symmetric(
vertical: 1.0,
),
child: new Stack(
children: <Widget>[
new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage(bgName),
colorFilter: new ColorFilter.mode(
Colors.black.withOpacity(0.45), BlendMode.darken),
fit: BoxFit.cover,
alignment: Alignment.center),
),
child: new SizedBox.expand(
child: Container(
alignment: Alignment.center,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Text(
name,
style: new TextStyle(fontSize: 29.0, color: Colors.white),
),
Padding(
padding: const EdgeInsets.only(top: 12.0),
child: new Text(
detail,
style:
new TextStyle(fontSize: 16.0, color: Colors.white),
),
)
],
),
),
),
),
],
),
);
}
}
I expect to get text from alertdialog.
Do you want to update data in your current screen or in another Scaffold/screen? Solution for the first option would be to set your desired data in a setState or pass it to a Model (with ScopedModel) and update the view. E.g. :
FlatButton(
child: const Text('ОТМЕНА'),
onPressed: () {
setState(() {
myData = data;
Navigator.of(context).pop();
}); // not sure if this will work, could you try?
}
),
If it is in a new/other screen, you can pass it in the Navigator like for example:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(data: myData),
),
);
},
Does this solve your problem? Otherwise, please elaborate on what it is you need.
I tried to use Navigator.of(context).pop("OK"); in the AlertDialog but it doesn't work.
use ValueChanged as a param on the showDialog method and it works well.
class Dialogs{
static showAlertDialog(BuildContext context, String title, String message,
{List<String> actions, ValueChanged onChanged}) async {
if (actions == null) {
actions = ["OK"];//default OK button.
}
await showDialog(
context: context,
child: AlertDialog(
title: Text(title ?? 'Message'),
content: Text(message),
actions: actions
.map((e) => new FlatButton(
child: Text(e.trim()),
onPressed: () {
Navigator.of(context).pop(e.trim());
if (onChanged != null) {
onChanged(e.trim());
}
}))
.toList(),
),
);
}
}
the caller looks like
_onProcess(){
String result = "";
await Dialogs.showAlertDialog(context, "Warning", "Warning message", actions: ["OK", "Cancel"],
onChanged: (value) {
result = value;
});
if (result != "OK") {
Dialogs.showSnackBarMessage(context, "Cancel This PTN");
return;
}
....process with the OK logic.
}
If you want to change an item of the list you can do that with setState() before calling Navigator.pop(). It is not possible to pass data through Navigator.pop() though, as you may be able to do with Navigator.push(... MyPage(data)).
You could achieve what you want through State management. You can check for state management tutorials in general. But the two practices that are used most in my opinion are Scoped Model and BLoC pattern. These practices help you pass data through the widget tree back and forward. I would recommend BLoC pattern there are many tutorials about it. Also there is a package which can be very helpful with BLoC pattern: flutter_bloc.