How to deal with infinite size - flutter

I was coding my flutter project when I fall under this error. I do not understand because I have tried all the available solution online and still it is not working. The craziest thing is I have the exact same code on the other page and it is working perfectly.
And If I restart the app it works. The first problem was a Material app which is the main function and even if I wrap the column with a scaffold it still doesn't work
Below is the error
The following assertion was thrown during performLayout():
RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
This probably means that it is a render object that tries to be as big as possible, but it was put inside another render object that allows its children to pick their own size.
The nearest ancestor providing an unbounded height constraint is: _RenderSingleChildViewport#20590 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
... needs compositing
... parentData: <none> (can use size)
... constraints: BoxConstraints(w=358.0, 0.0<=h<=731.0)
... layer: OffsetLayer#17148
... engine layer: OffsetEngineLayer#48e1c
... handles: 2
... offset: Offset(16.0, 63.0)
... size: Size(358.0, 731.0)
The constraints that applied to the RenderCustomMultiChildLayoutBox were: BoxConstraints(0.0<=w<=358.0, 0.0<=h<=Infinity)
The exact size it was given was: Size(358.0, Infinity)
Below this I have form that receives data from another one
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:loading_overlay/loading_overlay.dart';
import 'package:tembea/components/rounded_button.dart';
import 'package:tembea/components/show_toast.dart';
import 'package:tembea/components/time_pick.dart';
import 'package:tembea/screens/admin/admin_screens/restaurant/dashboard_restaurant.dart';
import '../../../../../constants.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:tembea/components/square_button.dart';
import 'dart:io' ;
import 'package:firebase_storage/firebase_storage.dart';
import 'add_images.dart';
class RestaurantSecondaryForm extends StatefulWidget {
const RestaurantSecondaryForm({
Key? key,
required this.name,
required this.location,
required this.price,
required this.description,
}) : super(key: key);
final String name;
final String location;
final String price;
final String description;
#override
_RestaurantSecondaryFormState createState() => _RestaurantSecondaryFormState();
}
class _RestaurantSecondaryFormState extends State<RestaurantSecondaryForm> {
bool showSpinner = false;
String selectedOpeningTime = '8:00 AM';
String selectedClosingTime = '17:00 PM';
String ? selectedTime;
final List<String> defaultImageList = [
'assets/images/image.png',
'assets/images/image.png',
'assets/images/image.png',
];
List<String> imageList =[];
List<File> files = [];
List<String> ? imageUrl;
TaskSnapshot? snap;
String ? photoUrl;
String ? photoUrl2;
String ? photoUrl3;
String selectedType = 'Restaurant';
#override
Widget build(BuildContext context) {
Future<void> openTimePicker(context) async {
final TimeOfDay? t =
await showTimePicker(
context: context, initialTime: TimeOfDay.now());
if(t != null){
setState(() {
selectedTime = t.format(context);
});
}
}
goToAddImage() async{
List<String> imgUrl = await Navigator.push(context, MaterialPageRoute(builder:(context){
return const AddImages();
}));
setState(() {
imageUrl = imgUrl;
});
}
if(imageUrl?.isNotEmpty == true){
setState(() {
photoUrl = imageUrl?[0];
photoUrl2 = imageUrl?[1];
photoUrl3 = imageUrl?[2];
imageList.add(photoUrl!);
imageList.add(photoUrl2!);
imageList.add(photoUrl3!);
});
}
else{
setState(() {
photoUrl = '';
photoUrl2 = '';
photoUrl3 = '';
});
}
return LoadingOverlay(
isLoading: showSpinner,
opacity: 0.5,
color: Colors.green,
progressIndicator: const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.green),
),
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: const Text('Add Restaurant'),
backgroundColor: kBackgroundColor.withOpacity(0.3),
),
body: Padding(
padding: const EdgeInsets.all(40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CarouselSlider(
options: CarouselOptions(
enlargeCenterPage: true,
enableInfiniteScroll: false,
autoPlay: false,
),
items:imageList.isEmpty ? defaultImageList.map((e) => ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
fit: StackFit.expand,
children: [
Image.asset(
e,
width: 1000,
height: 300,
fit: BoxFit.fill,
)
],
),
)).toList()
: imageList.map((e) => ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
fit: StackFit.expand,
children: [
Image.network(
e,
width: 1000,
height: 300,
fit: BoxFit.fill,
)
],
),
)).toList(),
),
const SizedBox(
height: 20,
),
Column(
children: [
DateButton(
text: 'Upload Images',
onPressed: () {
goToAddImage();
},
),
],
),
Column(
children: [
TimePick(
label: 'Opens at',
labelColor: Colors.green,
time: selectedOpeningTime,
onPressed: (){
openTimePicker(context).then((value) {
setState(() {
selectedOpeningTime = selectedTime!;
});
});
},
),
const SizedBox(
height: 20,
),
TimePick(
label: 'Closes at',
labelColor: Colors.red,
time: selectedClosingTime,
onPressed: (){
openTimePicker(context).then((value) {
setState(() {
selectedClosingTime = selectedTime!;
});
});
}
),
],
),
RoundedButton(
buttonName: 'Add Restaurant',
color: Colors.green,
onPressed: () async{
setState(() {
showSpinner = true;
});
final time = DateTime.now();
await FirebaseFirestore.instance.collection('activities').doc().set({
'Name' : widget.name,
'Location': widget.location,
'Description' : widget.description,
'Price' : widget.price,
'OpeningTime' : selectedOpeningTime,
'ClosingTime' : selectedClosingTime,
'PhotoUrl' : photoUrl,
'PhotoUrl2' : photoUrl2,
'PhotoUrl3' : photoUrl3,
'Type' : selectedType,
'ts' : time,
}).then((value) {
setState(() {
showSpinner = false;
});
showToast(message: 'Restaurant Added',
color: Colors.green
);
Navigator.pushNamedAndRemoveUntil(context, DashboardRestaurant.id, (r) => false);
});
}
),
],
),
),
),
);
}
}
which is supposed to navigate back to this view that brings the error
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tembea/components/add_button.dart';
import 'package:tembea/components/responsive.dart';
import 'package:tembea/components/show_dialog.dart';
import 'package:tembea/components/show_toast.dart';
import 'package:tembea/screens/admin/admin_screens/view_data.dart';
import 'event_form.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
class DashboardEvent extends StatefulWidget {
const DashboardEvent({Key? key}) : super(key: key);
static String id = 'dashboard_event';
#override
_DashboardEventState createState() => _DashboardEventState();
}
class _DashboardEventState extends State<DashboardEvent> {
final Stream<QuerySnapshot> activities = FirebaseFirestore
.instance.collection('activities')
.where('Type', isEqualTo: 'Event')
.orderBy('ts', descending: true)
.snapshots();
#override
Widget build(BuildContext context) {
return Column(
children: [
AddButton(
title: 'Events',
addLabel: 'Add Events',
onPressed: (){
Navigator.pushNamed(context, EventForm.id);
},),
const SizedBox(
height: 16.0,
),
const Divider(
color: Colors.white70,
height:40.0,
),
StreamBuilder<QuerySnapshot>(
stream: activities,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.green),
),
);
}
final data = snapshot.requireData;
if(data != null){
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: data.size,
itemBuilder: (context, index){
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CircleAvatar(
backgroundColor: Colors.transparent,
radius: 40,
child:Image.network(
data.docs[index]['PhotoUrl'],
),
),
Text( data.docs[index]['Name'], style:const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
),
if(Responsive.isWeb(context))
const SizedBox(
width: 50,
),
Responsive.isWeb(context) ? ButtonBlue(
addLabel: 'View Event',
color: Colors.green,
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context){
return ViewData(item: data.docs[index],);
}));
},
icon: const Icon(IconData(61161, fontFamily: 'MaterialIcons')),
) : InkWell(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context){
return ViewData(item: data.docs[index],);
}));
},
child: const Icon(IconData(61161, fontFamily: 'MaterialIcons')),
),
Responsive.isWeb(context) ? ButtonBlue(
addLabel: 'Delete Event',
color: Colors.red,
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context){
return ShowDialog(
deleteFunction: () async{
await FirebaseFirestore.instance.runTransaction((Transaction myTransaction) async {
FirebaseStorage.instance.refFromURL(data.docs[index]['PhotoUrl']).delete();
myTransaction.delete(snapshot.data!.docs[index].reference);
}).then((value) => Navigator.pop(context));
},
dialogTitle: "Delete",
dialogContent: "Do you really want to delete ${data.docs[index]['Name']} event?",
);
});
},
icon: const Icon(Icons.delete_outline,),
): InkWell(
onTap: (){
if(defaultTargetPlatform == TargetPlatform.iOS){
showCupertinoDialog(
context: context,
builder: (BuildContext context){
return ShowDialog(
deleteFunction: () async{
await FirebaseFirestore.instance.runTransaction((Transaction myTransaction) async {
FirebaseStorage.instance.refFromURL(data.docs[index]['PhotoUrl']).delete();
myTransaction.delete(snapshot.data!.docs[index].reference);
}).then((value) => Navigator.pop(context));
},
dialogTitle: "Delete",
dialogContent: "Do you really want to delete ${data.docs[index]['Name']} event?",
);
});
}
else if((defaultTargetPlatform == TargetPlatform.android)){
showDialog(
context: context,
builder: (BuildContext context){
return ShowDialog(
deleteFunction: () async{
await FirebaseFirestore.instance.runTransaction((Transaction myTransaction) async {
FirebaseStorage.instance.refFromURL(data.docs[index]['PhotoUrl']).delete();
myTransaction.delete(snapshot.data!.docs[index].reference);
}).then((value) => Navigator.pop(context));
},
dialogTitle: "Delete",
dialogContent: "Do you really want to delete ${data.docs[index]['Name']} event?",
);
});
}
else{
showDialog(
context: context,
builder: (BuildContext context){
return ShowDialog(
deleteFunction: () async{
await FirebaseFirestore.instance.runTransaction((Transaction myTransaction) async {
FirebaseStorage.instance.refFromURL(data.docs[index]['PhotoUrl']).delete();
myTransaction.delete(snapshot.data!.docs[index].reference);
Navigator.pop(context);
showToast(message: 'Deleted Successfully', color: Colors.green);
}).then((value) => Navigator.pop(context));
},
dialogTitle: "Delete",
dialogContent: "Do you really want to delete ${data.docs[index]['Name']} event?",
);
});
}
},
child: const Icon(Icons.delete_outline,),
),
],
),
const Divider(
color: Colors.white70,
height:40.0,
),
],
);
});
}
return const Center(
child: CircularProgressIndicator(),
);
},
)
],
);
}
}
I have been on this the entire day but in vain but in the same product, I have another view details with the same code that works
Please assist me on this

Related

How to call a function only once while the page is active in flutter

I have a dart page voterhome(like dashboard),at first when I arrive at voterhome it will call the getuserdetails() function and get the adhar of user to pass it to other pages so I can navigate to other pages (like vote,voteregister ..etc)
when I return back to voterhome from other pages it will call the getuserdetails()function again because the function is inside initstate() I don't want this to happen how can I do that
my code :
voterhome.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:election/services/IntoLogin.dart';
import 'package:election/pages/Voter/Vote.dart';
import 'package:election/pages/Voter/VoteRegister.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';
import '../../services/Auth.dart';
import '../../utils/Constants.dart';
import '../../services/Electioninfo.dart';
import '../../services/VerifyEmail.dart';
class VoterHome extends StatefulWidget {
//getting required parameters to pass on to vote and authorize
final Web3Client ethClient;
final String electionName;
final String electionaddress;
const VoterHome({Key? key, required this.ethClient, required this.electionName, required this.electionaddress}) : super(key: key);
#override
State<VoterHome> createState() => _VoterHomeState();
}
class _VoterHomeState extends State<VoterHome> {
//creating clients
late Client? httpClient;//http client
late Web3Client? ethclient;// eth client
//sign out user
final User? user = Auth().currentuser;
Future<void>signOut()async{
await Auth().signOut();
if(!mounted)return;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>IntroLogin()), (route) => false);
}
// voters info
var email;
var adhar;
var name;
var phone;
//checking if voter authorized or voted // dont have to do this because we does this on the respected pages
late bool isAuth = false;//if he is authorized
late bool isVoted = false;//if he is voted
Future<void>getUserDetail() async {
try {
final DocumentSnapshot voters = await FirebaseFirestore.instance
.collection('voters')
.doc(user?.email)
.get();
if (voters.data() != null) {
email = voters.get('email');
name = voters.get('name');
phone = voters.get('phone');
adhar = voters.get('adharnum');
print('adhar is $adhar');
}else{
print('cannot find details');
}
showSnackBar(succesdetailsnackSnack);
} catch (e) {
if (kDebugMode) {
print('get check user ::::: $e');
showSnackBar(errordetailsnackSnack);
}
}
}//function to check ends
#override
void initState() {
httpClient = Client();
ethclient = Web3Client(infura_url, httpClient!);
WidgetsBinding.instance.addPostFrameCallback((_) async {
await getUserDetail();
setState(() { });
});
super.initState();
}
#override
Widget build(BuildContext context) {
Map<String,dynamic> voterdata = {'name':name,'adharnum':adhar.toString(),'email':email,};
if(user!.emailVerified){
return Scaffold(
appBar: AppBar(
leading: IconButton(onPressed: () { signOut(); }, icon: const Icon(Icons.logout),),
actions: [IconButton(onPressed:(){setState(() {});}, icon: const Icon(Icons.refresh))],
title: const Text('Voter DASHBOARD'),backgroundColor: Colors.cyan,),
body: SingleChildScrollView(
child: Column(
children: [
Container(
padding: const EdgeInsets.all(24),
margin: const EdgeInsets.only(bottom: 16),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VoteRegister(electionName:widget.electionName,
ethClient: widget.ethClient, electionaddress:widget.electionaddress,adhar:adhar,)));
},
child: Card(borderOnForeground: true,elevation: 4,
child: Column(
children: [
Container(height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
image: const DecorationImage(
image: AssetImage('assets/undraw/electionday.png')))),
Container(decoration: const BoxDecoration(color: Colors.cyan),width: double.infinity,
child: const Center(
child: Text('Register to Vote',style: TextStyle(
fontWeight: FontWeight.bold,fontSize:16,color: Colors.white),),
),
)
],
),
),
),
),
Container(
padding: const EdgeInsets.all(24),
margin: const EdgeInsets.only(bottom: 16),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VoterVote(ethClient:ethclient!,electionName:widget.electionName,
electionaddress:widget.electionaddress ,votermap:voterdata,)));
},
child: Card(borderOnForeground: true,elevation: 4,
child: Column(
children: [
Container(height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
image: const DecorationImage(
image: AssetImage('assets/undraw/upvote.png')))),
Container(decoration: const BoxDecoration(color: Colors.cyan),width: double.infinity,
child: const Center(
child: Text('Vote',style: TextStyle(fontWeight: FontWeight.bold,fontSize:16,color: Colors.white),),
),
)
],
),
),
),
),
Container(
padding: const EdgeInsets.all(24),
margin: const EdgeInsets.only(bottom: 16),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ElectionInfo(ethClient:ethclient!,electionName:widget.electionName,
electionAddress:widget.electionaddress,)));
},
child: Card(borderOnForeground: true,elevation: 4,
child: Column(
children: [
Container(height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
image: const DecorationImage(
image: AssetImage('assets/undraw/electionday.png')))),
Container(decoration: const BoxDecoration(color: Colors.cyan),width: double.infinity,
child: const Center(
child: Text('Election details',style: TextStyle(
fontWeight: FontWeight.bold,fontSize:16,color: Colors.white),),
),
)
],
),
),
),
),
],
),
)
);
}else{
return Scaffold(
appBar:AppBar( ///app bar
backgroundColor: Colors.cyan,
leading: IconButton(
onPressed: () {
signOut();
},
icon: const Icon(Icons.logout_sharp),
),
title: const Text('Verify Voter email'),
actions: [
IconButton(
onPressed: () {
refresh();
},
icon: const Icon(Icons.refresh))
],
),
body: Container(margin: const EdgeInsets.only(top: 56),
child: Center(
child: Column(
children: [
Text('Your Email ${user?.email} is not verified'),
const SizedBox(height: 24,),
ElevatedButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => const VerifyEmail()),
(route) => false);
},
child: const Text('Verify Email'))
],
),
),
),
);
}
}
//function to refresh using setstate
void refresh() {
setState(() {});
}
//snackbar
SnackBar errordetailsnackSnack = const SnackBar(content: Text('You are not logged in if you are please check your internet connection'));
SnackBar succesdetailsnackSnack = const SnackBar(content: Text('successfull'));
SnackBar votedSnack = const SnackBar(content: Text('You have already voted'));
SnackBar RegisterSnack = const SnackBar(content: Text('You have already registered'));
// SnackBar errorSnack = const SnackBar(content: Text('Fill all the details'));
// SnackBar datanullSnack = const SnackBar(content: Text('No users registerd yet'));
//function to show snackbar
ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(SnackBar snackBar) {
return ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
vote.dart //when i go to voterhome() from this it again calls the function
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:election/pages/Voter/VoterHome.dart';
import 'package:election/utils/Constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:web3dart/web3dart.dart';
import '../../services/Auth.dart';
import '../../services/functions.dart';
import '../../services/IntoLogin.dart';
class VoterVote extends StatefulWidget {
final Web3Client ethClient;
final String electionName;
final String electionaddress;
final votermap;
const VoterVote({Key? key, required this.ethClient, required this.electionName, required this.electionaddress, this.votermap,}) : super(key: key);
#override
State<VoterVote> createState() => _VoterVoteState();
}
class _VoterVoteState extends State<VoterVote> {
final User? user = Auth().currentuser;//fi// rebase auth current user initialization
//sign out user function
Future<void> signOut() async {
if (!mounted) return;
await Auth().signOut();
if (!mounted) return;
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => IntroLogin()),
(route) => false);
}
//checking if the voter is already voted
late bool isAuth = false;
late bool isVoted = false;
Future<void>getUserDetail() async {
var voterdetails = widget.votermap;
try {
final DocumentSnapshot voters = await FirebaseFirestore.instance
.collection('Election')
.doc(widget.electionName).collection('voterAuth').doc(voterdetails['adharnum'])
.get();
if (voters.data() != null) {
isAuth = voters.get('isAuth');
isVoted = voters.get('isVoted');
}else{
isAuth = false;
isVoted= false;
print('cannot find details');
}
} catch (e) {
if (kDebugMode) {
print('get check user ::::: $e');
}
}
}//function to check ends
TextEditingController privatekeyController = TextEditingController();
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await getUserDetail();
setState(() { });
});
super.initState();
}
#override
Widget build(BuildContext context) {
if(isVoted== true && isAuth == true){
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.cyan,
leading: IconButton(onPressed: (){signOut();},icon: const Icon(Icons.logout_sharp),),
title:const Text('Vote'),
actions: [
IconButton(onPressed:(){
refresh();
}, icon: const Icon(Icons.refresh))
],
),
body: const Center(child: Text('you have already voted sir'),),
);
}else if(isVoted == false&&isAuth == true){
return Scaffold(
appBar:AppBar(
backgroundColor: Colors.cyan,
leading: IconButton(onPressed: (){signOut();},icon: const Icon(Icons.logout_sharp),),
title:const Text('Vote'),
actions: [
IconButton(onPressed:(){
refresh();
}, icon: const Icon(Icons.refresh))
],
),
body: Container(margin:const EdgeInsets.only(bottom: 56,top: 24),alignment: Alignment.topCenter,
child:SingleChildScrollView(
child: Column(
children: [
Center(
child: SelectableText("$voter_private_key && $voter_key2 && $voter_key3")
),
const SizedBox(height: 24,),
Container(padding: const EdgeInsets.all(16),
child: TextField(
controller: privatekeyController,
decoration:
const InputDecoration(hintText: 'Private key for voting',border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(8))))),
),
const SizedBox(height: 24,),
SingleChildScrollView(
child: StreamBuilder<List>(stream:getCandidatesNum(widget.ethClient,widget.electionaddress).asStream(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return Column(
children: [
for (int i = 0; i < snapshot.data![0].toInt(); i++)
FutureBuilder<List>(
future: candidateInfo(i, widget.ethClient,widget.electionaddress),
builder: (context, candidatesnapshot) {
if (candidatesnapshot.connectionState ==
ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return Card( //card to represent the candidate
color: Colors.cyan,
child: SizedBox(height: 100,
child: Center(
child: ListTile(
title: Text('Name: ${candidatesnapshot.data![0][0]}'),
subtitle: Text('Votes: ${candidatesnapshot.data![0][1]}'),
leading: ConstrainedBox(
constraints: const BoxConstraints(
minHeight: 90,
minWidth: 90,
maxHeight: 100,
maxWidth: 100,
),
child:const Image(image: AssetImage('assets/undraw/electionday.png')),
),
trailing: ElevatedButton(
onPressed: ()async {
try{
await vote(i,widget.ethClient,privatekeyController.text,widget.electionaddress);
await registerAuth();
gotoDashboard();
showSnackBar(succesdetailsnackSnack);
}catch(e){
if (kDebugMode) {
print(e);
}
showSnackBar(errordetailsnackSnack);
gotoDashboard();
}
}, child: const Text('Vote'),),
),
),
),
);
}
})
],
);
}
},
),
),
],
),
),
),
);
}else{
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.cyan,
leading: IconButton(onPressed: (){signOut();},icon: const Icon(Icons.logout_sharp),),
title:const Text('Vote'),
actions: [
IconButton(onPressed:(){
refresh();
}, icon: const Icon(Icons.refresh))
],
),
body: const Center(child: Text('you are not authorized please authorize first'),),
);
}
}
//snackbar
SnackBar errordetailsnackSnack = const SnackBar(content: Text(' already voted or please check your internet connection'));
SnackBar succesdetailsnackSnack = const SnackBar(content: Text('successfull'));
SnackBar voterSnack = const SnackBar(content: Text('you are a voter logout from voter account'));
SnackBar adminSnack = const SnackBar(content: Text('you are an admin logout from Admin account'));
// SnackBar errorSnack = const SnackBar(content: Text('Fill all the details'));
// SnackBar datanullSnack = const SnackBar(content: Text('No users registerd yet'));
//function to show snackbar
ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(SnackBar snackBar) {
return ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
void refresh() {
setState(() {});
}
Future<void> registerAuth() async {
var voterdetails = widget.votermap;
try {
await FirebaseFirestore.instance.collection('Election').doc(widget.electionName).collection('voterAuth').doc(voterdetails['adharnum']).update({'isVoted':true});
print('updated data aaaaaaaaaaaaaaa');
} catch (e) {
if (kDebugMode) {
print('failed to register on firebase $e');
}
}
}
void gotoDashboard(){
Navigator.pushAndRemoveUntil(context,MaterialPageRoute(builder:(context)=>VoterHome(ethClient: widget.ethClient,
electionName: widget.electionName, electionaddress: widget.electionaddress)), (route) => false);
}
}
One way to achieve what you want is by making your page retain its state.
Try this code
You have to add with AutomaticKeepAliveClientMixin to the screen like in the snippet below.
Override this #override bool get wantKeepAlive => true;.
Inside build method, add this super.build(context);.
class _TestScreen extends State<TestScreen> with AutomaticKeepAliveClientMixin<TestScreen> {
#override
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context);
return Scaffold();
}
}
After doing this, your page will not call initState() everytime that page is loaded.
When you navigate from VoteHome page to VoteRegister page, you use the push method. The push method returns a Future object. You can use the then method of Future to execute your code after VoteRegister was popped from the navigation stack or in other words the user pressed back button in appbar.
Navigator.of(context)
.push(MaterialPageRoute(
builder: (context) => VoteRegister(electionName:widget.electionName,ethClient: widget.ethClient, electionaddress:widget.electionaddress,adhar:adhar,)))
.then((value) {
// you can do what you need here
// setState etc.
// also reload your data here
});

Flutter: SharedPreferences showing null value?

eg: details about the questions ............................................................................................i have set a address in home page using SharedPreferences but when i get that value in SearchModulePage showing null. i have tried many more times always showing null
Home Page:-
import 'dart:convert';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:double_back_to_close_app/double_back_to_close_app.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoder/geocoder.dart';
import 'package:http/http.dart' as http;
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/category_model.dart';
import 'package:newbharatbiz/Screens/SearchServiceProvider.dart';
import 'package:newbharatbiz/Screens/SubCategoryPage.dart';
import 'package:newbharatbiz/Utils/NavDrawer.dart';
import 'package:newbharatbiz/Utils/Serverlinks.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Model Class/banner_model.dart';
import 'VendorRegistrationPage.dart';
import 'package:location/location.dart';
import 'package:flutter/services.dart';
var addressLine;
var getaddressLine;
var androidDeviceInfo;
var token;
var identifier;
var user_id;
var phone;
var name;
class HomePage extends StatefulWidget {
#override
_YourWidgetState createState() => _YourWidgetState();
}
class _YourWidgetState extends State<HomePage> {
Future<BannerModel> BannerList() async {
final response = await http.get(Uri.parse(Serverlinks.all_banner));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response);
return BannerModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Future<CategoryModel> CategoryList() async {
final response = await http.get(Uri.parse(Serverlinks.category_list));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response);
return CategoryModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
// late DateTime currentBackPressTime;
List<String> imagesList = [];
var currentLocation;
int currentIndexPage = 0;
#override
void initState() {
super.initState();
getUserLocation();
getdeviceid();
gettoken();
Setsharedpreferencevalue();
Getsharedpreferencevalue();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.deepOrangeAccent,
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VendorRegistrationPage(),
),
);
},
),
drawer: NavDrawer(),
appBar:
AppBar(title: Text('New Bharat Biz'), centerTitle: true, actions: [
IconButton(
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchServiceProvider(),
),
);
},
icon: Icon(Icons.search),
),
]),
body: DoubleBackToCloseApp(
child: SingleChildScrollView(
child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
FutureBuilder<BannerModel>(
future: BannerList(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
print((snapshot.data));
snapshot.data!.banner.forEach((e) {
imagesList.add(snapshot.data!.imgPath + e.image);
print(imagesList.length);
});
return CarouselSlider(
//add return keyword here
options: CarouselOptions(
height: 160,
aspectRatio: 16 / 9,
viewportFraction: 0.8,
initialPage: 0,
enableInfiniteScroll: true,
reverse: false,
autoPlay: true,
autoPlayInterval: const Duration(seconds: 3),
autoPlayAnimationDuration:
const Duration(milliseconds: 800),
autoPlayCurve: Curves.fastOutSlowIn,
enlargeCenterPage: true,
),
items: imagesList
.map(
(item) => Center(
child: Image.network(item,
fit: BoxFit.cover, width: 1000)),
)
.toList(),
);
}
return const Center(
/*
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
*/
);
}
// By default, show a loading spinner.
),
FutureBuilder<CategoryModel>(
future: CategoryList(),
builder: (BuildContext context, snapshot) {
//_getId();
if (snapshot.hasData) {
List<Result> data = snapshot.data!.result;
print((snapshot.data));
return GridView.builder(
itemCount: data.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
//padding: EdgeInsets.all(1),
itemBuilder: (ctx, index) {
return Padding(
padding: EdgeInsets.all(0.0),
child: new GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SubCategoryPage(
data[index].id,
),
),
);
},
child: new Container(
margin: const EdgeInsets.all(0),
padding: const EdgeInsets.all(0),
decoration: BoxDecoration(
border: Border.all(
width: 0.5,
color: Colors.grey,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 25,
),
Image.network(
snapshot.data!.imgPath + data[index].coverPic,
height: 55,
width: 55,
),
SizedBox(
height: 10,
),
Expanded(
child: Text(
data[index].name,
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
textAlign: TextAlign.center,
),
)
],
),
),
),
);
},
);
} else {
return const Center(
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
);
}
},
),
]),
),
snackBar: const SnackBar(
content: Text('Tap back again to leave'),
),
),
);
}
/*
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
return Future.value(false);
}
return Future.value(true);
}
*/
void getUserLocation() async {
//call this async method from whereever you need
LocationData? myLocation;
String error;
Location location = new Location();
try {
myLocation = await location.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'please grant permission';
print(error);
}
if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error = 'permission denied- please enable it from app settings';
print(error);
}
myLocation = null;
}
currentLocation = myLocation;
final coordinates =
new Coordinates(myLocation?.latitude, myLocation?.longitude);
var addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
String adminArea = first.adminArea;
String locality = first.locality;
String subLocality = first.subLocality;
String subAdminArea = first.subAdminArea;
addressLine = first.addressLine;
String featureName = first.featureName;
String thoroughfare = first.thoroughfare;
String subThoroughfare = first.subThoroughfare;
/* print(' ${first.locality}, ${first.adminArea},${first.subLocality}, ${first.subAdminArea},${first.addressLine}, ${first.featureName},${first.thoroughfare}, ${first.subThoroughfare}');
return first;*/
}
gettoken() async {
//token = await FirebaseMessaging.instance.getToken();
FirebaseMessaging.instance.getToken().then((token) {
token = token.toString();
// do whatever you want with the token here
});
}
getdeviceid() async {
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
if (Platform.isAndroid) {
AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
androidDeviceInfo = androidInfo.id!; //UUID for Android
} else if (Platform.isIOS) {
IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
androidDeviceInfo = iosInfo.identifierForVendor; //UUID for Android
}
}
void Setsharedpreferencevalue() async {
setState(() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('addressLine', addressLine);
prefs.setString('deviceID', androidDeviceInfo);
await prefs.setString("token", token!);
});
}
void Getsharedpreferencevalue() async {
setState(() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
androidDeviceInfo = prefs.getString('deviceID');
getaddressLine = prefs.getString('addressLine');
token = prefs.getString('token');
user_id = prefs.getString('user_id');
phone = prefs.getString('phone');
name = prefs.getString('name');
print("info : ${androidDeviceInfo}");
});
}
}
SearchModulePage:-
import 'dart:convert';
import 'package:flutter_mapbox_autocomplete/flutter_mapbox_autocomplete.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:newbharatbiz/Screens/SubCategoryPage.dart';
import 'package:shared_preferences/shared_preferences.dart';
var addressLine;
TextEditingController Locality = TextEditingController();
class SearchModulePage extends StatefulWidget {
String id;
String catId;
String serviceName;
String image;
String imgPath;
SearchModulePage(
this.id, this.catId, this.serviceName, this.image, this.imgPath);
#override
_YourWidgetState createState() =>
_YourWidgetState(id, catId, serviceName, image, imgPath);
}
class _YourWidgetState extends State<SearchModulePage> {
String id;
String catId;
String serviceName;
String image;
String imgPath;
_YourWidgetState(
this.id, this.catId, this.serviceName, this.image, this.imgPath);
#override
void initState() {
super.initState();
getshareddprefernces();
}
#override
Widget build(BuildContext context) {
// getsharedprefernces();
return WillPopScope(
onWillPop: () async => true,
child: new Scaffold(
appBar: new AppBar(
title: new Text(serviceName),
leading: new IconButton(
icon: new Icon(Icons.arrow_back_outlined),
onPressed: () {
Navigator.pop(
context, true); // It worked for me instead of above line
/* Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SubCategoryPage(
catId,
)),
);*/
}),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 30),
Image.network(
imgPath + image,
width: 60.0,
height: 60.0,
),
// Padding(padding: EdgeInsets.only(top: 15.0)),
const SizedBox(height: 20),
Text(serviceName,
style: TextStyle(color: Colors.black, fontSize: 15)),
// Padding(padding: EdgeInsets.only(top: 30.0)),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: Locality,
readOnly: true,
// initialValue: addressLine,
// set it to a string by default
decoration: InputDecoration(
hintText: "Search your locality",
hintStyle: TextStyle(
color: Color(0xff323131),
),
suffixIcon: Icon(
Icons.location_on_rounded,
color: Color(0xFF00796B),
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MapBoxAutoCompleteWidget(
apiKey:
"pk.eyJ1IjoibmV3YmhhcmF0Yml6IiwiYSI6ImNrbWJqb3B5ZzIyZnUyd254M2JndmhnNnQifQ.Km7hMjBHD_kwHWL7x7Y-Jg",
hint: "Search your locality",
onSelect: (place) {
// TODO : Process the result gotten
Locality.text = place.placeName!;
},
limit: 10,
),
),
);
},
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
// FocusScope.of(context).requestFocus(FocusNode());
addressLine = Locality.text;
if (addressLine == "") {
Fluttertoast.showToast(
msg: "Enter your locality",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black54,
textColor: Colors.white,
fontSize: 16.0);
/* var snackBar = SnackBar(content: Text('Enter your locality'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);*/
} else {
// String locality = Locality.text;
}
},
child: Text("Submit"),
style: ElevatedButton.styleFrom(
primary: Color(0xFF00796B),
padding:
EdgeInsets.symmetric(horizontal: 100, vertical: 10),
textStyle:
TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
),
],
),
),
),
);
}
void getshareddprefernces() async {
setState(() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
addressLine = await prefs.getString('addressLine');
Locality.text = addressLine.toString();
Fluttertoast.showToast(
msg: addressLine,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black54,
textColor: Colors.white,
fontSize: 16.0);
});
}
}
You have to wait till all asynchronous process is over, then after that when all values (here address, deviceId and token) are set to variables, then you can save or set values to shared preferences.
Here is the sample code for you:
#override
void initState() {
super.initState();
initializeVariables().then((boolValue){
Setsharedpreferencevalue();
});
// ..
}
Future<Boolean> initializeVariables() async {
await getUserLocation();
await getdeviceid();
await gettoken();
return true;
}

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:

Flutter:1 positional argument(s) expected, but 0 found

I am working on a flutter project, which separated the body: widget from the main.dart and placed it inside a new statefull widget with the file name todu_list.dart now i am trying to call it back to main.dart file body: SingleChildScrollView(child: Lists()), and am getting this error
1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.
I have gone through alot of similar questions here on StackOverFlow and realised i am supposed to add an argument inside the brackets "()" but i don't know which of the function from my Lists widget that i am expected to call there
Below is the "Lists" widget code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../models/todus.dart';
import 'package:intl/intl.dart';
import 'package:sqflite/sqflite.dart';
import '../models/database_helper.dart';
class Lists extends StatefulWidget {
final Function addTx;
Lists(this.addTx);
#override
_ListsState createState() => _ListsState();
}
class _ListsState extends State<Lists> {
final dbHelper = DatabaseHelper.instance;
void _addNewTransaction(BuildContextcontext) {
showModalBottomSheet(
backgroundColor: Colors.white,
isScrollControlled: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0))),
context: context,
builder: (_) {
return GestureDetector(
onTap: () {},
// Where i started the code pasting from
child: Padding(
padding: MediaQuery.of(context).viewInsets,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 0.000,
child: Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
autofocus: true,
onSubmitted: null,
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Description'),
controller: _discriptionController,
onSubmitted: null,
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: [
Text(selectedDateAndTime == null
? 'No Date Choosen'
: DateFormat('MM/dd/yyyy HH:mm')
.format(selectedDateAndTime)
// : DateFormat.yMd()
// .format(_selectedDate),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Icon(Icons.calendar_today),
// onPressed: () async {
// var value = await _selectedTime();
// },
onPressed: () => _selectDayAndTimeL(context),
),
],
),
),
RaisedButton(
child: Text('Save Todo'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
onPressed: _submitData,
),
],
),
),
),
),
),
);
},
);
}
final _titleController = TextEditingController();
final _discriptionController = TextEditingController();
var favorite;
// DateTime _selectedDate;
DateTime selectedDateAndTime;
#override
void dispose() {
super.dispose();
_discriptionController.dispose();
_titleController.dispose();
}
Future _selectDayAndTimeL(BuildContext context) async {
DateTime _selectedDay = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) => child);
TimeOfDay _selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (_selectedDay != null && _selectedTime != null) {
//a little check
}
setState(() {
selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
// _selectedDate = _selectedDay;
});
// print('...');
}
List<ItemLists> items = [
ItemLists(
title: 'Best Music of the Year',
description: 'Davido',
favorite: false,
),
ItemLists(
title: 'Best Album Cover design',
description: 'Brighter Press',
favorite: false,
),
void _submitData() {
// if (_amountController.text.isEmpty) {
// return;
// }
final enteredTitle = _titleController.text;
final enteredDescription = _discriptionController.text;
if (enteredTitle.isEmpty) {
return;
}
widget.addTx(
enteredTitle,
enteredDescription,
selectedDateAndTime,
);
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return SizedBox(
child: Container(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) {
return Dismissible(
key: ObjectKey(items[index]),
background: Container(
color: Colors.red,
),
child: Card(
child: ListTile(
leading: new IconButton(
icon: Icon(
Icons.check,
color:
items[index].favorite ? Colors.green : Colors.grey,
),
tooltip: 'Add to Favorite',
onPressed: () {
setState(() {
items[index].favorite = !items[index].favorite;
});
}),
title: Text('${items[index].title}'),
subtitle: Text('${items[index].description}'),
trailing: IconButton(
icon: Icon(Icons.calendar_today),
onPressed: () => _selectDayAndTimeL(context),
),
)),
onDismissed: (direction) {
final String myTitle = items[index].title;
// Remove the item from the data source.
setState(() {
var deletedItems = items.removeAt(index);
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('$myTitle Deleted'),
action: SnackBarAction(
label: 'Undo',
onPressed: () => setState(
() => items.insert(index, deletedItems),
)),
),
);
});
});
},
itemCount: items.length,
),
),
);
floatingActionButton:
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _addNewTransaction(context),
backgroundColor: Colors.redAccent,
);
}
}
You have to give a function as parameter in order to build your widget. This is not a function of your widget that you will be calling but the function addTx that you will be calling from within your Lists widget.
Either remove the parameter or pass a function to solve it.
Example: since your function is expected to have 3 parameters:
widget.addTx(
enteredTitle,
enteredDescription,
selectedDateAndTime,
);
you can create:
void addTitleDescDate(string title, string description, string date) { // NB you should probably use a Date object or epoch time.
print(title);
print(description);
print(date);
}
And you use this function Lists(addTitleDescDate)
As a side note I don't really see the point to have this function as a parameter shared to the Lists widget, but if you want to learn more about function as parameter that is still interesting.

Search with filter card (data from api) for Flutter

I have a code with the help of which I take the data through the Get method and use this data in the cards. I highlight the cards with color depending on their condition. The problem is that I can't add a search by (item.name). But I can't do it. I found some examples but couldn't add them to my code. I will be grateful for your help. Here is my code:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/object_main/ObjectListGet.dart';
import 'package:flutter_app_seals/model/object_main/ServicesObjectMain.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;
class JsonParseObjectSts extends StatefulWidget {
//
JsonParseObjectSts() : super();
#override
_JsonParseObjectsState createState() => _JsonParseObjectsState();
}
class _JsonParseObjectsState extends State <StatefulWidget> {
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder< List<ObjectListMain>>(
future: ServicesObjectMain.getObjectMain(),
builder: (context, snapshot)
{
// Data is loading, you should show progress indicator to a user
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
// Data is loaded, handle it
return ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(40),
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
final item = snapshot.data[index];
return Card(
color: (item.sealed == "Так") ? Colors.redAccent : Colors.greenAccent,
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
item.name,
style: TextStyle(fontSize: 30),
),
subtitle: Text("Запломбований:${item.sealed}"),
leading: Icon(
Icons.home_outlined,
size: 40,
color: Colors.black87,
),
onTap: () =>
{
if ('Так' == item.sealed) {
global.nameObj = item.name,
global.sealsNumb = item.seal_number,
global.typesOp = 'Так',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Unseals()),
)
}
else{
{
global.nameObj = item.name,
global.typesOp = 'Ні',
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Form_seals()),
)
}
}
}
),
);
},
);
}
);
return new Scaffold(
body:Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.white],
begin: Alignment.topCenter,
end: Alignment.bottomCenter),
),
child: futureBuilder
),
);
}
}
And scrin :
Also I tried one more way, but in it there is a problem, the data which I take away from api they are duplicated. Duplicate when I go to this page or when I delete text from the search widget.
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:convert';
import 'package:http/http.dart' as http;
class JsonParseObjectSts extends StatefulWidget {
#override
_JsonParseObjectsState createState() => _JsonParseObjectsState();
}
class _JsonParseObjectsState extends State <StatefulWidget> {
TextEditingController controller = new TextEditingController();
// Get json result and convert it to model. Then add
Future<Null> getUserDetails() async {
final response = await http.get(url);
final responseJson = json.decode(response.body);
setState(() {
for (Map user in responseJson) {
_userDetails.add(UserDetails.fromJson(user));
}
});
}
#override
void initState() {
super.initState();
getUserDetails();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Column(
children: <Widget>[
new Container(
color: Theme.of(context).primaryColor,
child: 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('');
},),
),
),
),
),
new Expanded(
child: _searchResult.length != 0 || controller.text.isNotEmpty
? 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: 30),
),
subtitle: Text("Запломбований:${_searchResult[i].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 40,
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()),
)
}
}
}
),
);
},
)
: 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: 30),
),
subtitle: Text("Запломбований:${_userDetails[index].sealed}"),
leading: Icon(
Icons.home_outlined,
size: 40,
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()),
)
}
}
}
),
);
},
),
),
],
),
);
}
onSearchTextChanged(String text) async {
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return ;
}
_userDetails.forEach((userDetail) {
if (userDetail.name.contains(text) || userDetail.name.contains(text))
_searchResult.add(userDetail);
});
setState(() {});
}
}
List<UserDetails> _searchResult = [];
List<UserDetails> _userDetails = [];
final String url = global.urlVar + '/object_status' + '?data_area=' + global.dataArea;
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'],
);
}
}