Flutter Slidable SlidableAction Calling onPressed even when it has not been pressed - flutter

I am using a library called flutter_slidable . Below is my fetchItems method
static Future<List<Item>> fetchItems(String url) async {
try {
// pub spec yaml http:
// import 'package:http/http.dart' as http;
final response = await http.get(
Uri.parse(
url),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
}) /*.timeout(const Duration(seconds: Config.responseTimeOutInSeconds))*/;
final List<Item> itemsList;
if (response.statusCode == 200) {
itemsList = json
.decode(response.body)
// In event of failure return line below
//.cast<Map<String, dynamic>>()
.map<Item>((json) => Item.fromJson(json))
.toList();
} else if (response.statusCode == 401) {
itemsList = [];
} else {
itemsList = [];
}
return itemsList;
} catch (e) {
if (kDebugMode) {
Logger().wtf(
"FetchItemsException $e \n\nResponseStatusCode ${statusCode!}");
}
rethrow;
}
}
And below is the code for my page that i populate
class ClassListWithSearchOnAppBarCustomCard extends StatefulWidget {
const ClassListWithSearchOnAppBarCustomCard({Key? key}) : super(key: key);
#override
_ClassListWithSearchOnAppBarCustomCardState createState() =>
_ClassListWithSearchOnAppBarCustomCardState();
}
class _ClassListWithSearchOnAppBarCustomCardState
extends State<ClassListWithSearchOnAppBarCustomCard> {
List<Item>? itemsList;
Future populateItemsList() async {
final itemsList = await AsyncFutures.fetchItems(
"https://api.json-generator.com/templates/ueOoUwh5r44G/data");
setState(() {
this.itemsList = itemsList;
});
}
#override
void initState() {
super.initState();
populateItemsList();
}
onSearch(String searchValue) {}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.grey.shade900,
leading: IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(
Icons.arrow_back,
color: Colors.white,
)),
title: Container(
child: TextField(
onChanged: (value) => onSearch(value),
cursorHeight: 21.0,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[850],
contentPadding: EdgeInsets.all(0),
prefix: Icon(
Icons.search,
color: Colors.grey.shade500,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide.none),
hintStyle:
TextStyle(fontSize: 15, color: Colors.grey.shade500),
hintText: "Search"),
style: TextStyle(
color: Colors.white,
),
),
),
),
body: Column(children: [
Expanded(
child: Builder(
builder: (BuildContext context) {
if (itemsList == null) {
return iconProgressIndicator();
} else {
return RefreshIndicator(
// background color
backgroundColor: Colors.white,
// refresh circular progress indicator color
color: Colors.green,
onRefresh: () async {
setState(() {
populateItemsList();
});
},
child: ListView.builder(
itemCount: itemsList!.length,
itemBuilder: (BuildContext context, int index) {
// flutter_slidable: ^1.2.0
// import 'package:flutter_slidable/flutter_slidable.dart';
return Slidable(
// Specify whether the slider is dismissible
key: const ValueKey(1),
// Sliding from left to right
startActionPane: ActionPane(
// Types of Motion
// Behind Motion, Drawer Motion, Scroll Motion , Stretch Motion
motion: const DrawerMotion(),
// dismissible: DismissiblePane(onDismissed: () {
// onDismissedRemoveItem(
// itemsList![index].id ?? "");
// }),
children: [
// Start this side with delete action if you have already implemented dismissible
// If Start with other slidable action create a new method for the slidable with a build context
SlidableAction(
onPressed: deleteSlidableAction(
context, itemsList![index].id ?? ""),
backgroundColor: Colors.red.shade500,
foregroundColor: Colors.white,
icon: Icons.delete,
label: 'Delete',
),
SlidableAction(
onPressed: dialogSlidableAction(
context, itemsList![index].id ?? ""),
backgroundColor: Colors.blueAccent.shade400,
foregroundColor: Colors.white,
icon: Icons.check_box_outline_blank,
label: 'Dialog',
),
],
),
child: myCustomCardWidget(
itemsList![index].id ?? "",
itemsList![index].title ?? "",
itemsList![index].subTitle ?? '',
itemsList![index].imageUrl ??
Config.nullNetworkImage),
);
},
));
}
},
),
)
]));
}
deleteSlidableAction(BuildContext context, String? itemId) {
setState(() {
itemsList!.removeWhere((item) => item.id == itemId);
});
}
dialogSlidableAction(BuildContext context, String? itemId) {
print(itemId);
}
void onDismissedRemoveItem(String itemId) {
setState(() {
itemsList!.removeWhere((item) => item.id == itemId);
});
}
}
The problem i am having is that onPressed of SlidableAction for both Delete and Dialog are being called even before they are pressed and the populated list items are all removed

SlidableAction(
// An action can be bigger than the others.
onPressed: (BuildContext context){
_yesPost(forMeList[i]["postID"]);
},
backgroundColor: Colors.green,
foregroundColor: Colors.white,
icon: Icons.check_circle_outline,
label: 'Yes',
),
try to add BuildContext.
that worked for me.

Related

how to disable button in flutter

I have an elevated button, to which i want to disable it after user hits the button, api gets called here. i have tried to setState but itseems not working. what else can i do to disable button.
hint: my concept i am working is that once ther users clicks the button, again the user should not be able to click again the same button.
Here is my code:
bool isEnable = false;
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
//FocusManager.instance.primaryFocus!.unfocus();
// });
// setState(() {
// isEnable = false;
// });
}
:null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: const Text('Entry',
style: TextStyle(
color: Colors.white,
)),
),
Please make sure variable qrdata.code and isEnable are initialized outside the build method. Every time when setState is called one or both the variables are getting reset.
The problem is whenever setState is pressed it is not rebuilding the button state. so to change the button state wrap your button with StatefulBuilder.
and please call your API in try catch.
class DisableButton extends StatefulWidget {
const DisableButton({Key? key}) : super(key: key);
#override
State<DisableButton> createState() => _DisableButtonState();
}
class _DisableButtonState extends State<DisableButton> {
bool isEnable = false;
int qrdata = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StatefulBuilder(
builder:
(BuildContext context, void Function(void Function()) setState) {
return ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding: MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(
const TextStyle(fontSize: 14, color: Colors.black))),
onPressed: qrdata != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
print(">>>> Button is disabled");
try {
final data = await http.get(
Uri.parse(
'https://jsonplaceholder.typicode.com/albums/1'),
);
if (!mounted) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NextPage(
data: data.body.toString(),
),
),
);
print("Api Data >>>> $data.body");
} catch (e) {
print("Error While fetching data");
}
setState(() {
isEnable = false;
});
print(">>>> Button is enabled");
}
: null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: Text(isEnable ? "Disabled" : "Enabled",
style: const TextStyle(
color: Colors.white,
)),
);
},
),
),
);
}
}
class NextPage extends StatelessWidget {
const NextPage({Key? key, required this.data}) : super(key: key);
final String data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(child: Text("Data : $data")),
);
}
}
The problem in your code is setting isEnable to true but not resting to false.
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
//FocusManager.instance.primaryFocus!.unfocus();
// });
// setState(() { <---- Uncomment this code.
// isEnable = false;
// });
}
:null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: const Text('Entry',
style: TextStyle(
color: Colors.white,
)),
),
Apply this code bellow:
You got error on double equal.
bool variable:
bool isDisabled = false;
Widget
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isDisabled
? () async {
setState(() {
isDisabled = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
});
setState(() {
isDisabled = false;
});
}
:null,

Delete Widget at button press Flutter

Recently implemented a tagForm widget at "+" button press, I want to delete those widgets now at "delete" button press, but right now, even when I press the "delete" button, nothing happens.
How can I solve this?
Any help appreciated!
code:
import 'package:flutter/material.dart';
import '../database/firestoreHandler.dart';
import '../models/todo2.dart';
import '../widgets/dialogs.dart';
class TodoEdit extends StatefulWidget {
String? doctitle;
String? doctdescription;
String? docimage;
String? docid;
List? doctags;
TodoEdit({Key? key, this.doctitle, this.doctdescription, this.docimage, this.docid,this.doctags}) : super(key: key);
#override
_TodoEditState createState() => _TodoEditState();
}
class _TodoEditState extends State<TodoEdit> {
final _formKey = GlobalKey<FormState>();
final tcontroller = TextEditingController();
final dcontroller = TextEditingController();
final icontroller = TextEditingController();
var textEditingControllers = <TextEditingController>[];
//-----------------the list where the form is stored----------
var textformFields = <Widget>[];
void _addformWidget(controller) {
setState(() {
textformFields.add(tagForm(controller));
});
}
//------------------------------------------------------------------------
Widget tagForm(controller){
return TextFormField(
controller: controller,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: "Tag",
labelStyle: TextStyle(color: Colors.white60),
fillColor: Colors.black,
filled: true,
suffixIcon: IconButton(
icon:Icon(Icons.delete, color: Colors.white,),
//--------------------- doesn't work?-------------------
onPressed: (){
setState(() {
textformFields.remove(tagForm(controller));
});
},
--------------------------------------------------------------
)
),
);
}
//-----------------------------------------------------------
#override
void initState() {
super.initState();
tcontroller.text = widget.doctitle.toString();
dcontroller.text = widget.doctdescription.toString();
icontroller.text = widget.docimage.toString();
widget.doctags?.forEach((element) {
var textEditingController = new TextEditingController(text: element);
textEditingControllers.add(textEditingController);
//return textformFields.add(tagForm(textEditingController)
return _addformWidget(textEditingController);
//);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
actions: [
IconButton(onPressed: (){
showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
title: Text('Delete TODO'),
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
TextButton(
child: Text('Delete'),
onPressed: () {
deleteData(widget.docid.toString(), context);
setState(() {
showSnackBar(context, 'todo "${widget.doctitle}" successfully deleted!');
});
},
),
],
);
},
);
},
icon: Icon(Icons.delete))
],
backgroundColor: Colors.grey[900],
title: Text("${widget.doctitle}"),
),
body: Container(
child: SafeArea(
child: Form(
key: _formKey,
child: Column(
children: [
SizedBox(height: 10),
TextFormField(
controller: tcontroller,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: "Title",
labelStyle: TextStyle(color: Colors.white60),
fillColor: Colors.black,
filled: true,
),
),
SizedBox(height: 10),
TextFormField(
controller: dcontroller,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: "Description",
labelStyle: TextStyle(color: Colors.white60),
fillColor: Colors.black,
filled: true,
),
),
SizedBox(height: 10),
TextFormField(
controller: icontroller,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: "Image url",
labelStyle: TextStyle(color: Colors.white60),
fillColor: Colors.black,
filled: true,
),
),
SizedBox(height: 10),
Row(children: [
Text("Tags:", style:TextStyle(color: Colors.white)),
IconButton(onPressed: (){
var textEditingController = new TextEditingController(text: "tag");
textEditingControllers.add(textEditingController);
_addformWidget(textEditingController);
print(textformFields.length);
},
icon: Icon(Icons.add,color: Colors.white,),
)
],),
/*SingleChildScrollView(
child: new Column(
children: textformFields,
)
),*/
Expanded(
child: SizedBox(
height: 200.0,
child: ListView.builder(
itemCount: textformFields.length,
itemBuilder: (context,index) {
return textformFields[index];
}),
)
),
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
List<String> test = [];
textEditingControllers.forEach((element) {
test.add(element.text);
});
if(tcontroller == '' && dcontroller == '' && icontroller == ''){
print("not valid");
}else{
var todo = Todo2(
title: tcontroller.text,
description: dcontroller.text,
image: icontroller.text,
tags: test,
);
updateData(todo, widget.docid.toString(),context);
setState(() {
showSnackBar(context, 'todo ${widget.doctitle} successfully updated!');
});
}
},
child: Icon(Icons.update),
),
);
}
}
You can't remove anything from the list with objects from tagForm(controller), because these objects are newly created and therefore not the same as in the list (as long as the == operator is not overwritten)
If you still want to have the widgets in a list instead of just storing the controllers and without having to change much, you could remove the widgets like this:
onPressed: (){
setState(() {
controller.dispose();
textEditingControllers.remove(controller);
textformFields.removeWhere((w) => w.controller = controller));
});
},
and change the type of your List: var textformFields = <TextFormField>[]; and of the method TextFormField tagForm(controller).
In general, you can of course optimize the state management, but with this solution it should work for now.
Dont't store Widget, it is bad way. Insteads store there property, render by List then remove by index when you need.
ps: some code syntax can wrong, i write this on browser.
class _TodoEditState extends State<TodoEdit> {
...
var textformFields = <String>[];
...
void _addformWidget([String? initValue]) {
setState(() => textformFields.add(initValue ?? ""));
}
...
Widget tagForm(String value, void Function(String) onChange, void Function() onRemove){
var openEditor = () {
// Open dialog with text field to edit from [value] call onChange with
// new value
OpenDialog().then((newvalue) {
if(newvalue != null) onChange(newvalue);
}
};
var delete = () {
// Open confirm dialog then remove
OpenConfirmDialog("your message").then((continue) {
if(continue) onRemove();
});
};
return InkWell(
onTap: openEditor,
child: Text(value), // render your tag value
);
}
...
#override
void initState() {
...
textformFields = List.filled(widget.doctags ?? 0, ""); // or List.generate/map if you want replace by own value.
}
...
#override
Widget build(BuildContext context) {
...
ListView.builder(
itemCount: textformFields.length,
itemBuilder: (context,index) => tagForm(
textformFields[index],
(newvalue) => setState(() => textformFields[index] = newvalue),
() => setState(() => textformFields = textformFields..removeAt(index));,
),
),
...
);
}

RenderFlex children have non-zero flex but incoming height constraints are unbounded in flatter

I have a page code written in an android studio. On this page, I display a list of objects, as well as a widget to search for these objects. When I clicked on the search widget, I had the following problem: "The following statement was thrown during layout:
RenderFlex is overcrowded 31 pixels below.
The corresponding widget that caused the errors was: "But then I found the answer to this question and added" SingleChildScrollView ".
But then I had this problem: "RenderFlex have non-zero flexibility, but the input height limits are unlimited." . And I can't solve it in any way. I will be grateful for your help. Here is my code:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/post/form_unseals.dart';
import 'package:flutter_app_seals/model/post/form_seals.dart';
import 'package:flutter_app_seals/model/setting/globalvar.dart' as global;
import 'dart:async';
import 'dart:io';
import 'dart:convert';
void main() => runApp(JsonParseObjectSts_UN());
class JsonParseObjectSts_UN extends StatefulWidget {
JsonParseObjectSts_UN() : super();
#override
_JsonParseObjectsState createState() => _JsonParseObjectsState();
}
class _JsonParseObjectsState extends State <StatefulWidget> {
List<UserDetails> _searchResult = [];
List<UserDetails> _userDetails = [];
TextEditingController controller = new TextEditingController();
final String url = global.urlVar ;
// Get json result and convert it to model. Then add
Future<Null> getUserDetails() async {
HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
final request = await client
.getUrl(Uri.parse(url))
.timeout(Duration(seconds: 5));
HttpClientResponse response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
final responseJson = json.decode(responseBody);
setState(() {
for (Map user in responseJson) {
_userDetails.add(UserDetails.fromJson(user));
}
});
}
#override
void initState() {
super.initState();
getUserDetails();
}
Widget _buildUsersList() {
return new ListView.builder(
itemCount: _userDetails.length,
itemBuilder: (context, index) {
return new Card(
color: (_userDetails[index].sealed == "Так") ? Colors.redAccent : Colors.greenAccent,
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
_userDetails[index].name,
style: TextStyle(fontSize: 25),
),
subtitle: Text("Запломбований:${_userDetails[index].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 30,
color: Colors.black87,
),
onTap: () =>
{
if ('Так' == _userDetails[index].sealed) {
global.nameObj = _userDetails[index].name,
global.sealsNumb = _userDetails[index].seal_number,
global.typesOp = 'Так',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Unseals()),
)
}
else{
{
global.nameObj = _userDetails[index].name,
global.typesOp = 'Ні',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Form_seals()),
)
}
}
}
),
);
},
);
}
Widget _buildSearchResults() {
return new ListView.builder(
itemCount: _searchResult.length,
itemBuilder: (context, i) {
return new Card(
color: (_searchResult[i].sealed == "Так") ? Colors.redAccent : Colors.greenAccent,
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
_searchResult[i].name,
style: TextStyle(fontSize: 25),
),
subtitle: Text("Запломбований:${_searchResult[i].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 30,
color: Colors.black87,
),
onTap: () =>
{
if ('Так' == _searchResult[i].sealed) {
global.nameObj = _searchResult[i].name,
global.sealsNumb = _searchResult[i].seal_number,
global.typesOp = 'Так',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Unseals()),
)
}
else{
{
global.nameObj = _searchResult[i].name,
global.typesOp = 'Ні',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Form_seals()),
)
}
}
}
),
);
},
);
}
Widget _buildSearchBox() {
return new Padding(
padding: const EdgeInsets.all(8.0),
child: new Card(
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
controller: controller,
decoration: new InputDecoration(
hintText: 'Пошук', border: InputBorder.none),
onChanged: onSearchTextChanged,
),
trailing: new IconButton(
icon: new Icon(Icons.cancel),
onPressed: () {
controller.clear();
onSearchTextChanged('');
},
),
),
),
);
}
Widget _buildBody() {
return new Scaffold(
body:Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.white],
begin: Alignment.topCenter,
end: Alignment.bottomCenter),
),
child: SingleChildScrollView(
child:Column(
children: <Widget>[
new Container(
color: Theme.of(context).primaryColor, child: _buildSearchBox()),
new Expanded(
child: _searchResult.length != 0 || controller.text.isNotEmpty
? _buildSearchResults()
: _buildUsersList()),
],
),
),
),
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: _buildBody()
);
}
onSearchTextChanged(String text) async {
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return;
}
_userDetails.forEach((userDetail) {
if (userDetail.name.contains(text) ) _searchResult.add(userDetail);
});
setState(() {});
}
}
class UserDetails {
final String name, seal_number,sealed;
UserDetails({this.name, this.sealed, this.seal_number});
factory UserDetails.fromJson(Map<String, dynamic> json) {
return new UserDetails(
sealed: json['sealed'],
name: json['name'],
seal_number: json['seal_number'],
);
}
}
My scrin:
My scrin when I want to use search:

how to increase the size of the window with the search result in flutter?

I have a page code written in an android studio. On this page, I display a list of objects, as well as a widget to search for these objects. When I clicked on the search widget,my list of objects is shrinking, and it is almost invisible (it is at the top). Can this be fixed somehow so that it can be seen on the whole page ??
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/post/form_unseals.dart';
import 'package:flutter_app_seals/model/post/form_seals.dart';
import 'package:flutter_app_seals/model/setting/globalvar.dart' as global;
import 'dart:async';
import 'dart:io';
import 'dart:convert';
void main() => runApp(JsonParseObjectSts_UN());
class JsonParseObjectSts_UN extends StatefulWidget {
JsonParseObjectSts_UN() : super();
#override
_JsonParseObjectsState createState() => _JsonParseObjectsState();
}
class _JsonParseObjectsState extends State <StatefulWidget> {
List<UserDetails> _searchResult = [];
List<UserDetails> _userDetails = [];
TextEditingController controller = new TextEditingController();
final String url = global.urlVar ;
// Get json result and convert it to model. Then add
Future<Null> getUserDetails() async {
HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
final request = await client
.getUrl(Uri.parse(url))
.timeout(Duration(seconds: 5));
HttpClientResponse response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
final responseJson = json.decode(responseBody);
setState(() {
for (Map user in responseJson) {
_userDetails.add(UserDetails.fromJson(user));
}
});
}
#override
void initState() {
super.initState();
getUserDetails();
}
Widget _buildUsersList() {
return new ListView.builder(
itemCount: _userDetails.length,
itemBuilder: (context, index) {
return new Card(
color: (_userDetails[index].sealed == "Так") ? Colors.redAccent : Colors.greenAccent,
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
_userDetails[index].name,
style: TextStyle(fontSize: 25),
),
subtitle: Text("Запломбований:${_userDetails[index].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 30,
color: Colors.black87,
),
onTap: () =>
{
if ('Так' == _userDetails[index].sealed) {
global.nameObj = _userDetails[index].name,
global.sealsNumb = _userDetails[index].seal_number,
global.typesOp = 'Так',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Unseals()),
)
}
else{
{
global.nameObj = _userDetails[index].name,
global.typesOp = 'Ні',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Form_seals()),
)
}
}
}
),
);
},
);
}
Widget _buildSearchResults() {
return new ListView.builder(
itemCount: _searchResult.length,
itemBuilder: (context, i) {
return new Card(
color: (_searchResult[i].sealed == "Так") ? Colors.redAccent : Colors.greenAccent,
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
_searchResult[i].name,
style: TextStyle(fontSize: 25),
),
subtitle: Text("Запломбований:${_searchResult[i].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 30,
color: Colors.black87,
),
onTap: () =>
{
if ('Так' == _searchResult[i].sealed) {
global.nameObj = _searchResult[i].name,
global.sealsNumb = _searchResult[i].seal_number,
global.typesOp = 'Так',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Unseals()),
)
}
else{
{
global.nameObj = _searchResult[i].name,
global.typesOp = 'Ні',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Form_seals()),
)
}
}
}
),
);
},
);
}
Widget _buildSearchBox() {
return new Padding(
padding: EdgeInsets.all(7.0),
child: new Card(
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
controller: controller,
decoration: new InputDecoration(
hintText: 'Пошук', border: InputBorder.none),
onChanged: onSearchTextChanged,
),
trailing: new IconButton(
icon: new Icon(Icons.cancel),
onPressed: () {
controller.clear();
onSearchTextChanged('');
},
),
),
),
);
}
Widget _buildBody() {
return new Scaffold(
body:Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.white],
begin: Alignment.topCenter,
end: Alignment.bottomCenter),
),
child:Column(
children: <Widget>[
new Expanded( flex: 1, child: _buildSearchBox()),
new Expanded(flex:8,
child: _searchResult.length != 0 || controller.text.isNotEmpty
? _buildSearchResults()
: _buildUsersList()),
],
),
),
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: _buildBody()
);
}
onSearchTextChanged(String text) async {
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return;
}
_userDetails.forEach((userDetail) {
if (userDetail.name.contains(text) ) _searchResult.add(userDetail);
});
setState(() {});
}
}
class UserDetails {
final String name, seal_number,sealed;
UserDetails({this.name, this.sealed, this.seal_number});
factory UserDetails.fromJson(Map<String, dynamic> json) {
return new UserDetails(
sealed: json['sealed'],
name: json['name'],
seal_number: json['seal_number'],
);
}
}
My page:
My page with search:
I have looked at your code several times, I just noticed a small error.
For the results of your searches, you try to display the "List" of searches in a ListView.builder, which is in a column in the parent container does not have a defined height.
Solution: Set a height for the main container and the problem will be solved

Scaffold in flutter

I am new to flutter. I have a question about scaffold in my project.
I have a home screen that I use to display the BottomNavigation widget. I guess that I also use if as a container to display all of the other pages/screens in so that the BottomNavigation will stay visible. Here is the code below:
class Home_Screen extends StatefulWidget {
static const String id = 'home_screen';
#override
_Home_ScreenState createState() => _Home_ScreenState();
}
// ignore: camel_case_types
class _Home_ScreenState extends State<Home_Screen> {
PageController _pageController = PageController();
List<Widget> _screens = [
AgentDashboardScreen(),
TransactionDetailScreen(),
AgentProfileScreen(),
];
int _selectedIndex = 0;
void _onPageChanged(int index) {
setState(() {
_selectedIndex = index;
});
}
void _itemTapped(int selectedIndex) {
if (selectedIndex == 3) {
Navigator.of(context).pushAndRemoveUntil(
// the new route
MaterialPageRoute(
builder: (BuildContext context) => WelcomeScreen(),
),
(Route route) => false,
);
} else {
_pageController.jumpToPage(selectedIndex);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _pageController,
children: _screens,
onPageChanged: _onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: _itemTapped,
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: _selectedIndex == 0 ? Colors.blueAccent : Colors.grey,
),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(
Icons.account_balance,
color: _selectedIndex == 1 ? Colors.blueAccent : Colors.grey,
),
label: 'Add Tran',
),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
color: _selectedIndex == 2 ? Colors.blueAccent : Colors.grey,
),
label: 'Profile',
),
BottomNavigationBarItem(
icon: Icon(
Icons.album_outlined,
color: _selectedIndex == 3 ? Colors.blueAccent : Colors.grey,
),
label: 'Logout',
),
],
),
);
}
}
In one of the screens that I can navigate to from the BottomNavigator I am having issues with a large white space above the keyboard. I have read that having a scaffold inside another scaffold can cause this.
So, when I navigate to the next page do I have a scaffold inside another scaffold? Here is a snippet from the second page.
class TransactionDetailScreen extends StatefulWidget {
static const String id = 'transaction_detail_screen';
final QueryDocumentSnapshot trxns;
//final Trxns trxns;
//final QuerySnapshot queryTrxns = trxns;
TransactionDetailScreen([this.trxns]);
#override
_TransactionDetailScreenState createState() =>
_TransactionDetailScreenState();
}
class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
String _trxnStatus = 'Listed';
#override
Widget build(BuildContext context) {
// Get the stream of transactions created in main.dart
final trxnProvider = Provider.of<TrxnProvider>(context);
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/Appbar_logo.png',
fit: BoxFit.cover, height: 56),
],
),
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
reverse: true,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text(
'Transaction Details',
style: TextStyle(
fontSize: 30,
),
),
SizedBox(
height: 8.0,
),
TextField(
autofocus: true,
keyboardType: TextInputType.text,
controller: clientFNameController,
textAlign: TextAlign.center,
onChanged: (value) {
trxnProvider.changeclientFName(value);
},
decoration: kTextFieldDecoration.copyWith(
hintText: 'Client First Name',
labelText: 'Client First Name'),
),
RoundedButton(
title: 'Save',
colour: Colors.blueAccent,
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
trxnProvider.saveTrxn();
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => AgentDashboardScreen(),
),
);
setState(() {
showSpinner = false;
});
} catch (e) {
// todo: add better error handling
print(e);
}
},
),
SizedBox(
height: 8.0,
),
(widget != null)
? RoundedButton(
title: 'Delete',
colour: Colors.red,
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
trxnProvider.deleteTrxn(widget.trxns['trxnId)']);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => AgentDashboardScreen(),
),
);
setState(() {
showSpinner = false;
});
} catch (e) {
// todo: add better error handling
print(e);
}
},
)
: Container(),
],
),
),
),
);
}
}
The keyboard works/looks as expected (no white space above) if the textboxes are empty. Am I doing this correctly or should I do it differently?
Thanks