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

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

Related

Flutter: Making a Dropdown Multiselect with Checkboxes

am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you
// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String> map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color> map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/
class Multiselect extends StatefulWidget {
final List<String> items;
const Multiselect({Key? key, required this.items}) : super(key: key);
#override
State<Multiselect> createState() => _MultiselectState();
}
class _MultiselectState extends State<Multiselect> {
final List<String> _selectedItems=[];
void _itemChange(String itemValue, bool isSelected) {
setState(() {
if (isSelected) {
_selectedItems.add(itemValue);
} else {
_selectedItems.remove(itemValue);
}
});
}
// this function is called when the Cancel button is pressed
void _cancel() {
Navigator.pop(context);
}
// this function is called when the Submit button is tapped
void _submit() {
Navigator.pop(context, _selectedItems);
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Select Topics'),
content: SingleChildScrollView(
child: ListBody(
children: widget.items
.map((item) => CheckboxListTile(
value: _selectedItems.contains(item),
title: Text(item),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (isChecked) => _itemChange(item, isChecked!),
))
.toList(),
),
),
actions: [
TextButton(
onPressed: _cancel,
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _submit,
child: const Text('Submit'),
),
],
);
}
}
class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
final List<String> items=[
'QUEUED',
'CLOSED',
'Rejected',
'INPROG',
'PENDING',
'RESOLVED',
'NEW',
];
final List<String>? results =await showDialog(
context: context,
builder: (BuildContext context) {
return Multiselect(items: items);
},
);
if(results !=null){
setState(() {
_selectedItems=results;
});
}
}
#override
void initState() {
loadData().then((value) {
_MyAllData.clear();
setState(() {
_MyAllData.addAll(value);
_SrForDsiplay=_MyAllData;
});
});
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http:MXSR/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold(resizeToAvoidBottomInset: false ,
appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
flexibleSpace: InkWell(onTap: () {
},),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (_MyAllData.isEmpty) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else { return
ListView(
children: <Widget>[Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
child: const Text('Filter')),
const Divider(
height: 30,
),
Wrap(
children: _selectedItems
.map((e) => Chip(
label: Text(e),
))
.toList(),
),
Row(children:<Widget>[ Expanded(
child: TextField(
decoration:
InputDecoration( hintText: "Enter id or description"),
onChanged: (text) {
text=text.toLowerCase();
setState(() {
_SrForDsiplay =_MyAllData.where((srAttributes) {
var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
var srID= srAttributes.attributes.ticketid.content.toString();
return srDescription.contains(text) || srID.contains(text);
}).toList();
title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
print(title_string);
}
);
},
)),])
],
),),
new ListView.builder(scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _SrForDsiplay.length,
itemBuilder: ((_, index) {
return
new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${_SrForDsiplay[index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${_SrForDsiplay[index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color:Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Row(children:[
Expanded(child: Badge(
position: BadgePosition.topEnd(top: -8, end: 20),
badgeColor: Colors.grey,
badgeContent: Text('1'),
child :IconButton(icon :Icon(Icons.file_present_rounded), padding: const EdgeInsets.all(0),
onPressed: () {
},
),
)
),
Expanded(child: IconButton (
icon: Icon(Icons.file_copy),
onPressed: () { },
),),
Expanded(child: IconButton(onPressed:() {
}, icon: Icon(Icons.delete)) )
],)
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
Navigator.push(
context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
);
}
);
}
),
)
]
);
}
},
),
),
);
}
}

'package:flutter/src/widgets/framework.dart':failed

#main.dart file
import 'package:flutter/material.dart';
import './widgets/new_transaction.dart';
import './widgets/transaction_list.dart';
import './widgets/chart.dart';
import './models/tranasction.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.amber,
// errorColor: Colors.red,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
// String titleInput;
// String amountInput;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
// Transaction(
// id: 't1',
// title: 'New Shoes',
// amount: 69.99,
// date: DateTime.now(),
// ),
// Transaction(
// id: 't2',
// title: 'Weekly Groceries',
// amount: 16.53,
// date: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime chosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: chosenDate,
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deleteTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tx) => tx.id == id);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Personal Expenses',
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
],
),
body: SingleChildScrollView(
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Chart(_recentTransactions),
TransactionList(_userTransactions, _deleteTransaction),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
#new_transaction.dart file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter/src/widgets/framework.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
late DateTime _selectedDate;
void initState() {
_selectedDate:
DateTime.now();
super.initState();
}
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
),
],
),
),
RaisedButton(
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button?.color,
onPressed: _submitData,
),
],
),
),
);
}
#override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
.add(DiagnosticsProperty<DateTime>('_selectedDate', _selectedDate));
}
}
#transaction_list.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chart.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chartbar.dart file
import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
height: 20,
child: FittedBox(
child: Text('\$${spendingAmount.toStringAsFixed(0)}'),
),
),
SizedBox(
height: 4,
),
Container(
height: 60,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
),
],
),
),
SizedBox(
height: 4,
),
Text(label),
],
);
}
}
#transaction.dart file
**i am using the latest version of flutter
and using android studio as emulator,
and using vs code as code editor my code has no errors,
but i keep getting this error after many attempts
i tested using real android device too but nothing changed error message:'package:flutter/src/widgets/framework.dart':failed
assertion:line4864 pos 12:'child==_child':is not true.
see also https://flutter.dev/docs/testing/errors **

Why am I having memory issues with flutter ChangeNotifierProvider?

I am making a shopping cart app in flutter with Change Notifier Provider. It is working fast and well at first. But it takes the more memory, the more I use it. I am adding and removing clearing items from list. Nothing complicated. Cannot know why it is working like this. It is slowing down gradually. This is main.dart:
class Main extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Cart(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: swatchColor,
primaryColor: primaryColor,
accentColor: tertiaryColor,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.black,
selectionColor: primaryColor,
selectionHandleColor: primaryColor,
),
),
initialRoute: '/login',
routes: {
'/home': (context) => Home(),
'/login': (context) => Login(),
'/tableReview': (context) => TableReview(),
'/createOrder': (context) => CreateOrder(),
'/orderReview': (context) => OrderReview(),
},
),
);
}
}
This is main cart_model.dart
import 'package:counter/data/models/cart_item.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
class Cart extends ChangeNotifier {
List<Item> cart = [];
addItemToCart({#required item}) {
Item newItem = Item(
id: item.id,
price: item.price is int ? item.price : int.parse(item.price),
title: item.title,
);
int i = cart.indexWhere((previousItem) => previousItem.id == newItem.id);
if (i > -1) {
cart[i].count++;
} else {
cart.add(newItem);
}
notifyListeners();
}
removeItemFromCart({#required item}) {
int index = cart.indexWhere((element) => element.id == item.id);
if (index > -1) {
if (cart[index].count > 1) {
cart[index].count--;
} else {
cart.removeWhere((element) => element.id == item.id);
}
}
notifyListeners();
}
clearCart() {
cart.clear();
notifyListeners();
}
int get totalPrice =>
cart.fold(0, (total, current) => total + (current.price * current.count));
}
This is menuitem.dart
class MenuItem extends StatelessWidget {
final dynamic foodItem;
MenuItem({#required this.foodItem});
void _showSecondPage(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) => Scaffold(
backgroundColor: Colors.black45,
body: Center(
child: Hero(
tag: foodItem.imgPath,
child: Image(image: NetworkImage(base_url + foodItem.imgPath)),
),
),
),
),
);
}
#override
Widget build(BuildContext context) {
int itemIndex = Provider.of<Cart>(context, listen: false)
.cart
.indexWhere((item) => item.id == foodItem.id);
return Container(
height: 80,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _showSecondPage(context),
child: Hero(
tag: foodItem.imgPath,
child: CircleAvatar(
backgroundImage: NetworkImage(base_url + foodItem.imgPath),
),
),
),
SizedBox(
width: 15,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
foodItem.title,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
Text('${foodItem.price.toString()} сум'),
],
)
],
),
Container(
width: 160,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon:
Icon(Icons.remove, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
Text(
itemIndex > -1
? '${Provider.of<Cart>(context).cart[itemIndex].count}'
: '0',
style: TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(Icons.add, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
],
),
),
],
),
);
}
}
This is consumer part:
import 'package:counter/common/socketio.dart';
import 'package:counter/data/models/cart_model.dart';
import 'package:counter/presentation/widgets/empty_cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class OrderReview extends StatefulWidget {
#override
_OrderReviewState createState() => _OrderReviewState();
}
class _OrderReviewState extends State<OrderReview> {
bool isCommentEnabled = false;
String guestCount;
String comment = '';
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
final myCart = context.watch<Cart>();
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text('Проверка заказа'),
),
body: Builder(
builder: (context) {
if (myCart.cart.length > 0) {
handleOrderCreate() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userId = prefs.getString('userId');
String tableNum = prefs.getString('tableNum');
String status = 'accepted';
print('$userId, $tableNum, $status');
Map orderToCreate = {
'tableNum': tableNum,
'status': 'accepted',
'userId': userId,
'guestCount': guestCount,
'comment': comment,
'foodList': myCart.cart
};
socketIO.emit('createOrder', json.encode(orderToCreate));
Navigator.of(context).pushNamed('/home');
Provider.of<Cart>(context, listen: false).clearCart();
}
return GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(new FocusNode()),
child: LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: IntrinsicHeight(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Form(
key: _formKey,
child: Column(
children: [
Container(
height: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color:
Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0,
3), // changes position of shadow
),
]),
child: ListView.separated(
itemBuilder:
(BuildContext context, int i) {
return ListTile(
title: Text(myCart.cart[i].title),
trailing: Container(
width: 160,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.remove,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.removeItemFromCart(
item: myCart
.cart[i]);
},
),
Text(
'${myCart.cart[i].count}',
style:
TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(
Icons.add,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.addItemToCart(
item: myCart
.cart[i]);
},
),
],
),
),
);
},
separatorBuilder:
(BuildContext context, int) {
return Divider(
height: 2,
color: Colors.grey,
);
},
itemCount: myCart.cart.length,
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Количество гостей',
),
onChanged: (newValue) {
setState(() => guestCount = newValue);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'Пожалуйста, введите количество гостей!';
}
return null;
},
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
onChanged: (newValue) {
setState(() => comment = newValue);
},
enabled: isCommentEnabled,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText:
'Лаваш острый, хот дог без майонеза и т.д.',
// labelText: 'Комментарий',
),
maxLines: 2,
),
),
Row(
children: [
Text('Комментарий'),
Switch(
value: isCommentEnabled,
onChanged: (bool value) {
setState(() =>
this.isCommentEnabled = value);
},
),
],
)
],
),
),
SizedBox(height: 20),
Row(
children: [
Text(
'Общая цена: ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
SizedBox(width: 20),
Text(
'${myCart.totalPrice} сум',
style: TextStyle(fontSize: 18),
),
],
),
Container(
height: 50,
width: 170,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.resolveWith(
(states) =>
Theme.of(context).primaryColor),
),
onPressed: () {
if (_formKey.currentState.validate()) {
handleOrderCreate();
}
},
child: Text(
'Отправить',
style: TextStyle(
color: Colors.white, fontSize: 18),
),
),
),
],
),
),
),
),
);
},
),
);
} else {
print('111');
return EmptyCart();
}
},
),
);
}
}
Is there something wrong with my code?

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.

Scroll View Not Responding in flutter

My Scrollview not Responding, can someone tell what I am missing in code:
Please Suggest me how to add scroll view listener I'm beginner.
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../main.dart';
import 'favourite_articles.dart';
import 'coin_system.dart';
class Settings extends StatefulWidget {
#override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
bool _notification = false;
ScrollController _controller;
#override
void initState() {
super.initState();
checkNotificationSetting();
}
checkNotificationSetting() async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = prefs.getInt(key) ?? 0;
if (value == 0) {
setState(() {
_notification = false;
});
} else {
setState(() {
_notification = true;
});
}
}
saveNotificationSetting(bool val) async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = val ? 1 : 0;
prefs.setInt(key, value);
if (value == 1) {
setState(() {
_notification = true;
});
} else {
setState(() {
_notification = false;
});
}
Future.delayed(const Duration(milliseconds: 500), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (BuildContext context) => MyHomePage()));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'More',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: 'Poppins'),
),
elevation: 5,
backgroundColor: Colors.white,
actions: <Widget>[
IconButton(
icon: Icon(Icons.mail),
color: Colors.black,
tooltip: 'Song Request',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
})
],
),
body: Container(
decoration: BoxDecoration(color: Colors.white),
child: SingleChildScrollView(
controller: _controller,
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 20, 0, 10),
child: Image(
image: AssetImage('assets/icon.png'),
height: 50,
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 10, 0, 20),
child: Text(
"Version 2.1.0 \n ",
textAlign: TextAlign.center,
style: TextStyle(height: 1.6, color: Colors.black87),
),
),
Divider(
height: 10,
thickness: 2,
),
//ListWheelScrollView(
ListView(
//itemExtent: 75,
shrinkWrap: true,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavouriteArticles(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/favourite.png",
width: 30,
),
title: Text('Favourite'),
subtitle: Text("See the saved songs"),
),
),
//Song Request Code
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/songrequest.png",
width: 30,
),
title: Text('Songs Request'),
subtitle: Text("Request your favourite songs"),
),
),
//Song Request Code End
ListTile(
leading: Image.asset(
"assets/more/notification.png",
width: 30,
),
isThreeLine: true,
title: Text('Notification'),
subtitle: Text("Change notification preference"),
trailing: Switch(
onChanged: (val) async {
await saveNotificationSetting(val);
},
value: _notification),
),
],
)
],
),
),
),
//),
);
//);
}
}
So, I have tried SingleChildScrollView, in that I have Container and Listview. But Listview doesn't response on scrolling action in landscape mode.
I have added ScrollController _controller; Do i have to create _controller class that listern the scrolling action?
In my understanding, you want to be able to get 2 scrolling. 1. using SingleChildScrollView and inside that Widget, you want to be able to scroll the bottom layer, thus you use ListView. To make it work, you have to place your ListView inside widget that has certain height. Example this implementation is:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
SizedBox(child: Text('Upper scrollable'), height: 450),
Divider(
height: 10,
thickness: 2,
),
Container(
height: 350,
child: ListView(
shrinkWrap: true,
children: <Widget>[
Container(
color:Colors.red,
child: SizedBox(child: Text('Bottom scrollable'), height: 450),
),
],
),
)
],
),
),
If you don't want to use 2 scroll, don't use ListView inside SingleChildScrollView.
ListView cannot be wrapped with SingleChildScrollView remove it
surround ListView with Expanded Widget
try one of the two alternatives.