how to make button together on flutter - android

Hello i have some problem, I need to make button together on my flutter code Like this,
but when i try on flutter it become like This, is there any way to make it like in first image?
heres my code for the button
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SizedBox(
width: 130,
height: 50,
child: TextButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.blue)),
onPressed: () {},
child: Text(
'Login',
style: TextStyle(color: Colors.white),
),
),
),
Expanded(
child: SizedBox(
width: 130,
height: 50,
child: TextButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.white),
),
onPressed: () {},
child: Text(
'Daftar',
style: TextStyle(color: Colors.blue),
),),
),
),
],
),

var selectedButton = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Container(
margin: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
shape: BoxShape.rectangle,
border: Border.all(color: Colors.blue, width: 3)),
child: Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
shape: BoxShape.rectangle,
color: selectedButton == 0 ? Colors.blue : Colors.white),
child: TextButton(
onPressed: () {
setState(() {
selectedButton = 0;
});
},
style: TextButton.styleFrom(
primary: selectedButton == 0 ? Colors.white : Colors.blue,
),
child: Text(
'TextButton',
style: TextStyle(fontSize: 16),
),
),
)),
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
shape: BoxShape.rectangle,
color: selectedButton == 1 ? Colors.blue : Colors.white),
child: TextButton(
onPressed: () {
setState(() {
selectedButton = 1;
});
},
style: TextButton.styleFrom(
primary: selectedButton == 1 ? Colors.white : Colors.blue,
),
child: Text(
'TextButton',
style: TextStyle(fontSize: 16),
),
),
)),
],
),
),
),
);
}

Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
width: 260,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
SizedBox(
width: 130,
height: 50,
child: TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(
15,
),
),
),
),
),
onPressed: () {},
child: Text(
'Login',
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
width: 130,
height: 50,
child: TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
),
onPressed: () {},
child: Text(
'Daftar',
style: TextStyle(color: Colors.blue),
),
),
),
],
),
),
],
),
),

Related

Can we group or filter data inside our hive boxes

I use hive to store my data locally in expense tracker app. I have saved all expenses in a box called expenseBox. I have given each expense item a date and I want items with the same date to be grouped together and displayed separately. Is there a way to achieve this?
Thanks for your help!
BTW this is the code for my homescreen where I display the items.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter_locales/flutter_locales.dart';
import '/models/expense.dart';
import '/widgets/expense_list_tile.dart';
import '/screens/add_expense_screen.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
static const routeName = '/home_page';
#override
_HomeScreenState createState() => _HomeScreenState();
}
enum SlidableAction {
edit,
delete,
}
class _HomeScreenState extends State<HomeScreen> {
late Box expenseBox;
late Box pocketBox;
bool isFabVisible = true;
#override
void initState() {
expenseBox = Hive.box<Expense>('expenses');
pocketBox = Hive.box<int>('pocket');
super.initState();
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: Hive.box<int>('pocket').listenable(),
builder: (context, Box<int> pocketBox, child) => Scaffold(
appBar: AppBar(
title: const LocaleText('appName'),
elevation: 0,
centerTitle: true,
),
body: NestedScrollView(
headerSliverBuilder: (context, _) => [
SliverAppBar(
expandedHeight: MediaQuery.of(context).size.height * 0.15,
flexibleSpace: FlexibleSpaceBar(
background: Container(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: [
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const LocaleText(
'appName',
style: TextStyle(
fontSize: 14, color: Colors.white),
),
Text(
'${pocketBox.get('budget') ?? 0}',
style: const TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const LocaleText(
'income',
style: TextStyle(
fontSize: 14, color: Colors.white),
),
Text(
'${pocketBox.get('totalIncome') ?? 0}',
style: const TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const LocaleText(
'expense',
style: TextStyle(
fontSize: 14, color: Colors.white),
),
Text(
'${pocketBox.get('totalExpense') ?? 0}',
style: const TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
],
),
),
Expanded(child: Container()),
],
),
),
),
),
],
body: ValueListenableBuilder(
valueListenable: Hive.box<Expense>('expenses').listenable(),
builder: (context, Box<Expense> expensesBox, child) {
return NotificationListener<UserScrollNotification>(
onNotification: (notification) {
if (notification.direction == ScrollDirection.forward) {
if (!isFabVisible) setState(() => isFabVisible = true);
} else if (notification.direction ==
ScrollDirection.reverse) {
if (isFabVisible) setState(() => isFabVisible = false);
}
return true;
},
child: Scrollbar(
thickness: 5,
interactive: true,
child: ListView.separated(
separatorBuilder: (context, index) {
return const SizedBox();
},
itemCount: expenseBox.length,
itemBuilder: (context, index) {
final expense = expenseBox.getAt(index);
return ExpenseListTile(index: index, expense: expense);
},
),
),
);
},
),
),
floatingActionButton: isFabVisible
? FloatingActionButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => const AddExpenseScreen(
index: -1,
),
));
},
child: const Icon(Icons.add),
)
: null,
),
);
}
}
You can try this code.
import 'package:flutter/material.dart';
import 'package:sticky_grouped_list/sticky_grouped_list.dart';
class MyMissionList extends StatefulWidget {
#override
State<MyMissionList> createState() => _MyMissionListState();
}
class _MyMissionListState extends State<MyMissionList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(150.0),
child: Container(
decoration: BoxDecoration(
color: AppColors.baseLightBlueColor,
// AppColors.blue,
borderRadius: BorderRadius.only(bottomRight: Radius.circular(30)),
),
child: Material(
color: AppColors.baseLightBlueColor,
elevation: 15,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.only(bottomRight: Radius.circular(30)),
),
child: Column(
children: [
AppBar(
backgroundColor: AppColors.baseLightBlueColor,
elevation: 0.0,
actions: [
Container(
padding: EdgeInsets.only(right: 20),
child: Image.asset(
"assets/Vector-2.png",
height: 5,
width: 22,
color: Colors.white,
)),
],
),
Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 20),
margin: EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: AppColors.baseLightBlueColor,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Hello User123,",
style:
TextStyle(color: AppColors.white, fontSize: 15),
),
SizedBox(height: 10),
Text(
AppStrings.totalAmount,
// "Montant total :",
style:
TextStyle(color: AppColors.white, fontSize: 11),
),
Text(
"592,30 €",
style:
TextStyle(color: AppColors.white, fontSize: 25),
),
],
),
)
],
),
),
)),
body: Column(
children: [
Padding(
padding: const EdgeInsets.only(left:15.0,right: 15,top: 15),
child: Text("My Mission",style: TextStyle(
color: Color(0xff243656),
fontSize: 15,
fontWeight: FontWeight.w300),
),
),
Expanded(
child: StickyGroupedListView<Element, DateTime>(
elements: elements,
order: StickyGroupedListOrder.ASC,
groupBy: (Element element) =>
DateTime(element.date.year, element.date.month, element.date.day),
groupComparator: (DateTime value1, DateTime value2) =>
value2.compareTo(value1),
itemComparator: (Element element1, Element element2) =>
element1.date.compareTo(element2.date),
floatingHeader: false,
groupSeparatorBuilder: (Element element) => Container(
height: 50,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: 220,
padding: EdgeInsets.only(left: 20,top: 20,bottom: 10),
child: Text(
'${element.heading}',
textAlign: TextAlign.start,
style: TextStyle(color: Color(0xff919AAA)),
),
),
],
),
),
itemBuilder: (_, Element element) {
return element.type
? GestureDetector(
onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context)=> WaitingForValidation()));
},
child: Card(
elevation: 4,
margin: EdgeInsets.only(bottom: 15, right: 15, left: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Container(
height: 70,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: AppColors.white),
child: Row(
children: [
Container(
width: MediaQuery.of(context).size.width * 0.62,
height: 50,
padding: EdgeInsets.only(top: 10,left: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
element.subTitle +
'${element.date.day}/${element.date.month}/'
'${element.date.year}',
style: TextStyle(
//color:AppColors.grey
color: Color(0xff919AAA),
fontSize: 12,
fontWeight: FontWeight.w300),
),
SizedBox(height: 2,),
Text(
element.hotelName,
style: TextStyle(
//color:AppColors.grey
color: Color(0xff243656),
fontSize: 15,
fontWeight: FontWeight.w300),
),
],
),
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Card(
elevation: 15.0,
shadowColor: Colors.blue[100],
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20.0))),
child: Container(
height: 30,
width: 80,
decoration: BoxDecoration(
// boxShadow: [BoxShadow(color: AppColors.grey, blurRadius: 20.0)],
borderRadius:
BorderRadius.circular(20.0),
gradient: LinearGradient(
colors: [
Colors.blue,
Colors.blue.shade900,
],
)),
child: MaterialButton(
onPressed: () {},
child: Text(
element.buttonText,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
),
),
),
],
),
),
),
)
: Card(
elevation: 4,
margin: EdgeInsets.only(bottom: 15, right: 15, left: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Container(
height: 70,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: AppColors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: MediaQuery.of(context).size.width * 0.62,
height: 50,
padding: EdgeInsets.only(top: 10,left: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
element.subTitle +
'${element.date.day}/${element.date.month}/'
'${element.date.year}',
style: TextStyle(
//color:AppColors.grey
color: Color(0xff919AAA),
fontSize: 12,
fontWeight: FontWeight.w300),
),
SizedBox(height: 2,),
Text(
element.hotelName,
style: TextStyle(
//color:AppColors.grey
color: Color(0xff243656),
fontSize: 15,
fontWeight: FontWeight.w300),
),
],
),
),
Padding(
padding: const EdgeInsets.only(top:5.0,bottom: 5),
child: Container(
height: 30,
width: 95,
child: MaterialButton(
onPressed: () {},
child: Text(
element.buttonText,
style: TextStyle(
color: AppColors.green,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
),
)
],
),
),
);
},
),
),
],
),
);
}
}
class Element {
bool type;
DateTime date;
String hotelName;
String subTitle;
String heading;
String buttonText;
Element(this.date, this.type, this.hotelName, this.subTitle, this.heading,
this.buttonText);
}
List<Element> elements = <Element>[
Element(
DateTime(2020, 7, 22),
false,
"Rendez-vous equipe prod",
"Jeudi",
"Terminate",
"Terminate",
),
Element(
DateTime(2021, 10, 15),
false,
"Rendez-vous equipe prod",
"Jeudi",
"Terminate",
"Terminate",
),
Element(
DateTime(2021, 10, 15),
false,
"Rendez-vous equipe prod",
"Jeudi",
"Terminate",
/**/
"Terminate",
),
Element(
DateTime(2021, 12, 12),
true,
"Visite entrepot Villabe ",
"Mercredi",
"To Plan",
"To Plan",
),
];

How to add vertical spacing to widgets Flutter

I have a piece of code here which makes up the body of the login and register screens. Everything is in the position i want but i would like to space them out a little. The two input fields, title, subtitle, button and textbutton are too close together vertically.
I tried to use mainaxisalignment.spacebetween but i get a constraint error and everything i have on the screen disappears afterwards except the background.
The body used by the register and login screen:
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomLeft,
colors: [Color(0xFF1F1F1F), Color(0xFF1F1F1F)],
),
image: DecorationImage(
image: AssetImage("lib/assets/images/register.png"),
alignment: Alignment.topCenter,
),
),
child: Stack(
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('lib/assets/images/bottomleft.png'),
alignment: Alignment.bottomLeft,
),
),
),
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('lib/assets/images/toptop.png'),
alignment: Alignment.topRight,
),
),
),
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('lib/assets/images/topbig.png'),
alignment: Alignment.topCenter,
repeat: ImageRepeat.repeat),
),
),
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('lib/assets/images/top.png'),
alignment: Alignment.topCenter,
repeat: ImageRepeat.repeatX),
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 25, vertical: 250),
child: ListView(
children: [
if (onBackPressed == null) verticalSpaceLarge,
if (onBackPressed != null) verticalSpaceRegular,
if (onBackPressed != null)
IconButton(
padding: EdgeInsets.zero,
onPressed: onBackPressed,
alignment: Alignment.centerLeft,
icon: Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
),
Center(
child: Text(
title!,
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.bold,
fontFamily: 'Montserrat',
),
),
),
Align(
alignment: Alignment.center,
child: SizedBox(
child: Center(
child: Text(
subtitle!,
style: ktsMediumGreyBodyText,
),
),
),
),
form!,
if (onForgotPassword != null)
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: onForgotPassword,
child: Center(
child: Text(
'Forgot Password?',
style: ktsMediumGreyBodyText.copyWith(),
),
),
),
),
if (validationMessage != null)
Center(
child: Text(
validationMessage!,
style: TextStyle(
color: Colors.red, fontSize: kBodyTextSize),
),
),
if (validationMessage != null) verticalSpaceRegular,
GestureDetector(
onTap: onMainButtonTapped,
child: Container(
width: double.infinity,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
color: kcPrimaryColor,
borderRadius: BorderRadius.circular(8),
),
child: busy!
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.white),
)
: Text(
mainButtonTitle!,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
),
),
if (onCreateAccountTapped != null)
GestureDetector(
onTap: onCreateAccountTapped,
child: Center(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Don\'t have an account?",
style: TextStyle(color: Colors.white),
),
Text(
"SIGN UP",
style: TextStyle(color: kcPrimaryColor),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"OR SIGN IN WITH",
style: TextStyle(color: kcMediumGreyColor),
),
],
),
],
),
),
),
if (showTermsText!)
Center(
child: Text(
"By signing up you agree to our terms, conditions and privacy policy",
style: ktsMediumGreyBodyText,
textAlign: TextAlign.center,
),
),
],
),
),
],
),
),
);
}
}
the login screen:
Widget build(BuildContext context) {
return ViewModelBuilder<LoginScreenModel>.reactive(
builder: (context, model, child) => Scaffold(
body: AuthenticationLayout(
busy: model.isBusy,
onCreateAccountTapped: () {},
//validationMessage: model.validationMessage,
title: 'SIGN IN',
subtitle: 'please fill the form below',
mainButtonTitle: 'SIGN IN',
form: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: 'Username',
hintStyle: TextStyle(color: Colors.white),
prefixIcon: const Icon(
Icons.person,
color: Colors.white,
),
),
),
TextField(
decoration: InputDecoration(
hintText: 'Password',
hintStyle: TextStyle(color: Colors.white),
prefixIcon: const Icon(
Icons.lock,
color: Colors.white,
),
),
),
],
),
onForgotPassword: () {},
),
),
viewModelBuilder: () => LoginScreenModel(),
);
}
}
Column(
children: <Widget>[
FirstWidget(),
SizedBox(height: 100),
SecondWidget(),
],
),
You should Add SizedBox() in between two Widgets, or Set Padding to your widgets or you use Container also like below:
Using SizedBox()
Column(
children:[
Widget 1(),
SizedBox(height:10),
Widget 2(),
SizedBox(height:10),
Widget 3(),
],
),
Using Padding()
Column(
children:[
Padding(
padding:EdgeInsets.all(8.0)
child: Widget 1(),
),
Padding(
padding:EdgeInsets.all(8.0)
child: Widget 2(),
),
Padding(
padding:EdgeInsets.all(8.0)
child: Widget 3(),
),
],
),
Using Container()
Column(
children:[
Container(
padding:EdgeInsets.all(8.0)
child: Widget 1(),
),
Container(
padding:EdgeInsets.all(8.0)
child: Widget 2(),
),
Container(
padding:EdgeInsets.all(8.0)
child: Widget 3(),
),
],
),
You should use padding on your choice like:
EdgeInsets.all(8.0),
EdgeInsets.only(left:8.0,top:8.0,right:8.0,bottom:8.0),
EdgeInsets.symmetric(vertical: 8.0,horizontal:8.0),
You may add some SizedBox() between or set margin to the components.
Use SizedBox widget to add vertical spacing to your widget.
For e.g
SizedBox(height: 16),

How to add multiple images on top of the background image

I have a piece of code here which makes up the body of the login and register screens. I added an image at the very top but my question is how do i add multiple images for the body?
I have some images i want to add in different positions for blur effects but whenever do either nothing shows up or gives me an error about the constraints.
When i add multiple containers with a single image in each one, i get the constraint error.
Everything was added in pubspec.yaml and in the folders correctly.
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomLeft,
colors: [Color(0xFF1F1F1F), Color(0xFF1F1F1F)],
),
image: DecorationImage(
image: AssetImage("lib/assets/images/register.png"),
alignment: Alignment.topCenter,
//fit: BoxFit.cover,
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 250),
child: ListView(
children: [
if (onBackPressed == null) verticalSpaceLarge,
if (onBackPressed != null) verticalSpaceRegular,
if (onBackPressed != null)
IconButton(
padding: EdgeInsets.zero,
onPressed: onBackPressed,
alignment: Alignment.centerLeft,
icon: Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
),
Center(
child: Text(
title!,
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.bold,
fontFamily: 'Montserrat',
),
),
),
verticalSpaceSmall,
SizedBox(
child: Center(
child: Text(
subtitle!,
style: ktsMediumGreyBodyText,
),
),
),
verticalSpaceRegular,
form!,
if (onForgotPassword != null)
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: onForgotPassword,
child: Center(
child: Text(
'Forgot Password?',
style: ktsMediumGreyBodyText.copyWith(),
),
),
),
),
verticalSpaceRegular,
if (validationMessage != null)
Center(
child: Text(
validationMessage!,
style:
TextStyle(color: Colors.red, fontSize: kBodyTextSize),
),
),
if (validationMessage != null) verticalSpaceRegular,
GestureDetector(
onTap: onMainButtonTapped,
child: Container(
width: double.infinity,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
color: kcPrimaryColor,
borderRadius: BorderRadius.circular(8),
),
child: busy!
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.white),
)
: Text(
mainButtonTitle!,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
),
),
verticalSpaceRegular,
if (onCreateAccountTapped != null)
GestureDetector(
onTap: onCreateAccountTapped,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
verticalSpaceMedium,
Text(
"Don\'t have an account?",
style: TextStyle(color: Colors.white),
),
horizontalSpaceTiny,
Text(
"SIGN UP",
style: TextStyle(color: kcPrimaryColor),
),
],
),
),
),
if (showTermsText!)
Center(
child: Text(
"By signing up you agree to our terms, conditions and privacy policy",
style: ktsMediumGreyBodyText,
textAlign: TextAlign.center,
),
),
],
),
),
),
);
}
}

how to check if my cloud firestore collection contains contains any documents

I am trying to check if my firestore collection "payments" contains any documents where the string userActive is contained in any document field array called participants,and if it doesn't perform an action or if it does perform a different action, this is what i have tried so far but its not working
import 'package:flutter/material.dart';
import 'package:wallet_app/send.dart';
import 'package:wallet_app/send_money.dart';
import 'package:wallet_app/recieve.dart';
import 'package:wallet_app/load.dart';
import 'package:wallet_app/account.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:wallet_app/CardScreen.dart';
import 'package:flutter_icons/flutter_icons.dart';
class HomeScreener extends StatefulWidget{
HomeScreen createState()=> HomeScreen();
}
class HomeScreen extends State<HomeScreener> {
HomeScreen createState() => HomeScreen();
final databaseReference = FirebaseFirestore.instance;
var userId = "dAIdrQggsrxvQ4KUo2aJ";
var userActive = "kim";
var userHasData = 0;
checkDatabase()async {
final docSnapshot = await FirebaseFirestore.instance
.collection('payments')
.where('participants', arrayContains: userActive)
.getDocuments();
if(docSnapshot.documents.isEmpty) {
// Your queried documents do not exist
userHasData = 1;
}
else if(docSnapshot.documents.isEmpty){
// Your queried documents do not exist
}
userHasData = 2;
}
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: double.infinity,
child: Stack(
children: <Widget>[
//Container for top data
Container(
margin: EdgeInsets.symmetric(horizontal: 32, vertical: 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Hello " + "$userActive", style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w700),),
Container(
margin: EdgeInsets.only(top: 20),
child: Row(
children: <Widget>[
// Icon(Icons.notifications, color: Colors.lightBlue[100],),
SizedBox(width: 16,),
CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
child: ClipOval(
child: Image.asset("assets/newdp.png", fit: BoxFit.contain,),
),
)
],
),
)
],
),
Text("What would you like to do today?", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16, color: Colors.blue[100]),),
SizedBox(height : 40,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.send, color: Colors.blue[900], size: 30,),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => sendPager()),
);
},
),
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Send", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.account_balance, color: Colors.blue[900], size: 30,),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},
),
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Account", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.people, color: Colors.blue[900], size: 30,),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},
),
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Recipients", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.add, color: Colors.blue[900], size: 30,),
onPressed: () {
databaseReference.collection("payments").add(
{
"amount_paid" : "2444242",
"amount_received" : "33535",
"currency_received" : "¥",
"currency_sent" :"K",
'date':FieldValue.serverTimestamp(),
"participants" :["kim", "john" ],
"receiver_name" : "john",
"sender_name" : "kim"
}).then((value){
print("================================sucess=============================================================");
print(value.documentID);
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},
),
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Invite", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
)
],
)
],
),
),
//draggable sheet
DraggableScrollableSheet(
builder: (context, scrollController){
return Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.only(topLeft: Radius.circular(40), topRight: Radius.circular(40))
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 24,),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Recent Transactions", style: TextStyle(fontWeight: FontWeight.w900, fontSize: 24, color: Colors.black),),
Text("See all", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16, color: Colors.grey[800]),)
],
),
padding: EdgeInsets.symmetric(horizontal: 32),
),
SizedBox(height: 24,),
//Container for buttons
Container(
padding: EdgeInsets.symmetric(horizontal: 32),
child: Row(
children: <Widget>[
Container(
child: Text("All", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
SizedBox(width: 16,),
Container(
child: Row(
children: <Widget>[
CircleAvatar(
radius: 8,
backgroundColor: Colors.green,
),
SizedBox(
width: 8,
),
Text("Recieved", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
SizedBox(width: 16,),
Container(
child: Row(
children: <Widget>[
CircleAvatar(
radius: 8,
backgroundColor: Colors.orange,
),
SizedBox(
width: 8,
),
Text("Transfer", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
)
],
),
),
SizedBox(height: 16,),
//Container Listview for expenses and incomes
Container(
child: Text(" ", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
padding: EdgeInsets.symmetric(horizontal: 32),
),
SizedBox(height: 5),
StreamBuilder(
stream: FirebaseFirestore.instance.collection("payments").where('participants', arrayContains: userActive).snapshots(),
builder: (context, snapshot){
checkDatabase();
return Container ( child:ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
padding: EdgeInsets.all(0),
controller: ScrollController(keepScrollOffset: false),
itemBuilder: (context, index){
DocumentSnapshot documentSnapshot = snapshot.data.docs[index];
//if(snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
if(userHasData == 1){
print(" no Data!!!");
return Center(child: Text("No Data"));
}
else if (userHasData == 2){
print("Found Data!!!");
if(documentSnapshot.data()["receiver_name"] == userActive ) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))
),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.all(Radius.circular(18))
),
child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
padding: EdgeInsets.all(12),
),
SizedBox(width: 16,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Recieved", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,
Text("" + documentSnapshot.data()["currency_received"] + documentSnapshot.data()["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text("+ " + documentSnapshot.data()["currency_sent"] + documentSnapshot.data()["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.lightGreen),),
Text(documentSnapshot.data()["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
],
),
],
),
);
}else if (documentSnapshot.data()["sender_name"] == userActive){
return Container(
margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))
),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.all(Radius.circular(18))
),
child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
padding: EdgeInsets.all(12),
),
SizedBox(width: 16,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Sent", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,
Text("" + documentSnapshot.data()["currency_received"] + documentSnapshot.data()["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text("- " + documentSnapshot.data()["currency_sent"] + documentSnapshot.data()["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.orange),),
Text(documentSnapshot.data()["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
],
),
],
),
);
}
}
// } return Center(child: const CircularProgressIndicator());
}
)
);
}
),
],
),
controller: scrollController,
),
);
},
initialChildSize: 0.65,
minChildSize: 0.65,
maxChildSize: 1,
)
],
),
);
}
}
Try using .exists :
final docSnapshot = await Firestore.instance.collection('payments').document("document_id").get();
if (docSnapshot.exists){
//document exists
}
else{
//document does not exists
}
for all documents:
final doc = await Firestore.instance.collection('payments').getDocuments();
if (doc.documents.isEmpty){
//Collection is empty
}
else{
//collection has documents
}
You can apply the logic before using it in the element, like on start of the class then use futureBuilder. You can set a bool using the above logic and then using the visibility widget to show the futureBuilder only if the document is available.
For your case:
final docSnapshot = await Firestore.instance
.collection('bus_information_user')
.where('participants', arrayContains: userActive)
.getDocuments();
if(docSnapshot.documents.isEmpty){
// Your queried dosuments does not exist
}
else{
// Your queried dosuments does exist
}
Ps:. I have not tried out the last part but should do the job.

Flutter Form: The method 'validate' was called on null. [All configurations are already configured]

please help me! I am creating simple login page but I got an exception look like this:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY╞════════════════ [+3s]
I/flutter (11275): The following NoSuchMethodError was thrown
building LoginScreen(dirty, dependencies: [MediaQuery]): [ ]
I/flutter (11275): The method 'validate' was called on null. [
] I/flutter (11275): Receiver: null [ ] I/flutter (11275):
Tried calling: validate() [ ] I/flutter (11275): [ ]
I/flutter (11275): The relevant error-causing widget was: [ ]
I/flutter (11275): LoginScreen
Although I think, I already configured all need configures. But somehow, My code thrown exception. How to fix it?
Here is my code:
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:my_app/services/UserService.dart';
/*
* This is login screen view.
*
* If you want to edit form section for example email and password fields, just edit these below functions.
* - _formEmailWidget()
* - _formPasswordWidget()
* If you want to edit social login section, just edit _socialLoginWidget() function.
* If you want to edit or change logo, just edit _logoWidget() function.
*/
class LoginScreen extends StatelessWidget {
static final Pattern _pattern =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
final GlobalKey<FormState> _key = GlobalKey<FormState>();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final UserAuth _auth = UserAuth.instance();
final Status status;
LoginScreen({#required this.status});
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: SafeArea(child: this._bodyWidgets(context)));
}
_logoWidget() {
return Padding(
padding: const EdgeInsets.only(top: 15.0, bottom: 50.0),
child: Image(image: AssetImage('assets/images/logo.png')));
}
_formEmailWidget() {
return Container(
decoration: BoxDecoration(
border:
Border(bottom: BorderSide(color: Colors.white, width: 1.0))),
child: TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
validator: (String value) {
RegExp regex = new RegExp(_pattern);
if (regex.hasMatch(value)) {
return null;
}
return "Please, Enter valid e-mail";
},
decoration: const InputDecoration(
icon: Icon(
FontAwesome.user,
color: Colors.white,
),
fillColor: Colors.white,
hintStyle: TextStyle(
color: Colors.white,
fontFamily: 'ProximaThin',
),
hintText: 'Your e-mail'),
));
}
_formPasswordWidget() {
return Container(
decoration: BoxDecoration(
border:
Border(bottom: BorderSide(color: Colors.white, width: 1.0))),
child: TextFormField(
controller: _passwordController,
validator: (String value) {
if (value.isEmpty || value.length < 6) {
return "Password must be more than 6 characters";
}
return null;
},
decoration: const InputDecoration(
icon: Icon(
FontAwesome.key,
color: Colors.white,
),
fillColor: Colors.white,
hintStyle: TextStyle(
color: Colors.white,
fontFamily: 'ProximaThin',
),
hintText: 'Your password'),
obscureText: true,
));
}
_submitRowWidget() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: null,
child: Text(
'forget password?',
style: TextStyle(color: Colors.white),
),
),
OutlineButton(
textColor: Colors.white,
highlightedBorderColor: Colors.white,
borderSide: BorderSide(
color: Colors.white, width: 0.8, style: BorderStyle.solid),
shape: OutlineInputBorder(borderRadius: BorderRadius.circular(10.0)),
onPressed: _loginAction(),
child: Text(
'Login',
style: TextStyle(color: Colors.white),
),
)
],
);
}
_loginAction() {
if (_key.currentState.validate()) {
_auth.signIn(_emailController.text, _passwordController.text);
} else {
AlertDialog(
content: Text(
"Your e-mail or password doesn't match, Would you like create an account?"),
elevation: 24.0,
shape: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
actions: <Widget>[
FlatButton(
onPressed: null,
child: Text("Yes"),
)
],
);
}
}
_socialLoginWidget() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: FlatButton(
padding: const EdgeInsets.only(
left: 10.0, top: 0.0, bottom: 0.0, right: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(FontAwesome.facebook_f, color: Colors.black),
SizedBox(
width: 10,
),
Text('Facebook',
style: TextStyle(
fontFamily: 'Proxima',
fontSize: 11,
color: Colors.black))
],
),
onPressed: null,
),
),
Container(
width: 100,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: FlatButton(
padding: const EdgeInsets.only(
left: 10.0, top: 0.0, bottom: 0.0, right: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(
FontAwesome.google,
color: Colors.black,
),
SizedBox(
width: 10,
),
Text(
'Google',
style: TextStyle(
fontFamily: 'Proxima', fontSize: 11, color: Colors.black),
)
],
),
onPressed: null,
),
)
],
);
}
_bodyWidgets(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_logoWidget(),
Expanded(
child: Center(
child: Container(
width: MediaQuery.of(context).size.width - 20,
decoration: BoxDecoration(
color: Colors.black,
boxShadow: [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, 0.35),
blurRadius: 15.0,
offset: Offset(0, -5))
],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30))),
child: Padding(
padding:
const EdgeInsets.only(top: 45.0, left: 45.0, right: 45.0),
child: Column(children: <Widget>[
Form(
key: this._key,
child: Column(
children: <Widget>[
_formEmailWidget(),
_formPasswordWidget(),
SizedBox(
height: 15.0,
),
_submitRowWidget()
],
),
),
SizedBox(
height: 45,
),
Text('or connect using',
style: TextStyle(
fontFamily: 'ProximaThin', color: Colors.white)),
SizedBox(
height: 15,
),
_socialLoginWidget(),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Don\'t have an account?',
style: TextStyle(
fontFamily: 'ProximaThin', color: Colors.white),
),
SizedBox(
width: 5,
),
InkWell(
onTap: null,
child: Text('Sign up',
style: TextStyle(
fontFamily: 'Proxima', color: Colors.white)),
)
],
)
]),
),
),
))
]);
}
}
You have two options here:
change bellow method OnPressed: _loginAction(), to OnPressed: _loginAction,
or change the same line to OnPressed: () { _loginAction(); },
fixed code bellow:
_submitRowWidget() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: null,
child: Text(
'forget password?',
style: TextStyle(color: Colors.white),
),
),
OutlineButton(
textColor: Colors.white,
highlightedBorderColor: Colors.white,
borderSide: BorderSide(
color: Colors.white, width: 0.8, style: BorderStyle.solid),
shape: OutlineInputBorder(borderRadius: BorderRadius.circular(10.0)),
onPressed: _loginAction,
child: Text(
'Login',
style: TextStyle(color: Colors.white),
),
)
],
);
}

Categories

Resources