Flutter - How can I reuse some code at multiple places - flutter

Hi I have a app where I will be making a book and this book will be with images,
I am trying to reuse code meaning how to add code within a method and than have that method at different areas but only change the image in each method .. .to make the code more reusable??? the code will stay the same but the image in each code block will change... i dont want to copy and paste the code again and again.
import 'dart:ui';
import 'package:adobe_xd/adobe_xd.dart';
import 'dart:io';
import 'package:Quran_highlighter/main.dart';
import 'package:flutter/rendering.dart';
import 'package:system_shortcuts/system_shortcuts.dart';
import 'package:Quran_highlighter/Widgets/NavDrawer.dart';
import 'package:flutter/material.dart';
import 'package:zoom_widget/zoom_widget.dart';
import 'package:flutter/gestures.dart';
import 'package:Quran_highlighter/Widgets/size_config.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
class Aliflaammeem extends StatefulWidget {
#override
_AliflaammeemState createState() => _AliflaammeemState();
}
class _AliflaammeemState extends State<Aliflaammeem> {
#override
Widget build(BuildContext context) {
var screenSizes = MediaQuery.of(context).size;
return Scaffold(
appBar: new AppBar(title: new Text("1 Alif-laam-meem آلم, Pg2")),
// return DefaultTextStyle(
// style: Theme.of(context).textTheme.bodyText2,
body: LayoutBuilder(builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: Stack(children: <Widget>[
new Slidable(
delegate: new SlidableDrawerDelegate(),
actionExtentRatio: 0.10,
// body: Center,
child: SafeArea(
top: true,
bottom: true,
right: true,
left: true,
child: new Container(
**child: new Image.asset(
"test/assets/Para 1 - Alif-laam-meem no color/quranpg2.png",**
fit: BoxFit.cover,
),
),
),
actions: <Widget>[
new IconSlideAction(
caption: 'English',
// color: Colors.lightBlue,
color: Colors.blueGrey,
icon: Icons.language,
foregroundColor: Colors.lightBlue,
// color: Colors.black,
// ),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Changepg2topg3()),
);
}),
new IconSlideAction(
caption: 'Forward',
// color: Colors.greenAccent,
// color: Colors.black87,
icon: Icons.arrow_back_ios,
foregroundColor: Colors.greenAccent,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Changepg2topg3()),
);
}),
// ),
],
secondaryActions: <Widget>[
new IconSlideAction(
caption: 'Back',
// color: Colors.red[200],
icon: Icons.arrow_forward_ios,
foregroundColor: Colors.red[200],
// color: Colors.black87,
// onTap: () => _showSnackBar('More'),
),
new IconSlideAction(
caption: 'Arabic',
// color: Colors.yellow[800],
icon: Icons.brightness_4,
foregroundColor: Colors.yellow[800],
color: Colors.blueGrey,
// onTap: () =>
),
],
),
]));
}));
}
}
//I WANT THE TOP CODE TO BE THE GLOBAL CODE WHICH WILL REUSED AGAIN AND
AGAIN IN THE SAME CLASS - AND IF I CHANGE SOMETHING UP THERE, I WANT IT TO AUTOMATICALLY CHANGE THROUGHOUT ALL THE PAGES
AND BELOW WE HAVE THE SAME CODE WHICH I COPIED AND PASTED - AND JUST CHANGED THE IMAGE AND APPBAR TITLE.... I NEED TO SEE HOW I CAN ACHIEVE THIS WITHOUT COPY AND PASTING....
class Changepg2topg3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
var screenSizes = MediaQuery.of(context).size;
return Scaffold(
appBar: new AppBar(title: new Text("1 Alif-laam-meem آلم, Pg3")),
// return DefaultTextStyle(
// style: Theme.of(context).textTheme.bodyText2,
body: LayoutBuilder(builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: Stack(children: <Widget>[
new Slidable(
delegate: new SlidableDrawerDelegate(),
actionExtentRatio: 0.10,
// body: Center,
child: SafeArea(
top: true,
bottom: true,
right: true,
left: true,
child: new Container(
// padding: EdgeInsets.zero,
**child: new Image.asset(
`"test/assets/Para 1 - Alif-laam-meem no color/quranpg3.png",*`*
// fit: BoxFit.fitidth,
fit: BoxFit.cover,
),
),
),
actions: <Widget>[
new IconSlideAction(
caption: 'English',
color: Colors.lightBlue,
icon: Icons.language,
// onTap: () =>
),
new IconSlideAction(
caption: 'Forward',
color: Colors.greenAccent,
icon: Icons.arrow_back_ios,
// onTap: () => _showSnackBar('Share'),
),
],
secondaryActions: <Widget>[
new IconSlideAction(
caption: 'Back',
color: Colors.red[200],
icon: Icons.arrow_forward_ios,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Aliflaammeem()),
);
}),
// ),
new IconSlideAction(
caption: 'Arabic',
color: Colors.yellow[800],
icon: Icons.brightness_4,
// onTap: () =>
),
],
),
]));
// );
}));
}
}
// }

1.Make a class returning a list
2.Make a New Widget function and pass-in the list to this function

Related

How to keep disappearing Flutter Bottom Navigation and AppBar after navigating from subpages

I have a bottom Tab bar in my app for navigation and appbar, from the menu page after adding products in Cart screen there is Continue button when i pressed it take me to Login screen, there a normal login with and otp verification, now when i try to navigate back to menu screen after successfull otp verification, i see Tab bar disappeared and the App bar.
How i can fix this problem
Cart Screen
return Scaffold
....
row
...
Container showOrderConfirmationBtn(BuildContext context) {
return Container(
height: 50.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.transparent, style: BorderStyle.solid, width: 1.0),
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10.0),
),
child: FlatButton(
onPressed: () {
isLoggedIn == false
? Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginPage()))
: Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CarConfirmationCompletePage()));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
'Continue',
style: TextStyle(
color: Colors.white,
fontFamily: 'BuffetRegular',
fontSize: 13,
letterSpacing: 0.5),
),
],
),
)
],
),
),
);
}
}
Login Screen
return Scafold
....
GestureDetector(
onTap: () async {
final prefs =
await SharedPreferences.getInstance();
final customerData = LoginModel(
mobile: maskFormatter.getUnmaskedText());
final result = await loginServices
.loginCustomer(customerData);
final customerId = result['id'];
if (result['existsFlag'] == '1') {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
} else {
// Registering customer
// Registering customer device info
// and navigating the user to otpverification page
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
}
},
child: Container(
margin: const EdgeInsets.only(right: 20.0),
width: 40,
height: 40.0,
decoration: BoxDecoration(
color: Colors.green.shade300,
borderRadius: BorderRadius.circular(10.0),
),
child: Icon(Icons.arrow_forward_ios),
),
),
Otp Screen
return Scaffold
....
PinEntryTextField(
fieldWidth: 60.0,
showFieldAsBox: true,
onSubmit: (String pin) async {
final prefs = await SharedPreferences.getInstance();
// redirected to menu page
final optData =
OtpModel(customerId: widget.customerId, otp: pin);
final result = await loginServices.otpVerify(optData);
if (result['existsFlag'] == '1') {
// setting customer prefs
prefs.setBool('isLoggedIn', true);
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: null,
content: Text('неверный код подтверждения '),
);
},
); //end showDialog()
}
// ...............................
// showDialog(
// context: context,
// builder: (context) {
// return AlertDialog(
// title: Text("Pin"),
// content: Text('Pin entered is $pin'),
// );
// },
// ); //end showDialog()
// ...............................
}, // end onSubmit
),
Menu Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:get_it/get_it.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
// ... Constants
import '../constants.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Models
import '../models/cart_order.dart';
import '../models/menu_model.dart';
// ... API'S
import '../apis/api_response.dart';
import '../apis/menu-api.dart';
// ... Pages
import '../pages/menu_detail.dart';
class MenuPage extends StatefulWidget {
final Products pro;
MenuPage({Key key, this.pro}) : super(key: key);
#override
_MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
ProductApi get productsServices => GetIt.I<ProductApi>();
APIResponse<List<Products>> _apiResponse;
bool _isLoading = false;
void _fetchProducts() async {
setState(() {
_isLoading = true;
});
_apiResponse = await productsServices.getProductsList();
setState(() {
_isLoading = false;
});
}
hasDiscount(product) {
return product.hasDiscount == '1'
? product.priceAfter
: product.hasDiscount == '0'
? product.priceBefore
: product.priceAfter;
}
#override
void initState() {
_fetchProducts();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: ListView(
physics: PageScrollPhysics(),
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: kDefaultPadding, vertical: kDefaultPadding),
child: Text('Меню', style: kStyleHeaders),
),
SizedBox(
height: 10.0,
),
Builder(builder: (_) {
if (_isLoading) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(child: null),
);
}
if (_apiResponse.error) {
return Center(child: Text(_apiResponse.errorMessage));
}
if (_apiResponse.data.length == 0) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(
child: Text(
'No products has been found..!',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
fontFamily: 'BuffetBold',
color: Colors.black,
),
),
),
);
}
return GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: _apiResponse.data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.72,
mainAxisSpacing: 1.0,
crossAxisSpacing: 1.0,
),
itemBuilder: (context, index) {
var product = _apiResponse.data[index];
return CachedNetworkImage(
imageUrl: product.imageMedium,
imageBuilder: (context, imageProvider) => Column(
children: [
GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetail(
id: product.id,
title: product.title,
description: product.description,
structure: product.structure,
imageLarge: product.imageLarge,
weight: product.weight,
hasDiscount: product.hasDiscount,
priceBefore:
double.parse(product.priceBefore),
priceAfter:
double.parse(product.priceAfter),
isHit: product.isHit,
isNew: product.isNew,
isSpicy: product.isSpicy,
isRecommended: product.isRecommended,
isVegetarian: product.isVegetarian,
attributes: product.attributes),
),
),
child: Container(
alignment: Alignment(-1, 0.9),
child: (product.isNew == '1')
? Image.asset(
'assets/images/new.png',
width: 60.0,
)
: null,
height: 165.0,
width: 165.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
),
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 2.0,
spreadRadius: 0,
offset: Offset(0, 2))
],
),
),
),
Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 10.0),
child: Row(
children: [
Flexible(
child: Text(product.title,
style: kStyleTitle))
],
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
product.weight != null
? product.weight
: '',
style: kStyleWeight),
Text(
product.hasDiscount != '0'
? product.priceBefore
: '',
style: kStyleDiscount),
Container(
margin: EdgeInsets.symmetric(
horizontal: 3, vertical: 0),
height: 30.0,
width: 70.0,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0),
),
color: kPrimaryColor,
textColor: Colors.white,
padding:
EdgeInsets.symmetric(horizontal: 5.0),
onPressed: () {
// ... Todo
context.read<OrderNotify>().addOrder(
CartOrder(
product: product,
qty: 1,
price: hasDiscount(product)),
);
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(hasDiscount(product),
style: kStylePrice),
Icon(
FontAwesomeIcons.rubleSign,
size: 13.0,
color: Colors.white,
)
],
),
),
),
],
),
),
],
),
placeholder: (context, url) => Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation(Color(0xffB81F33)),
),
),
errorWidget: (context, url, error) => Icon(
Icons.error,
size: 40.0,
color: Theme.of(context).primaryColor,
),
);
},
);
}),
],
),
],
),
),
);
}
}
Main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ... API'S
import './apis/category-api.dart';
import './apis/menu-api.dart';
import './apis/promotion-api.dart';
import './apis/login-api.dart';
import './apis/ipaddress-api.dart';
import './apis/deviceinfo-api.dart';
import './apis/customer_deviceinfo-api.dart';
// Providers
import './providers/order_notify.dart';
import 'app.dart';
void setupLocator() {
GetIt.I.registerLazySingleton(() => PromotionApi());
GetIt.I.registerLazySingleton(() => CategoriesApi());
GetIt.I.registerLazySingleton(() => ProductApi());
GetIt.I.registerLazySingleton(() => LoginApi());
GetIt.I.registerLazySingleton(() => IPAddressInfo());
GetIt.I.registerLazySingleton(() => DeviceInfo());
GetIt.I.registerLazySingleton(() => CustomerDeviceInfoApi());
}
void setDeviceInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
DeviceInfo deviceServices = GetIt.I<DeviceInfo>();
IPAddressInfo ipServices = GetIt.I<IPAddressInfo>();
prefs.setString('ipAddress', await ipServices.getIPAddress());
prefs.setString('manufacturerModel', await deviceServices.getPhoneInfo());
prefs.setString('deviceVersion', await deviceServices.getPhoneVersion());
prefs.setString('os', await deviceServices.getOperatingSystem());
prefs.setString(
'screenResolution', await deviceServices.getScreenResolution());
prefs.setString('packageOrBundle', await deviceServices.getPackageName());
prefs.setString('appVersion', await deviceServices.getAppVersion());
prefs.setString('isPhysical',
await deviceServices.isPhysicalDevice() == true ? '1' : '0');
prefs.setBool('isLoggedIn', false);
}
void main() {
// ... setup shared prefrences
// ... todo
// ... get device informaton set shared prefrences
// ... todo
// ... Setuploacator
setupLocator();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (ctx) => OrderNotify(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
),
),
);
setDeviceInfo();
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isStartHomePage = false;
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 3), () {
// If the page has not jump over the jump page
if (!isStartHomePage) {
// Go Home and destroy the current page
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => App(),
),
(Route<dynamic> rout) => false);
isStartHomePage = true;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
'assets/images/stripes_min.jpg',
),
),
),
),
Positioned(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/Buffet_Logo_Trans_min.png',
width: 200.0,
height: 200.0,
),
],
),
),
),
],
),
);
}
}
main.screen
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// ... APP Helpers
import '../helpers/app_helper.dart';
// ... Pages
import '../pages/home_page.dart';
import '../pages/promotions_page.dart';
import '../pages/menu_page.dart';
import '../pages/more_page.dart';
import '../pages/orders_page.dart';
import '../pages/cart.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Widgets
import '../widgets/badge.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
// Current Index set to 0
int currentTabIndex = 0;
final List<Widget> pages = [
HomePage(
key: PageStorageKey('HomePage'),
),
PromotionsPage(
key: PageStorageKey('PromoPage'),
),
MenuPage(
key: PageStorageKey('MenuOage'),
),
OrdersPage(
key: PageStorageKey('Orderpage'),
),
MorePage(
key: PageStorageKey('Morepage'),
),
Cart(
key: PageStorageKey('CartPage'),
)
];
final PageStorageBucket bucket = PageStorageBucket();
// Current page
Widget currentPage;
void setTabIndex(index) {
setState(() {
currentTabIndex = index;
currentPage = pages[index];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
elevation: 0.0,
leading: InkWell(
onTap: () {
Helper.launchUrl('tel:88007073566');
},
child: Icon(
Icons.call,
color: Colors.black,
size: 25.0,
),
),
title: Text(
'BUFFET',
style: TextStyle(fontSize: 30.0, fontFamily: 'BuffetBold'),
),
centerTitle: true,
actions: [
Container(
margin: EdgeInsets.symmetric(horizontal: 0),
width: 60,
child: Badge(
color: Colors.green,
child: IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Cart()));
},
),
value: context.watch<OrderNotify>().items.length.toString(),
),
)
],
),
body: PageStorage(
child: pages[currentTabIndex],
bucket: bucket,
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setTabIndex(index);
},
currentIndex: currentTabIndex,
type: BottomNavigationBarType.fixed,
selectedItemColor: Theme.of(context).primaryColor,
selectedFontSize: 0,
unselectedFontSize: 0,
iconSize: 30,
elevation: 0,
backgroundColor: Colors.white,
selectedIconTheme: IconThemeData(size: 28),
unselectedItemColor: Theme.of(context).focusColor.withOpacity(1),
selectedLabelStyle:
Theme.of(context).textTheme.bodyText1.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
unselectedLabelStyle:
Theme.of(context).textTheme.button.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
showUnselectedLabels: true,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home_outlined,
),
label: 'Главная',
),
BottomNavigationBarItem(
icon: Icon(Icons.card_giftcard_outlined),
label: 'Акции',
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant),
label: 'Меню',
),
BottomNavigationBarItem(
icon: Icon(Icons.av_timer),
label: 'Заказы',
),
BottomNavigationBarItem(
icon: Icon(Icons.menu),
label: 'Еще',
)
],
),
);
}
}
App.dart
import 'package:flutter/material.dart';
// ... Constants
import 'constants.dart';
// ... Screens
import './screens/main_screen.dart';
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Buffet',
theme: ThemeData(
primaryColor: kPrimaryColor,
fontFamily: 'Buffet',
),
home: MainScreen(),
);
}
}
Your mistake is that you pushed MenuPage to stack in OtpScreen
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
You should pop the otp page or navigate to MainScreen that contains your PageStorage

The method RegisterCustomer isn't defined for the class Dashboard when routing to another screen in flutter

I have Dashboard screen in lib directory. The register_customer.dart file is under customers subdirectory in lib folder. I have imported register_customer.dart in dashboard screen. However the RegisterCustomer class in register_customer.dart is not resolving. Here is my code:
lib/dashboard.dart
import 'package:flutter/material.dart';
import './customers/register_customer.dart';
class MyDashboard extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: defaultBackgroundColor,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: btnTextColor,
),
onPressed: () {
//navigate to the previous page
Navigator.pop(context);
},
),
//navabar title text text
title: Text('Dashboard'),
),
body: Center(
child: Column(
children: <Widget>[
Container(
margin: const EdgeInsets.all(20.0),
//color: Colors.amber[600],
width: 200.0,
height: 250.0,
child: ListView(
children: <Widget>[
GestureDetector(
child: ListTile(
title: Text(
'Register Customer',
style:
TextStyle(fontSize: 20, color: Color(0xffE06C19)),
),
leading: Icon(
Icons.user,
color: Colors.amber,
),
),
onTap: () {
**//this is where the error is being raised**
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterCustomer()));
},
),
],
),
),
],
))),
);
}
}
lib/customers/register_customer.dart
import 'package:flutter/material.dart';
class RegisterCustomer extends StatefulWidget {
#override
_RegisterCustomerState createState() => _RegisterCustomerState();
}
String _first_name;
String _last_name;
class _RegisterCustomerState extends State<RegisterCustomer> {
final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.purple[800],
accentColor: Colors.amber,
accentColorBrightness: Brightness.dark),
home: Scaffold(
appBar: AppBar(
title: Text(
'Register Customer',
style: TextStyle(fontSize: 20),
textAlign: TextAlign.center,
),
),
body: Container(
margin: EdgeInsets.all(12),
child: Form(
key: _formkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 50,
),
RaisedButton(
color: Color(0xff980CF0),
textColor: Colors.white,
splashColor: Colors.grey,
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
child: Text(
'Register',
style: TextStyle(
color: Colors.orangeAccent,
fontSize: 17,
),
),
onPressed: () {
if (!_formkey.currentState.validate()) {
return;
}
//submit data to the server
},
)
],
),
),
),
),
);
}
}
I am experiencing same issue with other routes. What am I doing wrong?
I think the import path is incorrect:
import 'package:projectname/customer/register_customer.dart
if the file is in lib/customer/register_customer.dart

Flutter variable doesn't change background color when changed?

I'm new to flutter and am trying to update the background color of a scaffold when a variable is changed. the variable is declared in another file. The reason why it needs to change? I am trying to change the background of the app to grey, a dark mode option. Any advice on why the background doesn't change when the variable does? Any advice would be appreciated, thanks!
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';
import './Widgets/DrawerSettings.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatefulWidget {
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: Container(
width: 70,
child: ClipRRect(
borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
child: Drawer(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.bookmark),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SavedRoute()));
},
),
IconButton(
icon: Icon(Icons.rate_review),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: ReviewRoute()));
},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.share('Share');
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute()));
},
)
],
),
),
),
),
),
appBar: AppBar(
title: Text(
'Explore',
),
centerTitle: true,
backgroundColor: Colors.cyan[500],
),
body: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white, //Here is the code to change the background color when variable change.
body: Padding(
padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
child: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(5.0),
children: <Widget>[
Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
height: 150,
width: double.maxFinite,
child: InkWell(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SecondRoute()));
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
fit: BoxFit.cover,
height: 150.0,
width: 100.0,
),
),
),
),
),
],
),
),
),
),
),
);
}
}
Here is the second file
import 'package:flutter/material.dart';
class SettingsRoute extends StatefulWidget {
#override
_SettingsRouteState createState() => _SettingsRouteState();
}
bool DarkMode = false;
class _SettingsRouteState extends State<SettingsRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
appBar: AppBar(
title: Text(
'Settings',
),
centerTitle: true,
),
body: ListView(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
child: SwitchListTile(
title: Text(
'Dark Mode',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
color: DarkMode ? Colors.white : Colors.grey[800],
),
),
value: DarkMode,
activeColor: Colors.white,
inactiveThumbColor: Colors.white,
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
},
),
),
),
],
),
),
);
}
}
You can copy paste run full code below
You can pass callback refresh to SettingsRoute and call with widget.callback()
You can see working demo below
code snippet
class _FirstRouteState extends State<FirstRoute> {
refresh() {
setState(() {});
}
...
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute(
callback: refresh,
)));
},
...
class SettingsRoute extends StatefulWidget {
final VoidCallback callback;
SettingsRoute({this.callback});
...
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
widget.callback();
},
working demo
full code
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:share/share.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatefulWidget {
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: Container(
width: 70,
child: ClipRRect(
borderRadius: BorderRadius.vertical(top: Radius.circular(.0)),
child: Drawer(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.bookmark),
onPressed: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SavedRoute()));*/
},
),
IconButton(
icon: Icon(Icons.rate_review),
onPressed: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: ReviewRoute()));*/
},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.share('Share');
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SettingsRoute(
callback: refresh,
)));
},
)
],
),
),
),
),
),
appBar: AppBar(
title: Text(
'Explore',
),
centerTitle: true,
backgroundColor: Colors.cyan[500],
),
body: Scaffold(
backgroundColor: DarkMode
? Colors.grey[800]
: Colors
.white, //Here is the code to change the background color when variable change.
body: Padding(
padding: const EdgeInsets.fromLTRB(2, 12, 2, 12),
child: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(5.0),
children: <Widget>[
Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(2, 10, 2, 0),
height: 150,
width: double.maxFinite,
child: InkWell(
onTap: () {
/* Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: SecondRoute()));*/
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
'https://i.ytimg.com/vi/hlWiI4xVXKY/maxresdefault.jpg',
fit: BoxFit.cover,
height: 150.0,
width: 100.0,
),
),
),
),
),
],
),
]),
),
),
),
));
}
}
class SettingsRoute extends StatefulWidget {
final VoidCallback callback;
SettingsRoute({this.callback});
#override
_SettingsRouteState createState() => _SettingsRouteState();
}
bool DarkMode = false;
class _SettingsRouteState extends State<SettingsRoute> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: DarkMode ? Colors.grey[800] : Colors.white,
appBar: AppBar(
title: Text(
'Settings',
),
centerTitle: true,
),
body: ListView(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 10, 20),
child: SwitchListTile(
title: Text(
'Dark Mode',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
color: DarkMode ? Colors.white : Colors.grey[800],
),
),
value: DarkMode,
activeColor: Colors.white,
inactiveThumbColor: Colors.white,
onChanged: (bool value) {
setState(() {
DarkMode = !DarkMode;
});
widget.callback();
},
),
),
),
],
),
),
);
}
}
You need to get the value of the DarkMode variable from a global variable like using an app state provider. Or you can send the DarkMode value as a parameter to the next page. The first one is a better use-case.
Your provider will look like this:
import 'package:flutter/material.dart';
class AppStateProvider with ChangeNotifier {
bool _darkMode = false;
bool get darkMode => this._darkMode;
void setDarkMode(bool value) {
this._darkMode = value;
}
}
You can read more from here.

Flutter - whitespaces displaying for image in portrait and landscape

I keep seeing lot of white space if I do landscape or portrait within my image. I do need the slidable so didn't want to tweak the code too much, but I do want it to look representable
is there something wrong with my code?
I did add a picture this is happening in both landscape and portrait mode
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text(
"1 Alif-laam-meem آلم, Pg2",
style: new TextStyle(color: styling.appBarTextcolor),
),
leading: new IconButton(
icon: new Icon(styling.appBarBackArrowIcon),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NavDrawer(),
));
})),
body: LayoutBuilder(builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: Stack(children: <Widget>[
new Slidable(
delegate: new SlidableDrawerDelegate(),
actionExtentRatio: styling.sizeofenglishandforward,
child: SafeArea(
top: true,
bottom: true,
right: true,
left: true,
child: new Container(
child: new Image.asset(
"test/assets/Para 1 - Alif-laam-meem no color/quranpg2-1.png",
// fit: BoxFit.fitidth,
fit: BoxFit.cover,
),
),
),
actions: <Widget>[
new IconSlideAction(
caption: styling.englishIconText,
color: styling.englishIconColorstripe,
icon: styling.englishIcon,
foregroundColor: styling.englishIconColor,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Changepg2topg2Color()),
);
}),
new IconSlideAction(
caption: styling.forwardIconText,
color: styling.forwardIconColorstripe,
icon: styling.forwardIcon,
foregroundColor: styling.forwardIconColor,
// onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => Changepg2topg3()),
// );
// }
),
// ),
],
secondaryActions: <Widget>[
new IconSlideAction(
caption: styling.backIconText,
color: styling.backIconColorstripe,
icon: styling.backIcon,
foregroundColor: styling.backIconColor,
// onTap: () => _showSnackBar('More'),
),
new IconSlideAction(
caption: styling.arabicIconText,
color: styling.arabicIconColorstripe,
icon: styling.arabicIcon,
foregroundColor: styling.arabicIconColor,
// onTap: () =>
),
],
),
]));
}));
}
}
SafeArea is preventing your image to go at some restricted areas of screen like, underneath the notch area. Or for some devices there are NavigationKeys in the bottom of screen. Try removing these
Cheers :)
child: SafeArea(
top: true,
bottom: true,
right: true,
left: true,

Switch screen in flutter without context in flutter

I have this dart file(app_bar.dart) and am storing Appbars inside it and i have logged_home.dart file where am calling the app_bar.dart from. Now i want to be able to navigate to a new screen when i click next screen it sends me to PostData() while in app_bar.dart.
app_bar.dart:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kopala_dictionary/screens/authenticate/login.dart';
import 'package:kopala_dictionary/screens/author/post_data.dart';
import 'package:kopala_dictionary/screens/home/unlogged_home.dart';
//for logged in user
final loggedBar = AppBar(
title: Text('Kopalaz Dictionary'),
backgroundColor: Colors.green,
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
color: Colors.white,
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => PostData()));
},
icon: Icon(Icons.add),
label: Text(
'Post',
style: TextStyle(color: Colors.white),
)),
],
);
//For unlogged users
final unloggedBar = AppBar(
title: Text('Kopalaz Dictionary'),
backgroundColor: Colors.green,
elevation: 0.0,
);
logged_home.dart:
import 'package:flutter/material.dart';
import 'package:kopala_dictionary/screens/wrapper.dart';
import 'package:kopala_dictionary/services/auth.dart';
import 'package:kopala_dictionary/shared/app_bar.dart';
class LoggedInUserHome extends StatelessWidget {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green[10],
appBar: loggedBar,
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text(
'Kopalationary Menu',
style: TextStyle(color: Colors.white),
),
decoration: BoxDecoration(
color: Colors.green,
),
),
ListTile(
title: Text('Home'),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Wrapper()));
},
),
ListTile(
title: Text(
'My profile',
),
onTap: () {},
),
ListTile(
title: Text('Logout'),
onTap: () async {
dynamic result = await _auth.logoutUser();
},
),
ListTile(
title: Text(
'About',
),
onTap: () {},
),
],
),
),
body: Center(
child: Text('Development in progress!'),
),
);
}
}
do not forget that in Flutter everything is a widget !
So my advice would be to create functions which returns a widget:
import 'package:flutter/material.dart';
//for logged in user
AppBar loggedBar(BuildContext context) {
return AppBar(
title: Text('Kopalaz Dictionary'),
backgroundColor: Colors.green,
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
color: Colors.white,
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => PostData()));
},
icon: Icon(Icons.add),
label: Text(
'Post',
style: TextStyle(color: Colors.white),
)),
],
);
}
//For unlogged users
AppBar unloggedBar(BuildContext context) {
return AppBar(
title: Text('Kopalaz Dictionary'),
backgroundColor: Colors.green,
elevation: 0.0,
);
}
Do keep in mind that flutter does a lot in the background and it is therefore better practice not to store widget in global variable. If you need to access those widgets from different part of your app you should look into Inherited Widget or other form of state management (see list here).
see below link:
Navigate without context in Flutter with a Navigation Service
https://medium.com/flutter-community/navigate-without-context-in-flutter-with-a-navigation-service-e6d76e880c1c
also, you can use GetX library