Display a widget if the user is an admin flutter - flutter

I have a "settings" screen where the user can click on "Admin mode" and then is asked for a password. If this password corresponds to a defined password that I'll give to the admins of the app, he has the app displaying all the admin widgets on the other screens.
I want to set a default admin password, when the user click on the "validate" button, the program check is the password is correct. I have a button on a screen that is like the "admin panel" and I want this button to be displayed only if the user is an admin.
Here is the Dialog I created and where I suppose I'll have to create something to check if the password is correct in the onPressed function.
class DialogModeAdmin extends StatelessWidget {
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
String _passAdmin;
dialogContent(BuildContext context) {
return Container(
decoration: new BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10.0,
offset: const Offset(0.0, 10.0),
),
],
),
child: SizedBox(
height: 120,
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text("Mot de passe"),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: new BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.black,
width: 1,
),
boxShadow: [BoxShadow(
color: Color.fromRGBO(10, 10, 10, 0.25),
blurRadius: 5.0,
spreadRadius: -2.0,
offset: Offset(3.0, 5.0),
)],
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
child: SizedBox(
height: 30,
child: Padding(
padding: const EdgeInsets.only(left: 5.0, right: 5.0, top: 1.0, bottom: 4.0),
child: FormBuilderTextField(
// validator: FormBuilderValidators.required(context),
decoration: InputDecoration(
border: InputBorder.none,
),
name: 'passadmin',
onChanged: (String value) {
_passAdmin = value;
},
),
)
)
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: SizedBox(
height: 30,
width: 90,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color.fromRGBO(255, 64, 0, 1.0),
onPrimary: Colors.white,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
),
onPressed: () async{
if(_fbKey.currentState.validate()){
// check if the password is correct and then set a local variable to true to set the privileges of an admin
}
},
child: Text('Valider'),
),
),
),
],
)
)
);
}
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 0.0,
backgroundColor: Colors.transparent,
child: dialogContent(context),
);
}
}

You can store a isAdmin boolean in a static way or with ChangeNotifier (similar to observable).
https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple
https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html
Then use this value to show/hide your widgets with the Visibility Widget
https://api.flutter.dev/flutter/widgets/Visibility-class.html
Visibility(
visible: // isAdmin variable,
child: ...
),
EDIT : For your problem to check the password :
class DialogModeAdmin extends StatelessWidget {
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
String _passAdmin;
// This is your password
final String _password = "MyPassword";
dialogContent(BuildContext context) {
...
name: 'passadmin',
// Here you store correctly what the user typed
onChanged: (String value) {
_passAdmin = value;
},
),
...
child: ElevatedButton(
...
onPressed: () async{
if(_fbKey.currentState.validate()){
// check if the password is correct and then set a local variable to true to set the privileges of an admin
// As the comment says :
if(_passAdmin == _password){
// set the static/valueNotifier to true
} else {
// display an error 'wrong password'
}
}
},
child: Text('Valider'),
),
...
}

Related

how to display input value from text field to other pages?

I'm trying to display the input value below onto another page that contains radio buttons . my aim is that every time i write or change a value in a textfield it gets updated and displays onto a different page with the radio options . The snippet of code below is for the textfield - i used riverpod to connect it to firestore:
class AddMealPage extends ConsumerWidget {
const AddMealPage({Key? key}) : super(key: key);
static const String route = "/addMeal";
#override
Widget build(BuildContext context, WidgetRef ref) {
final model = ref.read(addMealProvider);
return LoadingLayer(
child: Scaffold(
appBar: AppBar(
elevation: 0,
iconTheme: const IconThemeData(
color: Colors.black,
),
title: const Text(
"Create Meal",
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
backgroundColor: Colors.white,
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: MaterialButton(
padding: const EdgeInsets.all(16),
color: Colors.black,
onPressed: model.enabled
? () async {
try {
await model.writeMeal();
Navigator.pop(context);
} catch (e) {
AppSnackbar(context).error(e);
}
}
: null,
child: const Text(
"Add meal",
style: TextStyle(color: Color.fromARGB(255, 247, 245, 245)),
),
),
),
body: SingleChildScrollView(
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 60.0, horizontal: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () async {
final picked = await ImagePicker()
.pickImage(source: ImageSource.gallery);
if (picked != null) {
model.file = File(picked.path);
}
},
child: Container(
margin: const EdgeInsets.only(),
width: MediaQuery.of(context).size.width,
height: 210.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: (model.mealUrl != null || model.file != null)
? DecorationImage(
image: model.file != null
? FileImage(model.file!)
: NetworkImage(model.mealUrl!)
as ImageProvider,
fit: BoxFit.cover,
)
: null),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (model.mealUrl == null && model.file == null)
const Expanded(
child: Center(
child: Icon(
Icons.photo,
),
),
),
const Material(
color: Colors.transparent,
child: Padding(
padding: EdgeInsets.all(8.0),
),
),
],
),
),
),
const SizedBox(
height: 10,
),
const Padding(
padding: EdgeInsets.only(left: 15.0),
child: Text(
"Meal Name",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
),
),
Container(
height: 50,
padding: const EdgeInsets.only(top: 10),
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.symmetric(horizontal: 20),
child: TextFormField(
textInputAction: TextInputAction.done,
initialValue: model.mealName,
maxLines: 1,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.grey),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(color: Colors.grey),
),
),
onChanged: (v) => model.mealName = v,
),
),
I want to display the input value i get from the textfield above in the format of a radioButton on a seperate page :
enum Variant { mealName }
class RadioOption extends StatefulWidget {
const RadioOption({Key? key}) : super(key: key);
#override
State<RadioOption> createState() => _RadioOptionState();
}
class _RadioOptionState extends State<RadioOption> {
Variant? _character = Variant.mealName;
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RadioListTile<Variant>(
title: const Text('$mealName'),
value: Variant.MealName,
groupValue: _character,
onChanged: (Variant? value) {
setState(() {
_character = value;
});
},
),
I don't see the whole architecture of the app. But if you want to transfer model.mealName, you can make String value (mealName) in your RadioOption, and pass it through the constructor:
final mealName;
RadioOption({required this.mealName});
And then access it in _RadioOptionState by:
title: const Text(widget.mealName);
You can use TextEditingController and add this controller to your TextFormField which have controller properties but you can't use initialValue and controller both so avoid initialValue. To put value you can use controller.text = your_value;
You value will be filled in text field.
To get value from TextFormField Use var newValue = controller.text; and send this newValue to another page in constructor.

Can't reduce size of an elevated button

I am trying to reproduce Apple memo recorder button. Right now, I am trying to reduce the size of Stop Button. First, I have tried without the SizedBox and then with. I am getting the same result.Even if embedded in a SizedBox, I can not achieve what I want.
Please, can somebody tells me what I am missing? Thank you.
Container _RecordButton(){
return Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false?
_createRecordElevatedButton() : _createStopElevatedButton()),);
}
ElevatedButton _createRecordElevatedButton(
{IconData icon, Function onPressFunc}) {
return ElevatedButton(
onPressed: () {
if (isRecording = false){
setState(() {
isRecording = true;
});
}},
style: ButtonStyle(
shape: MaterialStateProperty.all(CircleBorder()),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/));
}
SizedBox _createStopElevatedButton(
{IconData icon, Function onPressFunc}) {
return SizedBox(
height: 14,
width: 14,
child: ElevatedButton(
onPressed: () {
/* if (isRecording = true){
setState(() {
isRecording = false;
});
}*/
},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10,10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
side: BorderSide(color: Colors.red)
)
),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/)),
);
}
Wrap your elevated button with container and give height and width accordingly.
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.grey)),
child: Container(
padding: EdgeInsets.all(7),
width: 50.0,
height: 50.0,
child: ElevatedButton(
onPressed: () {},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10, 10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(color: Colors.red))),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red),
),
child: null,
)),
),
Please replace your code with below code:
class MyElevatedButton extends StatefulWidget {
const MyElevatedButton({Key? key}) : super(key: key);
#override
_MyElevatedButtonState createState() => _MyElevatedButtonState();
}
class _MyElevatedButtonState extends State<MyElevatedButton> {
bool isRecording=false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton(icon: Icons.add)
: _createStopElevatedButton(icon: Icons.minimize,onPressFunc: (){})),
),
],
),
),
),
);
}
/* Container _RecordButton() {
return Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton()
: _createStopElevatedButton()),
);
}*/
Widget _createRecordElevatedButton(
// ignore: unused_element
{required IconData icon,/* VoidCallback onPressFunc*/}) {
return ElevatedButton(
onPressed: () {
if (isRecording = false) {
setState(() {
isRecording = true;
});
}
},
style: ButtonStyle(
shape: MaterialStateProperty.all(CircleBorder()),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor:
MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/
), child: Text('play'),);
}
// ignore: unused_element
SizedBox _createStopElevatedButton({required IconData icon, required VoidCallback onPressFunc}) {
return SizedBox(
height: 14,
width: 14,
child: ElevatedButton(
onPressed: () {
/* if (isRecording = true){
setState(() {
isRecording = false;
});
}*/
},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10, 10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
side: BorderSide(color: Colors.red))),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor:
MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/
), child: Text('onPressed'),),
);
}
}
Try this code :
MyElevatedButton
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class MyElevatedButton extends StatefulWidget {
const MyElevatedButton({Key? key}) : super(key: key);
#override
_MyElevatedButtonState createState() => _MyElevatedButtonState();
}
class _MyElevatedButtonState extends State<MyElevatedButton> {
bool isRecording=false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton() /*_createRecordElevatedButton(icon: Icons.add,)*/
: _createStopElevatedButton()),
),
],
),
),
),
);
}
Widget _createRecordElevatedButton(){
return GestureDetector(
onTap: (){
setState(() {
isRecording = true;
});
print('clickOnPressedButton');
},
child: Container(
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(child: Text('Play',style: TextStyle(fontSize: 12,color: Colors.white),)),
),
);
}
Widget _createStopElevatedButton(){
return GestureDetector(
onTap: (){
setState(() {
isRecording = false;
});
print('clickOnPressedButton');
},
child: Container(
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(child: Text('Pause',style: TextStyle(fontSize: 12,color: Colors.white),)),
),
);
}
}

I want to implement OTP verification screen without any package

I want to implement OTP verification screen without any package.
when i entered the number it should move to next input field
I m using this code in my current project take a refrence this will help
class Otp extends StatefulWidget {
final String? phnNumber;
final String ? code;
String? from;
Otp({Key ?key, this.phnNumber, this.from, this.code}) : super(key:
key);
#override
_OtpState createState() => _OtpState();
}
class _OtpState extends State<Otp> {
double ? height ;
double ? width;
TextEditingController ? contrller1;
TextEditingController ? contrller2;
TextEditingController ? contrller3;
TextEditingController ? contrller4;
SendOtpRequest resend = SendOtpRequest();
SharedPreferences ? prefs;
getSharedPreferences () async
{
prefs = await SharedPreferences.getInstance();
}
String Code = "";
#override
void initState() {
// TODO: implement initState
super.initState();
contrller1 = TextEditingController();
contrller2 = TextEditingController();
contrller3 = TextEditingController();
contrller4 = TextEditingController();
getSharedPreferences();
}
#override
Widget build(BuildContext context) {
height= MediaQuery.of(context).size.height;
width = MediaQuery.of(context).size.height;
final verifyprovider = Provider.of<PostDataProvider>(context);
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
toolbarHeight:height! * 0.07802345,
titleSpacing: 0,
backgroundColor: HexColor("#18263d"),
automaticallyImplyLeading: false,
leading: Padding(
padding: const EdgeInsets.only(left: 8.0,),
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Container(
color: Colors.transparent,
child: Image.asset("assets/images/back_ic-1.png")),
),
),
// SizedBox(width: width!*0.001234,),
title:Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: height!/15,
width: height!/15,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
width: 2,
color:HexColor("#fc4f00"),
)),
child: Padding(
padding: const EdgeInsets.all(1.0),
child: Container(
height: height!/11,
width: height!/11,
decoration: BoxDecoration(
image: const DecorationImage(
image:
AssetImage("assets/images/home_logo.png"),
fit: BoxFit.fill
),
shape: BoxShape.circle,
border: Border.all(
width: 1,
color:HexColor("#fc4f00"),
)),
),
),
),
SizedBox(width: width! * 0.04234,),
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text("Verification",
style: GoogleFonts.oswald(fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: width! * 0.03345
),),
),
],
) ,
),
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 24, horizontal: 32),
child: Column(
children: [
Text("We have send verification code on your mobile number",
style: GoogleFonts.oswald(fontStyle: FontStyle.normal,
fontSize: width!*0.0234,
color: HexColor("#8b8b8b")),
),
SizedBox(height: height!/38,),
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_textFieldOTP(first: true, last: false,controllerr:
contrller1),
_textFieldOTP(first: false, last: false,controllerr:
contrller2),
_textFieldOTP(first: false, last: false,controllerr:
contrller3),
_textFieldOTP(first: false, last: true, controllerr:
contrller4),
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap:() {
resend.phoneNumber= widget.phnNumber;
resend.countryCode = widget.code;
verifyprovider.resendOtp(context,
jsonEncode(resend));
},
child: Text("Resend OTP?",
style: GoogleFonts.oswald(fontStyle:
FontStyle.normal,
fontSize: width!*0.0234,
color: HexColor("#fc4f00")),
),
),
),
SizedBox(height: height!/28,),
GestureDetector(
onTap: (){
if(contrller1!.text.isNotEmpty&&
contrller2!.text.isNotEmpty&&contrller3!.
text.isNotEmpty&&contrller4!.text.isNotEmpty){
verifyOtpRequest verify = verifyOtpRequest();
verify.phoneNumber = widget.phnNumber;
verify.otp=
contrller1!.text+contrller2!.
text+contrller3!.text+contrller4!.text;
verifyprovider.otpVerification(context,
jsonEncode(verify), widget.from);
}else{
CommonUtils.showToast(msg: "Please fill all the
fields ");
}
},
child: Container(
height: height!/18,
width: width,
decoration: BoxDecoration(
color: HexColor("#fc4f00"),
borderRadius: BorderRadius.circular(10)
),
child: Center(
child: Text("Verify",style: TextStyle(
color: Colors.white,
fontSize: width!*0.02345
),),
)
),
),
],
),
],
),
),
),
);
}
Widget _textFieldOTP({bool ? first, last,
TextEditingController ?
controllerr}) {
return Container(
height:height!/12 ,
child: AspectRatio(
aspectRatio: 1.0,
child: TextField(
controller: controllerr,
autofocus: true,
onChanged: (value) {
if (value.length == 1 && last == false) {
FocusScope.of(context).nextFocus();
}
if (value.length == 0 && first == false) {
FocusScope.of(context).previousFocus();
}
},
showCursor: false,
readOnly: false,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
keyboardType: TextInputType.number,
maxLength: 1,
decoration: InputDecoration(
counter: Offstage(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(width: 2, color: Colors.black54),
borderRadius: BorderRadius.circular(12)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(width: 2, color: Colors.black54),
borderRadius: BorderRadius.circular(12)),
),
),
),
);
}
}
When the length of the input data reaches one, you will have to change the text field focus node.
For Example
If you are in the first field, and you enter a number field one focus should be lost, and field two should be in focus. This can be done, by requestFocus.
This article will of help for you: Flutter Focus

Navigating to a new page with button class

This is my buttons class. I want to use its on pressed function to navigate to another page.
class DigerButtonu extends StatelessWidget {
final String butonyazisi;
final IconData butoniconu;
final Function butonfonksiyonu;
const DigerButtonu(this.butonyazisi,this.butonfonksiyonu,this.butoniconu);
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 20,right: 20),
width: 50,
height: 550,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Color(0xFF15182D).withOpacity(0.4),
blurRadius: 8,
spreadRadius: 2,
offset: Offset(4,4),
),
],
borderRadius: BorderRadius.all(Radius.circular(10)),
border: Border.all(
color: Colors.black,
width: 0.2,
)
),
child: ElevatedButton(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(butoniconu, color: Colors.white,size: 22,),
MyVerticalText(butonyazisi),
Icon(butoniconu, color: Colors.white,size: 22,),
],
),
style: ElevatedButton.styleFrom(
primary: Color(0xFF15182D),
onPrimary: Colors.white,
onSurface: Colors.grey,
//elevation: 0,
),
onPressed: (){
butonfonksiyonu;
},
),
);
}
}
But when i try to use the code below, it says 'The argument type 'Future'can't be assigned to the parameter type 'Function' '. How can i use it?
DigerButtonu('AYARLAR',Navigator.push(context,MaterialPageRoute(builder: (context) => clicker()), route),Icons.settings_rounded)
You can simply use lambdas for passing functions. Currently you pass the result of your method and not the method itself.
Here is your code with the corresponding lambda expression:
DigerButtonu('AYARLAR', () => Navigator.push(context,MaterialPageRoute(builder: (context) => clicker()), route),Icons.settings_rounded)

How to reuse a widget in flutter

I am learning flutter I want a particular widget to be reused with different images at run time.
How to attain this is giving me difficulties I would like to know how to get this.
I am writing the peice of code kindly suggest what is a correct way
scaffold: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
trailing: Image.asset('assets/Menu_Button.png'),
automaticallyImplyLeading: false,
backgroundColor: Colors.blueAccent,
),
child: SafeArea(
child: Material(
child: Container(
child: Column(
children: [
Column(
children: <Widget>[
new Stack(children: <Widget>[
new Container(
child: background.Row1
),
Container(
color: Colors.blueAccent,
child: Image.asset('assets/card_bg.png')
),
]
),
Container(
color: Colors.blueAccent,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ShowingOptions('assets/image1.png').Options,//*****calling function with parameter so that it can put widget**********//
ShowingOptions('assets/image2.png').Options,
ShowingOptions('assets/image3.png').Options,
ShowingOptions('assets/image4.png').Options,
],
),
background.Row2,
background.Row3
],
),
),
))
),
);
}
}
/**********function defination starts *************/
ShowingOptions(image) {
Widget Options = padding: EdgeInsets.only(bottom: 5, left: 7,
right: 7, top: 5),
child: Container(
height: 55.0,
width: 55.0,
child: Padding(
padding: EdgeInsets.all(1),
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 10,
child: new Image.asset(image, height: 150, width:
150),
)),
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
border: new Border.all(
color: Colors.orange,
width: 5.0,
),
)
),
);
}
}
/**********function defination ends *************/
What Iam doing is making a funciton and when I am calling the function 'showOptions('assets/image1')' I am passing the image that I need to show.
Inside the function defination I am writing a widget that I wanted to be placed whenevr I call that funcition bys showing the image that I have passed
the way I implemented this whole is not working want a solution. I know this is not the proper way as I am new I would like to have some guidance.
Create a Custom Widget,
Create a Stateless or Stateful Class
declare Required Vairables
return your Custom Widget
below is Example of CustomButton with onPressed event.
//Create a Stateless or Stateful Class
class CustomButton extends StatelessWidget {
//declare Required Vairables
final String buttonText;
final VoidCallback onPressed;
final bool loading;
//constructor
CustomButton({this.buttonText,this.onPressed,this.loading});
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 30,right: 30),
child: Container(
decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100)),
color: Colors.red),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.all(Radius.circular(100)),
splashColor: Colors.green,
onTap: onPressed,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Center(child:
loading==true?
CircularProgressIndicator(backgroundColor: Colors.white,)
:
Text(buttonText,style: TextStyle(fontSize: 30,color: Colors.white),)),
),
),
),
),
),
),
],
);
}
}
Use :
CustomButtonSmall(buttonText: "Direction",onPressed: (){})
Here is a wonderfully explained example of how to achieve this easily.
I just copy the code from there. You basically have to create a separate class for the widget you have in mind:
import 'package:flutter/material.dart';
class AppTextFormField extends StatelessWidget {
//
AppTextFormField({
this.controller,
this.hintText,
this.helpText,
this.prefixIcon,
this.suffixIcon,
this.isPassword,
this.enabled,
this.readOnly,
this.borderColor,
});
final TextEditingController controller;
final String hintText;
final String helpText;
final IconData prefixIcon;
final IconData suffixIcon;
final bool isPassword;
final bool enabled;
final bool readOnly;
final Color borderColor;#override
Widget build(BuildContext context) {
return Container(
child: TextFormField(
controller: controller,
readOnly: null == readOnly ? false : true,
obscureText: null == isPassword ? false : true,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.greenAccent,
width: 1.0,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.greenAccent,
width: 1.0,
),
),
border: OutlineInputBorder(
borderSide: BorderSide(
color: null == borderColor ? Colors.teal : borderColor,
width: 1.0,
),
),
hintText: null == hintText ? '' : hintText,
helperText: null == helpText ? '' : helpText,
prefixIcon: null == prefixIcon ? null : Icon(prefixIcon),
suffix: null == suffixIcon ? null : Icon(suffixIcon),
enabled: null == enabled ? true : false,
),
),
);
}
}
And then in the class where you want to use the widget you call the it like this:
Container(
child: Column(
children: [
AppTextFormField(
controller: _emailController,
helpText: 'Email',
hintText: 'Email',
prefixIcon: Icons.email,
),
AppTextFormField(
controller: _passwordController,
helpText: 'Password',
hintText: 'Password',
isPassword: true,
prefixIcon: Icons.lock_open,
),
You don't have to use all the methods, just the ones you need.