Flutter dropdown, select is disabled on validation error - validation

Validation is working well but incase of validation error, option to select on option is disabled.
DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null)
return "Please select your gender";
return null;
},
),
Above code is in a page view,
my variables
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
My entire Form code : just reduced to one field its very long
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final List<GlobalKey<FormState>> _page = [
GlobalKey<FormState>(),
GlobalKey<FormState>(),
GlobalKey<FormState>(),
];
final _key = GlobalKey<ScaffoldState>();
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
void changePage() {
if (currentPageValue < 3) {
if (_page[currentPageValue].currentState.validate()) {
setState(() {
currentPageValue += 1;
});
}
}
}
#override
Widget build(BuildContext context) {
var deviceSize = MediaQuery.of(context).size;
var deviceWidth = deviceSize.width;
return Scaffold(
key: _key,
backgroundColor: _backgroundColor,
appBar: AppBar(
backgroundColor: _backgroundColor,
leading: IconButton(
icon: Icon(
currentPageValue == 0 ? Icons.close : Icons.keyboard_backspace,
size: 20.0,
color: _headerColor,
),
onPressed: currentPageValue == 0
? () => Navigator.pop(context)
: () => back()),
centerTitle: true,
elevation: 0.0,
),
body: Form(
key: _page[0],
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: deviceWidth * 0.9,
height: dropDownHeight,
child: ButtonTheme(
child: DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null) return "Please select your gender";
return null;
},
),
),
),
RaisedButton(
color: buttonColor,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10.0),
),
child: Text(
'Next',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
),
),
onPressed: () => changePage(),
),
],
),
),
),
);

Looking at your code, I strongly recommend you create 3 different Forms and validate them separately, so you don't have any problem regarding form state. To achieve this, you can just wrap the fields into their respective Form and be sure not to mix the forms nor have them one inside the other.
Below, an example based on your code and on what I have said:
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _page1 = GlobalKey<FormState>();
final _page2 = GlobalKey<FormState>();
final _page3 = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
int currentPageValue;
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
void changePage(GlobalKey<FormState> page) {
if (currentPageValue < 3) {
if (page.currentState.validate()) {
setState(() {
currentPageValue += 1;
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _key,
body: ListView(
children: <Widget>[
Form(
key: _page1,
child: Column(
children: [
DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null) return "Please select your gender";
return null;
},
),
RaisedButton(
child: Text('Next'),
onPressed: () => changePage(_page1),
),
],
),
),
Form(
key: _page2,
child: Column(
children: [
// SomeField(
//
// ),
// SomeOtherField(
//
// ),
RaisedButton(
child: Text('Next'),
onPressed: () => changePage(_page2),
),
],
),
),
],
),
);
}
}

Related

Flutter: Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform, not working

I am new to flutter and i am building a Notes App. In my project i create three files main.dart, addUser.dart & editUser.dart My CREATE operation(addUser.dart) works properly & READ operation(main.dart) as well but when i click on read operation note it shows an red error with warning Bad state: field does not exist within the DocumentSnapshotPlatform
I am getting this error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following StateError was thrown building Builder(dirty):
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was
MaterialApp
lib\main.dart:18
When the exception was thrown, this was the stack
#0 DocumentSnapshotPlatform.get._findKeyValueInMap
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:82
#1 DocumentSnapshotPlatform.get._findComponent
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:98
#2 DocumentSnapshotPlatform.get
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:113
#3 DocumentSnapshot.get
package:cloud_firestore/src/document_snapshot.dart:49
#4 DocumentSnapshot.[]
package:cloud_firestore/src/document_snapshot.dart:56
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 2 of 826 libraries in 14,160ms.
Restarted application in 11,595ms.
W/DynamiteModule(10940): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(10940): Considering local module providerinstaller:0 and remote module
providerinstaller:0
W/ProviderInstaller(10940): Failed to load providerinstaller module: No acceptable module found.
Local version is 0 and remote version is 0.
════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during layout:
A RenderFlex overflowed by 240 pixels on the bottom.
The relevant error-causing widget was
Column
lib\main.dart:96
To inspect this widget in Flutter DevTools, visit: http://127.0.0.1:9101/#/inspector?
uri=http%3A%2F%2F127.0.0.1%3A52941%2F0C0SU5iODJs%3D%2F&inspectorRef=inspector-0
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen.
If the content is legitimately bigger than the available space, consider clipping it with a ClipRect
widget before putting it in the flex, or using a scrollable container rather than a Flex, like a
ListView.
The specific RenderFlex in question is: RenderFlex#b9fbf relayoutBoundary=up10 OVERFLOWING
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by rendering library ═════════════════════════════════
A RenderFlex overflowed by 240 pixels on the bottom.
The relevant error-causing widget was
Column
lib\main.dart:96
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was
MaterialApp
lib\main.dart:18
════════════════════════════════════════════════════════════════════════════════
my Main.dart file
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:darwish_latest/addNote.dart';
import 'package:darwish_latest/editNote.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
CollectionReference ref = FirebaseFirestore.instance.collection('darwish');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("UMHE Note"),
),
floatingActionButton: FloatingActionButton(
// backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => AddNote()));
}),
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection("darwish")
.orderBy("time")
.snapshots(),
builder: (context, snapshot) {
return ListView.builder(
itemCount:
snapshot.hasData ? snapshot.data.documents.length : 0,
itemBuilder: (_, index) {
var darwish = snapshot.data.documents[index];
return snapshot.data.documents.length == 0
? Text("Text Notes Found")
: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => EditNote(
darwish['empId'], darwish.id)));
},
child: Container(
margin: EdgeInsets.all(10),
constraints: BoxConstraints(maxHeight: 150),
color: Colors.grey.withOpacity(0.4),
child: Column(children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['empid'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['user'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['email'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['password'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['DOB'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(darwish['address'],
style: GoogleFonts.sourceCodePro(
fontSize: 20)),
),
]),
),
);
});
},
));
}
}
my addNote.dart file
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class AddNote extends StatefulWidget {
#override
_AddNoteState createState() => _AddNoteState();
}
class _AddNoteState extends State<AddNote> {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
TextEditingController empId = TextEditingController();
TextEditingController user = TextEditingController();
TextEditingController emailid = TextEditingController();
TextEditingController passwordd = TextEditingController();
TextEditingController dobirth = TextEditingController();
TextEditingController myaddress = TextEditingController();
CollectionReference ref = FirebaseFirestore.instance.collection('darwish');
String empid = '';
String username = '';
String email = '';
String password = '';
String dob = '';
String address = '';
buildEmployeeid() => TextFormField(
controller: empId,
decoration: InputDecoration(
labelText: 'Employee Id',
border: OutlineInputBorder(),
),
validator: (value) {
if (value.isEmpty) {
return 'Employee id can not be empty';
}
return null;
},
onSaved: (value) => setState(() => empid = value),
);
Widget buildUsername() => TextFormField(
controller: user,
decoration: InputDecoration(
labelText: 'Username',
border: OutlineInputBorder(),
),
validator: (value) {
if (value.isEmpty) {
return 'Title can not be empty';
}
return null;
},
maxLength: 30,
onSaved: (value) => setState(() => username = value),
);
Widget buildEmail() => TextFormField(
controller: emailid,
decoration: InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
validator: (value) {
final pattern =
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+";
final regExp = RegExp(pattern);
if (value.isEmpty) {
return 'Email can not be empty';
} else if (!regExp.hasMatch(value)) {
return 'Enter a valid email';
}
return null;
},
keyboardType: TextInputType.emailAddress,
onSaved: (value) => setState(() => email = value),
);
Widget buildPassword() => TextFormField(
controller: passwordd,
decoration: InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
validator: (value) {
if (value.isEmpty) {
return 'Password can not be empty';
}
return null;
},
onSaved: (value) => setState(() => password = value),
obscureText: true,
);
buildDOB() => TextFormField(
controller: dobirth,
decoration: InputDecoration(
labelText: 'Date Of Birth',
border: OutlineInputBorder(),
),
validator: (value) {
if (value.isEmpty) {
return 'Date of Birth can not be empty';
}
return null;
},
onSaved: (value) => setState(() => dob = value),
);
buildAddress() => TextFormField(
controller: myaddress,
decoration: InputDecoration(
labelText: 'Address',
border: OutlineInputBorder(),
),
validator: (value) {
if (value.isEmpty) {
return 'Address can not be empty';
}
return null;
},
maxLength: 30,
onSaved: (value) => setState(() => address = value),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'UMHE Form',
),
),
body: Form(
key: formKey,
// autovalidate: true,
child: ListView(
padding: EdgeInsets.all(16),
children: [
buildEmployeeid(),
const SizedBox(height: 32),
buildUsername(),
const SizedBox(height: 16),
buildEmail(),
const SizedBox(height: 32),
buildPassword(),
const SizedBox(height: 32),
buildDOB(),
const SizedBox(height: 32),
buildAddress(),
const SizedBox(height: 32),
ElevatedButton(
child: Text(
'Submit',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
onPressed: () {
final isValid = formKey.currentState.validate();
FocusScope.of(context).unfocus();
if (isValid) {
// formKey.currentState.save();
ref.add({
'empid': empId.text,
'user': user.text,
'email': emailid.text,
'password': passwordd.text,
'DOB': dobirth.text,
'address': myaddress.text,
'time': DateTime.now()
});
formKey.currentState.reset();
return AlertDialog(
content: Text('Saved Successfully...'),
);
}
}),
],
),
),
);
}
}
my myEdit.dart file
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class EditNote extends StatefulWidget {
String id;
String docid;
EditNote(id, docid);
#override
_EditNoteState createState() => _EditNoteState();
}
class _EditNoteState extends State<EditNote> {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
TextEditingController empId = TextEditingController();
TextEditingController user = TextEditingController();
TextEditingController emailid = TextEditingController();
TextEditingController passwordd = TextEditingController();
TextEditingController dobirth = TextEditingController();
TextEditingController myaddress = TextEditingController();
#override
void initState() {
empId.text = widget.id;
}
CollectionReference ref = FirebaseFirestore.instance.collection("darwish");
editEmployeeId() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Employee Id can not be empty';
}
return null;
},
controller: empId,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'Employee Id',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
editUser() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'User can not be empty';
}
return null;
},
controller: user,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'User',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
editEmailId() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Email Id can not be empty';
}
return null;
},
controller: emailid,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'Email Id',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
editPassword() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Password can not be empty';
}
return null;
},
controller: passwordd,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'Password',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
editDOB() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'DOB can not be empty';
}
return null;
},
controller: dobirth,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'Date Of Birth',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
editMyAddress() => TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Address can not be empty';
}
return null;
},
controller: myaddress,
decoration: InputDecoration(
// fillColor: Colors.grey.withOpacity(0.4),
filled: true,
hintText: 'Employee Id',
),
style: GoogleFonts.sourceCodePro(
fontSize: 25,
// color: Colors.black,
fontWeight: FontWeight.bold),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Edit Note"),
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
onPressed: () => {Navigator.pop(context)}),
actions: [
IconButton(
icon: Icon(
Icons.delete,
color: Colors.white,
),
onPressed: () {
FirebaseFirestore.instance
.collection('darwish')
.doc(widget.docid)
.delete()
.then((value) => Navigator.pop(context));
}),
],
),
body: Form(
key: formKey,
child: ListView(
padding: EdgeInsets.all(16),
children: [
editEmployeeId(),
const SizedBox(height: 16),
editUser(),
const SizedBox(height: 32),
editEmailId(),
const SizedBox(height: 32),
editPassword(),
const SizedBox(height: 32),
editDOB(),
const SizedBox(height: 32),
editMyAddress(),
ElevatedButton(
child: Text(
'Update',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
onPressed: () {
if (formKey.currentState.validate()) {
FirebaseFirestore.instance
.collection("darwish")
.doc(widget.docid)
.set({
'empid': empId.text,
'user': user.text,
'email': emailid.text,
'password': passwordd.text,
'DOB': dobirth.text,
'address': myaddress.text,
// 'content': content.text,
'time': DateTime.now()
}).then((value) => Navigator.pop(context));
}
}),
],
)));
}
}

Flutter Radio Buttons validation

I am implementing a custom radio button with validation and values are passed in those buttons. There is a run time error which i am not able to figure out. I am getting the following error
The following assertion was thrown during performLayout():
I/flutter (10799): An InputDecorator, which is typically created by a TextField, cannot have an unbounded width.
I/flutter (10799): This happens when the parent widget does not provide a finite width constraint. For example, if the
I/flutter (10799): InputDecorator is contained by a Row, then its width must be constrained. An Expanded widget or a
I/flutter (10799): SizedBox can be used to constrain the width of the InputDecorator or the TextField that contains it.
I/flutter (10799): 'package:flutter/src/material/input_decorator.dart':
I/flutter (10799): Failed assertion: line 945 pos 7: 'layoutConstraints.maxWidth < double.infinity'
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter FormBuilder Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Colors.purple),
),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
MyHomePageState createState() {
return MyHomePageState();
}
}
class MyHomePageState extends State<MyHomePage> {
var data;
bool autoValidate = true;
bool readOnly = false;
bool showSegmentedControl = true;
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
final GlobalKey<FormFieldState> _specifyTextFieldKey =
GlobalKey<FormFieldState>();
ValueChanged _onChanged = (val) => print(val);
// var genderOptions = ['Male', 'Female', 'Other'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FormBuilder Example"),
),
body: Padding(
padding: EdgeInsets.all(10),
child: SingleChildScrollView(
child: Row(
children: <Widget>[
FormBuilder(
// context,
key: _fbKey,
autovalidate: true,
//initialValue: {
// 'movie_rating': 5,
// },
readOnly: false,
child: Row(
children: <Widget>[
FormBuilderRadio(
decoration:
InputDecoration(labelText: 'My chosen language'),
attribute: "best_language",
leadingInput: true,
onChanged: _onChanged,
validators: [FormBuilderValidators.required()],
options:
["Delete", "Approve", "Revert"]
.map((lang) => FormBuilderFieldOption(
value: lang,
child: Text('$lang'),
))
.toList(growable: false),
),
],
),
),
Row(
children: <Widget>[
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
"Submit",
style: TextStyle(color: Colors.white),
),
onPressed: () {
if (_fbKey.currentState.saveAndValidate()) {
print(_fbKey.currentState.value);
} else {
print(_fbKey.currentState.value);
print("validation failed");
}
},
),
),
SizedBox(
width: 20,
),
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
"Reset",
style: TextStyle(color: Colors.white),
),
onPressed: () {
_fbKey.currentState.reset();
},
),
),
],
),
],
),
),
),
);
}
}
void changeIndex() {
setState(() {
selectedIndex = 1;
print("Value passed is delete");
});
}
void changeIndex1() {
setState(() {
selectedIndex = 1;
print("Value passed is a");
});
}
void changeIndex2() {
setState(() {
selectedIndex = 1;
print("Value passed is r");
});
}
Widget customRadio1() => OutlineButton(
onPressed: () => changeIndex(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 0 ? Colors.red : Colors.grey),
child: Text(lst[0], style: TextStyle(
color: selectedIndex == 0 ? Colors.red : Colors.grey),),
);
Widget customRadio2() => OutlineButton(
onPressed: () => changeIndex1(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 1 ? Colors.green : Colors.grey),
child: Text(lst[1], style: TextStyle(
color: selectedIndex == 1 ? Colors.green : Colors.grey),),
);
Widget customRadio3() {
return OutlineButton(
onPressed: () => changeIndex2(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 2 ? Colors.cyan : Colors.grey),
child: Text(lst[2], style: TextStyle(
color: selectedIndex == 2 ? Colors.cyan : Colors.grey),),
);
}
}
An InputDecorator cannot have an unbounded width as mentioned in the logs. The cause of this is that the InputDecorator is in a Scrollable Row and has an undefined width. To solve this issue, you can wrap the child widgets in the Row with a Container with a width configured.

Flutter :- How to sorting a custom List

Here I want I've some listed item and I want to sort item them on its id or rating. when I click on the side drawer button it will need to rearrange the list view with sorted items hope you understand my question.
I've tried this smooth_sort package for sorting but it won't work for me because it will sort based on the index. and I want to sort based on my own value.
Here is the output image
Here is my code
class _MapAddressListingScreenState extends State<MapAddressListingScreen>
with AfterLayoutMixin<MapAddressListingScreen> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
List addressData;
#override
void afterFirstLayout(BuildContext context) {
_getAddress();
}
_getAddress() {
List requestedLatlong = ModalRoute.of(context).settings.arguments;
print("============================Address Data");
print(requestedLatlong);
setState(() {
addressData = requestedLatlong;
});
}
List<Widget> _addressData() {
List<Widget> _address = [];
for (int i = 0; i < addressData.length; i++) {
_address.add(
GestureDetector(
onTap: () {
print('address list taped');
AddWalkinModel model = widget.addWalkinModel;
print("After model");
model.fromMap = false;
model.fromMapListing = true;
model.autoAssign = addressData[i]['autoAssign'];
model.branchId = addressData[i]['branchId'];
model.branchServiceId = addressData[i]['branchServiceId'];
print("After Model Model");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DynamicScreen(
addWalkinModel: model,
),
),
);
},
child: AddressListingTile(listingTileData: addressData[i]),
),
);
}
return _address;
}
Widget itemCard() {
return Container(
child: Column(
children: _addressData(),
),
);
}
#override
Widget build(BuildContext context) {
var colorStyles = Theming.colorstyle(context);
return Scaffold(
key: _scaffoldKey,
backgroundColor: colorStyles['primary'],
appBar: AppBar(
title: Text("BSP Listview "),
centerTitle: true,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.pop(context);
},
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.sort),
onPressed: () {
_scaffoldKey.currentState.openEndDrawer();
},
),
],
),
endDrawer: Drawer(
child: Column(
children: <Widget>[
SizedBox(
height: 100,
),
FlatButton(
onPressed: () {
ratingSort.shuffle();
},
child: Text("sort")),
],
),
),
body: Stack(
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(30.0),
topRight: const Radius.circular(30.0)),
child: Stack(
children: <Widget>[
SingleChildScrollView(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
itemCard(),
],
),
),
)
],
),
),
),
],
),
);
}
}
You can use the sort method of the list for sorting the list in the specific format as follows
#override
void initState() {
super.initState();
for(int i=0;i<fields.length;i++) {
print("BEFORE==>>> ${fields[i].rating}");
}
fields.sort((a, b) => a.rating.compareTo(b.rating)); ///FROM THIS LINE YOU CAN PERFORM SHORTING ACCORDING TO THE RATING BASES
for(int i=0;i<fields.length;i++) {
print("AFTER==>>> ${fields[i].rating}");
}
}
And i have use the my demo custom list for it
List<Fields> fields = [
new Fields(
'DEFAULT CATEGORY',
2,
),
new Fields(
'DEFAULT CATEGORY',
1,
),
new Fields(
'DEFAULT CATEGORY',
5,
),
new Fields(
'DEFAULT CATEGORY',
3,
),
new Fields(
'DEFAULT CATEGORY',
4,
),
];
And output will be follow
Please check the full source of code for it
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutterlearningapp/colors.dart';
class HomeScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _HomeScreen();
}
}
class _HomeScreen extends State<HomeScreen> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: Text("Demo Scroll"),
),
body: Container(
height: double.infinity,
width: double.infinity,
color: Colors.white,
child: Column(
children: <Widget>[
RaisedButton(
child: Text("Shoring"),
onPressed: (){
setState(() {
fields.sort((a, b) => a.rating.compareTo(b.rating));
});
},
),
Expanded(
child: ListView.builder
(
itemCount: fields.length,
itemBuilder: (BuildContext ctxt, int index) {
return ListTile(
title: new Text("Rating #${fields[index].rating}"),
subtitle: new Text(fields[index].title),
);
}
) ,
)
],
),
),
));
}
}
class Fields {
final String title;
final int rating;
Fields(this.title, this.rating);
}
List<Fields> fields = [
new Fields(
'Two',
2,
),
new Fields(
'One',
1,
),
new Fields(
'DEFAULT CATEGORY',
5,
),
new Fields(
'Three',
3,
),
new Fields(
'Four',
4,
),
];
And above output of the program as follow

Flutter: unwanted white background above the keyboard

I tried to add resizeToAvoidBottomPadding: false below Scaffold but it doesn't change anything.
Could anyone help me figure out how to fix this?
Here is the entire code of the file:
class showAll extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _showAllState();
}
}
class _showAllState extends State<showAll> {
navigateToDetail(DocumentSnapshot indexedData, context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(itemSelected: indexedData)));
}
Widget build(BuildContext context) {
return Scaffold(
// resizeToAvoidBottomPadding: false, <-- it does not work...
// resizeToAvoidBottomInset: false, <-- it does not work...
appBar: AppBar(
title: Text('All Items'),
backgroundColor: Colors.teal,
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(
context: context,
delegate: CustomSearchDelegate(),
);
},
),
],
),
body: StreamBuilder(
stream: Firestore.instance
.collection('ARC_items')
.orderBy('name')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('loading...');
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(
snapshot.data.documents[index].data['name'].toString()),
subtitle: Text(
'Total amount: ${snapshot.data.documents[index].data['# of items'].toString()}'),
onTap: () {
navigateToDetail(snapshot.data.documents[index], context);
// testingReservations(
// snapshot.data.documents[index].documentID);
},
),
);
}),
);
}
}
class CustomSearchDelegate extends SearchDelegate {
navigateToDetail(DocumentSnapshot indexedData, context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(itemSelected: indexedData)));
}
displayGrids(data, context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Flexible(
child: Padding(
padding: EdgeInsets.all(5.0),
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.0,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: data.map<Widget>(
(categoryInfo) {
return GestureDetector(
child: GridTile(
child: CustomCell(categoryInfo),
),
onTap: () {
navigateToDetail(categoryInfo, context);
},
);
},
).toList(),
),
),
),
],
);
}
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
close(context, null);
},
);
}
#override
Widget buildResults(BuildContext context) {
// TODO: implement buildResults
return null;
}
#override
Widget buildSuggestions(BuildContext context) {
// If you want to add search suggestions as the user enters their search term, this is the place to do that.
return StreamBuilder(
stream: Firestore.instance.collection('ARC_items').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('loading...');
final results = snapshot.data.documents.where(
(DocumentSnapshot a) =>
a.data['name'].toString().toLowerCase().contains(
query.trim().toLowerCase(),
),
);
return displayGrids(results, context);
});
}
}

Remove Padding or Margin from Drawer Header in Flutter App

How do I remove the padding or margin from my Drawer Header in this example below.
I've set margin and padding to EdgeInsets.zero for both but this is not doing the job.
Menu Screen Example Image
Here is the code that produced this menu. Everything works. I simply can't remove the padding from the header specifically. The blue field should reach all the way to the edges on the top and sides.
import "package:flutter/material.dart";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Menu App',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: AppDrawer(mainMenu),
appBar: AppBar(
title: Text("My Menu App"),
),
);
}
}
class AppDrawer extends StatelessWidget {
List menuChoices;
AppDrawer(this.menuChoices);
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: menuChoices.length,
itemBuilder: (BuildContext cntxt, int index) {
return _constructItem(menuChoices[index]);
},
),
);
}
Widget _constructHeader(Choices choice) {
return DrawerHeader(
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
child: Container(
child: Stack(
children: <Widget>[
Positioned(
bottom: 12.0,
left: 16.0,
child: Text(
choice.title,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w500),
),
),
],
),
),
decoration: BoxDecoration(
color: Colors.blue,
),
);
}
Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return DrawerHeader(child: _constructHeader(choice));
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}
}
class Choices {
const Choices(
{#required this.title,
#required this.itemType,
this.icon,
this.enabled = true,
this.action});
final String itemType;
final String title;
final IconData icon;
final bool enabled;
final Function action;
}
// These are the menu choices
const List<Choices> mainMenu = const <Choices>[
const Choices(
itemType: "Header",
title: "My Header Text",
icon: Icons.face,
),
const Choices(
itemType: "Item",
title: 'My Profile',
icon: Icons.person,
enabled: true,
action: null,
),
const Choices(
itemType: "Divider",
),
const Choices(
itemType: "Item",
title: 'About',
icon: Icons.info,
enabled: true,
action: null,
),
const Choices(
itemType: "Divider",
),
const Choices(
itemType: "Item",
title: 'Help',
icon: Icons.help_outline,
enabled: true,
action: null,
),
];
Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return DrawerHeader(padding: EdgeInsets.zero ,child: _constructHeader(choice));
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}
DrawerHeader has been called both in the switch statement and in the _constructHeaderMethod. Simply calling the _constructHeaderMethod is all that is needed. Essentially I had a DrawerHeader as a child of a DrawerHeader which was unnecessary.
Changing the _constructItem method as below solves the problem.
Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return _constructHeader(choice);
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}
}

Resources