I have designed a ui using flutter first I checked it in my phone which is Moto g5s plus the ui looks goods and I occupies entire screen but when I open the same app in iPhone 11 pro max I am getting a huge empty space but when I open it in iPhone 8 then the ui looks fine as it is in Moto g5s plus. I want to know how to have same consistent ui across different device sizes in flutter?
class Login extends StatefulWidget
{
#override
State<StatefulWidget> createState() {
return LoginState();
}
}
class LoginState extends State<Login>
{
String _email,_password;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState()
{
super.initState();
}
Widget _progressBar(AuthProvider authProvider)
{
//print("progress"+authProvider.progressStatus.toString());
return Visibility(
maintainSize: true,
maintainAnimation: true,
maintainState: true,
visible: authProvider.progressStatus,
child: Container(
child: Center(
child: SizedBox(
width: 60,
height: 60,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0.0, 1.0), //(x,y)
blurRadius: 1.0,
),
],
),
),
Center(
child: CircularProgressIndicator(),
)
],
),
)
)
),
);
}
Widget _emailTextField(AuthProvider authProvider)
{
return TextFormField(
onChanged: (String value){
authProvider.checkEmail(value);
},
decoration: InputDecoration(
labelText: "Email id",
errorText: authProvider.emailStatus ? null : "Enter a valid email",
border: OutlineInputBorder(
borderRadius: new BorderRadius.circular(32.0),
)
),
keyboardType: TextInputType.emailAddress,
validator: (String value){
if(value.isEmpty || !RegExp(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").hasMatch(value))
{
return "Enter a valid email";
} else {
return null;
}
},
onSaved: (String value){
_email = value;
},
);
}
Widget _passwordTextField(AuthProvider authProvider)
{
//print("pass check "+authProvider.passStatus.toString());
return TextFormField(
decoration: InputDecoration(labelText: "Password",
filled: true,
errorText: authProvider.passStatus ? null : "Password is too short",
border: OutlineInputBorder(
borderRadius: new BorderRadius.circular(32.0),
),
fillColor: Colors.white
),
keyboardType: TextInputType.text,
obscureText: true,
onChanged: (String value){
authProvider.checkPassword(value);
},
validator: (String value){
if(value.isEmpty)
{
return "Enter a valid password";
}
else if(value.length < 8)
{
return "Password is too short";
}
else
{
return null;
}
},
onSaved: (String value){
_password = value;
},
);
}
void _login(AuthProvider authProvider)
{
if(!_formKey.currentState.validate())
{
return;
}
_formKey.currentState.save();
Map<String,String> map = new Map();
map['email'] = _email;
map['password'] = _password;
authProvider.login(map);
}
#override
Widget build(BuildContext context) {
final authProvider = Provider.of<AuthProvider>(context);
if(authProvider.loginStatus != null && authProvider.loginStatus != "success")
{
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text('${authProvider.loginStatus}',
style: TextStyle(color: Colors.black),),
backgroundColor: Color(0xFFe5e5e5),
));
}
return Scaffold(
key: _scaffoldKey,
body: Stack(
children: <Widget>[
SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
margin: EdgeInsets.fromLTRB(0, 48, 0, 0),
child: Text(
"Take Orders",
style: TextStyle(color: Theme.of(context).primaryColorDark,fontSize: 20),
),
),
Container(
child: Text(
"Track the Best Selling Items",
style: TextStyle(color: Theme.of(context).primaryColor,fontSize: 16),
),
),
Container(
margin: EdgeInsets.fromLTRB(16, 0, 16, 0),
child: SvgPicture.asset('assets/images/undraw_booking.svg',width: 100.0,height: 280.0,),
),
Container(
margin: EdgeInsets.fromLTRB(16, 0, 0, 0),
child:Row(
children: <Widget>[
Text(
"Login To ",
style: TextStyle(color: Colors.black,fontSize: 20)
),
Text(
"Take orders",
style: TextStyle(color: Theme.of(context).primaryColorDark,fontSize: 20),
)
],
),
),
Container(
margin: EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
//_emailTextField(_loginBloc),
Container(
margin: EdgeInsets.fromLTRB(0, 8, 0, 0),
child: _emailTextField(authProvider),
),
Container(
margin: EdgeInsets.fromLTRB(0, 8, 0, 0),
child: _passwordTextField(authProvider),
),
Container(
margin: EdgeInsets.fromLTRB(0, 8, 0, 0),
child: Align(
alignment: Alignment.centerLeft,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0)
),
padding: EdgeInsets.fromLTRB(64, 12, 64, 12),
color: Theme.of(context).accentColor,
textColor: Colors.white,
child: Text(
"Login",
),
onPressed: (){
_login(authProvider);
},
) ,
),
),
],
),
),
),
],
),
)
),
_progressBar(authProvider),
],
),
);
}
}
images of emulator
without seeing code i cannot advise you proper solution however, i guess that tricks will solve your many issues.
instead of using fixed values
try to use
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
you can also use them like
height: MediaQuery.of(context).size.height * 0.80, // 80% of screen height
width: MediaQuery.of(context).size.width * 0.35, // 35% of screen width
Hope will help you
Related
this is my first time using community to ask about my project. First thing first, english isn't my first language and I'm a very beginner in flutter world. I'm trying to build my first mobile application using flutter and now I'm trying to connect my project to firebase (I looked at youtube tutorial). I don't know if the firebase already connect because when I'm trying to run the application and go to registration page, there this error message.
And here is my code:
import 'package:dfu_check_application/common/auth_controller.dart';
import 'package:flutter/material.dart';
import 'package:dfu_check_application/common/theme_helper.dart';
import 'package:dfu_check_application/pages/widgets/header_widget.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'profile_page.dart';
class RegistrationPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _RegistrationPageState();
}
}
class _RegistrationPageState extends State<RegistrationPage> {
final _formKey = GlobalKey<FormState>();
bool checkedValue = false;
bool checkboxValue = false;
#override
Widget build(BuildContext context) {
var nameController = TextEditingController();
var emailController = TextEditingController();
var passwordController = TextEditingController();
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Stack(children: [
Container(
height: 150,
child: HeaderWidget(150, false, Icons.person_add_alt_1_rounded),
),
Container(
margin: EdgeInsets.fromLTRB(25, 50, 25, 10),
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
alignment: Alignment.center,
child: Column(
children: [
Form(
key: _formKey,
child: Column(
children: [
GestureDetector(
child: Stack(
children: [
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
border:
Border.all(width: 5, color: Colors.white),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 20,
offset: const Offset(5, 5),
),
],
),
child: Icon(
Icons.person,
color: Colors.grey.shade300,
size: 80.0,
),
),
Container(
padding: EdgeInsets.fromLTRB(80, 80, 0, 0),
child: Icon(
Icons.add_circle,
color: Colors.grey.shade700,
size: 25.0,
),
),
],
),
),
SizedBox(
height: 30,
),
Container(
child: TextFormField(
controller: nameController,
decoration: ThemeHelper().textInputDecoration(
'Full Name', 'Enter your full name'),
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(
height: 30,
),
SizedBox(height: 20.0),
Container(
child: TextFormField(
controller: emailController,
decoration: ThemeHelper().textInputDecoration(
"E-mail address", "Enter your email"),
keyboardType: TextInputType.emailAddress,
validator: (val) {
// ignore: prefer_is_not_empty
if (!(val!.isEmpty) &&
!RegExp(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$")
.hasMatch(val)) {
return "Enter a valid email address";
}
return null;
},
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(height: 20.0),
Container(
child: TextFormField(
obscureText: true,
controller: passwordController,
decoration: ThemeHelper().textInputDecoration(
"Password*", "Enter your password"),
validator: (val) {
if (val!.isEmpty) {
return "Please enter your password";
}
return null;
},
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(height: 15.0),
FormField<bool>(
builder: (state) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Checkbox(
value: checkboxValue,
onChanged: (value) {
setState(() {
checkboxValue = value!;
state.didChange(value);
});
}),
Text(
"I accept all terms and conditions.",
style: TextStyle(color: Colors.grey),
),
],
),
Container(
alignment: Alignment.centerLeft,
child: Text(
state.errorText ?? '',
textAlign: TextAlign.left,
style: TextStyle(
color: Theme.of(context).errorColor,
fontSize: 12,
),
),
)
],
);
},
validator: (value) {
if (!checkboxValue) {
return 'You need to accept terms and conditions';
} else {
return null;
}
},
),
SizedBox(height: 20.0),
GestureDetector(
onTap: () {
AuthController.instance.register(
nameController.text.trim(),
emailController.text.trim(),
passwordController.text.trim());
},
),
Container(
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: const EdgeInsets.fromLTRB(40, 10, 40, 10),
child: Text(
"Register".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () {
if (_formKey.currentState!.validate()) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => ProfilePage()),
(Route<dynamic> route) => false);
}
},
),
),
SizedBox(height: 30.0),
Text(
"Or create account using social media",
style: TextStyle(color: Colors.grey),
),
SizedBox(height: 25.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
child: FaIcon(
FontAwesomeIcons.google,
size: 35,
color: HexColor("#EC2D2F"),
),
onTap: () {
setState(() {
showDialog(
context: context,
builder: (BuildContext context) {
return ThemeHelper().alartDialog(
"Google Account",
"You tap on Google icon.",
context);
},
);
});
},
),
],
),
],
),
),
],
),
),
]),
),
);
}
}
If you guys see more error on my code, please tell me because I'm very clueless about this. Thank you in advance!
The issue occurs from Stack the one inside
Column(
children: [
Form(
key: _formKey,
child: Column(
children: [
GestureDetector(
child: Stack( // this one
Can be fixed by providing hight
GestureDetector(
child: SizedBox(
height: MediaQuery.of(context).size.height, //this based on your need
child: Stack(
I think you can re struct the widget and don't need to use multi-Stack.
More about /ui/layout and Unbounded height / width
So I'm trying to update the value of the drop down list using the setState, but when I select a value from the list, the value on the screen won't be able to change
import 'package:demo_app_admin/Custom/custom_Font.dart';
import 'package:flutter/material.dart';
import '/Custom/Custom_Raised_Bottun.dart';
import '/Custom/Header.dart';
import '/Custom/inputField.dart';
class LoginView extends StatefulWidget {
#override
_LoginViewState createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
#override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final isKeyboard = MediaQuery.of(context).viewInsets.bottom != 0;
String _dropdownvalue = "Global admin";
List<String> _items = <String> ["Global admin", "Institution admin"];
return Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.topCenter, colors: [
Colors.teal[700]!,
Colors.teal[200]!,
Colors.teal[400]!
]),
),
child: Column(
children: <Widget>[
const SizedBox(
height: 80,
),
if (!isKeyboard)
Header(
padding: const EdgeInsets.all(20),
crossAxisAlignment: CrossAxisAlignment.start,
head: "Welcome",
headTextStyle:
const TextStyle(color: Colors.white, fontSize: 40),
sizedBoxHeight: 10,
subtitle: "Sign In to Your Admin Account",
subtitleTextStyle:
const TextStyle(color: Colors.white, fontSize: 18),
),
Expanded(
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
topRight: Radius.circular(60),
)),
child: Padding(
padding: const EdgeInsets.all(30),
child: SingleChildScrollView(
reverse: true,
padding: EdgeInsets.all(32),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
const SizedBox(
height: 40,
),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10)),
child: Column(
children: <Widget>[
InputField(
labelText: 'Email',
padding: EdgeInsets.all(10),
borderSide: BorderSide(color: Colors.grey),
hintText: "Enter your email",
color: Colors.grey,
inputBorder: InputBorder.none,
obscureText: false,
enableSuggestion: true,
autoCorrect: true,
onSaved: (value) {},
// (value){controller.email = value!;},
validator: (value) {
if (value == null) {
print("ERROR");
}
},
),
InputField(
labelText: 'Password',
padding: EdgeInsets.all(10),
borderSide: BorderSide(color: Colors.grey),
hintText: "Enter your password",
color: Colors.grey,
inputBorder: InputBorder.none,
obscureText: true,
enableSuggestion: false,
autoCorrect: false,
onSaved: (value) {},
// (value){ controller.password = value!;},
validator: (value) {
if (value == null) {
print("ERROR");
}
},
),
],
),
),
const SizedBox(
height: 40,
),
here is the issue
DropdownButton<String>(
value: _dropdownvalue,
icon: Icon(Icons.keyboard_arrow_down),
items: _items.map((String _items) {
return DropdownMenuItem<String>(
value: _items,
child: CustomFont(text: _items),
);
}).toList(),
onChanged: (value) {
setState(() => _dropdownvalue = value!);
}),
const SizedBox(
height: 40,
),
CustomRaisedButton(
width: 200,
height: 50.0,
margin: const EdgeInsets.symmetric(horizontal: 50),
color: Colors.teal.shade500,
borderRadius: BorderRadius.circular(10),
text: "LOGIN",
textColor: Colors.white,
fontSize: 17,
fontWeight: FontWeight.bold,
function: () {}
// {
// _formKey.currentState?.save();
// if(_formKey.currentState?.validate() !=null){
// controller.signInWithEmailAndPassword();
// }
// },
),
SizedBox(
height: 10,
),
],
),
),
),
),
))
],
),
),
);
}
}
The issue is here, you are declaring variables inside build. Therefore, variables get reset to default value on every build. Means setState.
Declare variables outside the build method.
class _LoginViewState extends State<LoginView> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _dropdownvalue = "Global admin";
List<String> _items = <String>["Global admin", "Institution admin"];
#override
Widget build(BuildContext context) {
final isKeyboard = MediaQuery.of(context).viewInsets.bottom != 0;
return Scaffold(
More about StatefulWidget.
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
I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, here I feel I need some help. I have written code to upload photograph, but I wanted to shift the method to another and access the functionality.
Here is my code
class EditProfile extends StatefulWidget {
EditProfile({Key? key}) : super(key: key);
#override
State<EditProfile> createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
File? image;
Future PickedImage(ImageSource source) async {
try {
final image = await ImagePicker()
.pickImage(source: source, maxWidth: 160, maxHeight: 160);
if (image == null) return;
setState(() {
final _imgTemp = File(image.path);
});
} on PlatformException catch (e) {
print('failed to Upload $e');
}
}
#override
Widget build(BuildContext context) {
var _textController = ProfileEdit();
return Scaffold(
body: GetX<ProfileController>(
init: Get.put<ProfileController>(ProfileController()),
builder: (ProfileController profileController) {
return Container(
child: ListView.builder(
itemCount: profileController.profiles.length,
itemBuilder: (BuildContext context, int i) {
final _profileModel = profileController.profiles[i];
setTextEditControllerValue(_textController, _profileModel);
return SafeArea(
child: Container(
padding: EdgeInsets.all(20),
child: Form(
child: Column(
children: [
const SizedBox(
height: 20,
),
GestureDetector(
onTap: () {
photoBottomSheet();
},
child: CircleAvatar(
radius: 100,
backgroundImage: NetworkImage(
'https://www.alchinlong.com/wp-content/uploads/2015/09/sample-profile.png'),
),
),
const SizedBox(
height: 40,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.fNameController),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border:
OutlineInputBorder(borderSide: BorderSide()),
),
controller: _textController.lNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Address',
border:
OutlineInputBorder(borderSide: BorderSide()),
),
controller: _textController.adressController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Phone Numbaer',
border:
OutlineInputBorder(borderSide: BorderSide()),
),
controller: _textController.phoneController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'School Name',
border:
OutlineInputBorder(borderSide: BorderSide()),
),
controller: _textController.sclNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Student Class',
border:
OutlineInputBorder(borderSide: BorderSide()),
),
controller: _textController.stdClassController,
),
SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () async {
CircularProgressIndicator();
ProfileModel profileModel =
profileModelVal(_textController);
await FirestoreDb.updateProfile(profileModel);
Get.offAll(ProfileScreen());
},
child: Text('Update'))
],
),
),
),
);
}),
);
},
));
}
void photoBottomSheet() {
Get.bottomSheet(
Container(
//color: Colors.white,
height: 150,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
//Text('Select from source'),
GestureDetector(
onTap: () =>
PickedImage(ImageSource.camera),
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Icon(
Icons.camera,
size: 25,
color: Colors.white,
),
SizedBox(
width: 10,
),
Text(
'Camera',
style: TextStyle(fontSize: 25, color: Colors.white),
),
],
),
),
SizedBox(
height: 10,
),
Divider(
thickness: 0.5, color: Colors.white,
),
SizedBox(
height: 10,
),
GestureDetector(
onTap: () =>
PickedImage(ImageSource.gallery),
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Icon(
Icons.image,
size: 25,
color: Colors.white,
),
SizedBox(
width: 10,
),
Text(
'Gallery',
style: TextStyle(fontSize: 25, color: Colors.white),
),
],
),
),
],
),
),
backgroundColor: Color(0xff2AA8A1),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
);
}
ProfileModel profileModelVal(ProfileEdit _textController) {
final profileModel = ProfileModel(
firstName: _textController.fNameController.text.trim(),
lastName: _textController.lNameController.text.trim(),
parentName: _textController.fatherNameController.text.trim(),
phoneNumber: _textController.phoneController.text.trim(),
address: _textController.adressController.text.trim(),
schoolName: _textController.sclNameController.text.trim(),
stdClass: _textController.stdClassController.text.trim());
return profileModel;
}
void setTextEditControllerValue(
ProfileEdit _textController, ProfileModel _profileModel) {
_textController.fNameController.value =
TextEditingValue(text: _profileModel.firstName);
_textController.lNameController.value =
TextEditingValue(text: _profileModel.lastName);
_textController.fatherNameController.value =
TextEditingValue(text: _profileModel.parentName);
_textController.adressController.value =
TextEditingValue(text: _profileModel.address);
_textController.phoneController.value =
TextEditingValue(text: _profileModel.phoneNumber);
_textController.sclNameController.value =
TextEditingValue(text: _profileModel.schoolName);
_textController.stdClassController.value =
TextEditingValue(text: _profileModel.stdClass);
}
void clearTextController(ProfileEdit _textController) {
_textController.fNameController.clear();
_textController.lNameController.clear();
_textController.fatherNameController.clear();
_textController.adressController.clear();
_textController.phoneController.clear();
_textController.sclNameController.clear();
_textController.stdClassController.clear();
}
}
Now the method photoBottomSheet() has to be shifted to another file and I should use it in any page I want. Please help me Here.
create a dart file called photo_bottom_sheet and add the method there, then where ever you want to add it you will just have to import that file on the top of the dart file like so :
import 'package:app/photo_bottom_sheet';
and then add the method wwhere you need it
photoBotomSheet()
where you want it.
1.copy the function and make separate .dart file.
2. import that function from that file wherever you want just like you import package.
I am trying to come up with a code editor which takes input from a text form field and shows the output on a Rich Text widget using DartSyntaxHighlighter.
While it works fine for a short snippet of code, it doesn't show all the code for a larger snippet. Here's what I've done so far :
class CodeEditorWidget extends StatefulWidget {
CodeEditorWidget();
#override
_ContentWidgetState createState() {
return _ContentWidgetState();
}
}
class _ContentWidgetState extends BaseState<CodeEditorWidget> {
String _currentCode = "";
#override
void initializeData() {
_currentCode = "class HelloWorld {\n"
"public static void main() {\n"
"System.out.println(\"Hello again\");\n"
"}\n"
"}";
_contentController.addListener(() {
_currentCode = _contentController.value.text;
setState(() {
});
});
}
#override
Widget build(BuildContext context) => _buildContent();
Widget _buildContent() {
//return _buildBody();
userState = AppStateWidget.of(context).userState;
return _buildBody();
}
Scaffold _buildBody() => Scaffold(
key: _scaffoldLoginKey,
appBar: buildAppBar("Code Editor"),
body: _buildCodeEditor(),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
floatingActionButton: _buildFab(),
);
_buildCodeEditor() => Card(
margin: const EdgeInsets.fromLTRB(BaseState.horizontalMargin, 0, BaseState.horizontalMargin, 0),
child: Column(
children: <Widget>[
Expanded(
child: _buildCodeView()//buildSyntaxCodeBlock(_currentCode, 12)//_buildCodeView(),
),
_buildInputContainer()
],
),
);
_buildCodeView() => SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
width: double.infinity,
height: double.maxFinite,
padding: EdgeInsets.all(12),
decoration: BoxDecoration(color: Colors.black),
child: RichText(
text: TextSpan(
style: TextStyle(fontFamily: 'VarelaRound-Regular', fontSize: 12),
children: <TextSpan>[
DartSyntaxHighlighter(SyntaxHighlighterStyle.darkThemeStyle()).format(_currentCode)
],
),
),
),
),
);
Container _buildInputContainer() {
return Container(
color: Colors.grey,
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_buildInputLayout(),
],
),
);
}
_buildInputLayout() => Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[_buildTextForm()],
);
Widget _buildTextForm() => Flexible(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
style: buildTextStyleBlack(16),
decoration: InputDecoration.collapsed(hintText: "Type here..."),
maxLines: 10,
validator: _validateEmptyCode,
controller: _contentController,
keyboardType: TextInputType.multiline,
onSaved: (String contentString) {
//_currentCode = contentString;
},
),
),
),
);
String _validateEmptyCode(String value) {
return value.isEmpty ? "Required" : null;
}
var _contentController = TextEditingController();
_buildFab() => FloatingActionButton(
onPressed: () {
setState(() {
});
},
child: Icon(Icons.add),
foregroundColor: Colors.white,
backgroundColor: Colors.green,
);
var _scaffoldLoginKey = GlobalKey<ScaffoldState>();
_showSnackBar(String message) => _scaffoldLoginKey.currentState
.showSnackBar(SnackBar(content: Text(message, style: buildTextStyle(16),)));
}
Here's a screen shot for reference :
This is a web page I am trying to build in flutter.
For me, this piece of code is doing what you are trying to acheive.
TextEditingController text1Controller = new TextEditingController();
TextEditingController text2Controller = new TextEditingController();
#override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
return new Scaffold(
backgroundColor: Colors.white,
appBar: new PreferredSize(
preferredSize: new Size(screenSize.width, 55.0),
child: new AppBar(
elevation: 5.0,
title : new Text(
"Code Editor",
style: new TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18.0)),
centerTitle: true,
backgroundColor: Colors.blue,
),
),
body: Container(
child: Column(
children: <Widget>[
new Padding(padding: EdgeInsets.only(bottom: 20.0, top: 20.0)),
new TextField(
onChanged: (text) {
setState(() {
text2Controller.text = text;
});
},
controller: text1Controller,
keyboardType: TextInputType.text,
autofocus: false,
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
focusedBorder: OutlineInputBorder(borderSide: const BorderSide(color: Colors.black, width: 2.0)),
),
),
new Padding(padding: EdgeInsets.only(bottom: 20.0)),
new TextField(
controller: text2Controller,
keyboardType: TextInputType.text,
autofocus: false,
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
focusedBorder: OutlineInputBorder(borderSide: const BorderSide(color: Colors.black, width: 2.0)),
),
)
],),),
);
}