Open Screen from TabView Flutter not Fullscreen - tabs

I have a view as attach files
body: TabBarView(
controller: _tabController,
children: [
TabSreen(index: _tabController.index, eventId: widget.eventEntity.eventId),
TabScreen(index: _tabController.index, eventId: widget.eventEntity.eventId)
]
),
TabScreen is StatefulWiget,
Click on each item in List of TabScreen, open to SecondScreen
How to make the second screen show as fullscreen. I mean the SecondView should remove the part: Event1, Event Name, Status. Just showing the view with below navigation as Fullscreen
Currently, I am using following code to open the SecondScreen (StatefulWiget) from TabScreen
Navigator.push(
context,
MaterialPageRoute(builder: (context) => new SecondScreen(title: _forms[index].name)),
);

Here is a simple example since you didn't share enough code, you can compare your code with this.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test',
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Color(0xFF048ec8),
indicatorColor: Colors.red,
cursorColor: Colors.red,
),
home: MainScreenWithTab(),
);
}
}
class MainScreenWithTab extends StatefulWidget {
#override
State<StatefulWidget> createState() => MainScreenWithTabState();
}
class MainScreenWithTabState extends State<MainScreenWithTab> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Screen'),
),
body: Column(
children: <Widget>[
TabBar(
tabs: <Widget>[
Tab(
text: 'Left',
),
Tab(
text: 'Right',
)
],
),
Expanded(
child: TabBarView(children: [
RaisedButton(
child: Text('Tap for new screen'),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Screen()));
},
),
FlatButton(
child: Text('Push View 2'),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Screen()));
},
),
]),
),
],
),
),
);
}
}
class Screen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Screen'),
),
body: Container(
width: double.infinity,
height: double.infinity,
color: Colors.yellow,
child: Center(
child: Text('New Screen'),
),
),
);
}
}

Navigator.of(context,rootNavigator: true)
.push(
MaterialPageRoute(
builder: (context) => PDFScreen(path: pathPDF.path),
),
);
You should allow the screen a new navigator, try the above code, it should work now.

Related

Flutter local json list view navigation not working

i have retrieving json data locally and negative to single screen in flutter
Make an asset folder in your project root directory and put my JSON file into that.
Entry the JSON file into pubspec.yaml file
Made a method to read the JSON file into your flutter application
List Screen
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' as rootBundle;
import 'package:license_app/data/data.dart';
import 'package:license_app/model/pqtnj_model.dart';
import 'package:license_app/page/detail.dart';
class MyList extends StatelessWidget {
MyList({Key? key}) : super(key: key);
//final list = Pquestion.generate();
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: ReadJsonData(),
builder: (context, data) {
if (data.hasData) {
var items = data.data as List<PjQuestion>;
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
contentPadding: const EdgeInsets.all(15.0),
leading: CircleAvatar(
backgroundColor: Colors.blue.shade400,
child: Text(
items[index].id.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
title: Text(
items[index].question.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return DetailScreen(snapshot.lists[index]);
}));
},
),
elevation: 5,
margin: const EdgeInsets.all(10),
shadowColor: Colors.black12,
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: const BorderSide(color: Colors.white)),
);
});
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
));
}
Future<List<PjQuestion>> ReadJsonData() async {
final jsondata =
await rootBundle.rootBundle.loadString('assets/json/pquestion.json');
final list = json.decode(jsondata) as List<dynamic>;
return list.map((e) => PjQuestion.fromJson(e)).toList();
}
}
on Tab is not navigating
the error i am getting now
"Undefined name 'snapshot'.
Try correcting the name to one that is defined, or defining the name."
Detail Screen
import 'package:flutter/material.dart';
import 'package:license_app/data/data.dart';
class DetailScreen extends StatelessWidget {
final Pquestion pquestion;
const DetailScreen(this.pquestion, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(pquestion.question),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Row(
children: <Widget>[
Expanded(
child: Text(
pquestion.answer,
style: const TextStyle(fontSize: 20.0, color: Colors.black),
overflow: TextOverflow.visible,
),
)
],
)),
);
}
}
when you tap in the first screen to load the detail screen it actually sends a data with it self which you literally changed its name to data instead of snapshot, and you initialized data to items so,
try this:
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return DetailScreen(items[index]);
}));
},

how to call a function in flutter from another page

I'm new to flutter and i was working on a small poc project. All I Want is that to call a function which is in second page from my first page using abutton click. here what i had done,
1st page
class Mainpage extends StatefulWidget {
#override
_MainpageState createState() => _MainpageState();
}
class _MainpageState extends State<Mainpage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: Padding(
padding: EdgeInsets.only(left: 12),
child: IconButton(
icon: Icon(Icons.menu,
color: Colors.grey[500],
size: 30,),
onPressed: () {
print('Click leading');
},
),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
Text('Basic AppBar'),
]
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.notifications,
color: Colors.grey[500],
size: 30,),
onPressed: () {
Navigator.pushNamed(context, '/notifications');
},
),
],
),
body:
Container(
padding: EdgeInsets.fromLTRB(10,10,10,0),
child: Column(
children:<Widget>[
Row(
children:<Widget>[
]),
SizedBox(height: 60),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
GestureDetector(
child: Image.asset('assets/cam.png',
height:90),
onTap: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
elevation: 16,
child: Container(
height: 180.0,
width: 330.0,
child: ListView(
children: <Widget>[
SizedBox(height: 20),
//Center(
Padding(
padding: const EdgeInsets.only(left:15.0),
child: Text(
"Add a Receipt",
textAlign: TextAlign.left,
style: TextStyle(fontSize: 24, color: Colors.black, fontWeight: FontWeight.bold),
),
),
// ),
SizedBox(height: 20),
FlatButton(
child: Text(
'Take a photo..',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 20),
),
onPressed: () {
});
i don't know want to give in the onpressed function at the end of the above code
and the 2nd page is as follow
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _selectedFile;
bool _inProcess = false;
Map data = {};
Widget getImageWidget() {
if (_selectedFile != null) {
return Image.file(
_selectedFile,
width: 350,
height: 650,
fit: BoxFit.cover,
);
} else {
return Image.asset(
"assets/splashlogo.png",
width: 350,
height: 650,
fit: BoxFit.cover,
);
}
}
getImage(ImageSource source) async {
this.setState((){
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
maxWidth: 1080,
maxHeight: 1080,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.black,
toolbarWidgetColor: Colors.white,
//toolbarTitle: "RPS Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.black,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false
),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
)
);
this.setState((){
_selectedFile = cropped;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
}
i needed to call getImage(ImageSource.camera); inside the my onpress function in the 1st page which points to the getimage function on second page.
can anyone help me with it..?
here add this in you 1st page in onpressed
Navigator.pushReplacementNamed(context,'/2ndpage',arguments: {
'pickerCode': "0",
});
and on the second page you do
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
data = ModalRoute.of(context).settings.arguments;
print(data);
if(data['pickerCode']=="0"){
getImage(ImageSource.camera);
}
});
}
this is a tricky thing but I think it will help you.
Use a GlobalKey.
GlobalKey<_MyHomePageState> globalImageKey = GlobalKey();
Change this:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}): super(key:key)
#override
_MyHomePageState createState() => _MyHomePageState();
}
when using MyHomePage:
MyHomePage(key: globalImageKey)
call:
globalImageKey.currentState.getImage(ImageSource.camera);

Flutter switch widget- I ony want it to execute the function when it's active, what to do?

I have a problem with the switch widget in flutter. I only want to execute the onChanged function when I activate it but every time I click on the switch even when it's not active, it executes the function and I have the popup menu that appears.
new Switch(
value: false,
onChanged: (bool isOn) {
if(isOn){
setState(() {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
key: _alertDialogKey,
contentPadding: EdgeInsets.only(left: 25, right: 25),
title: Center(
child: Text("Choisissez une filiale")
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20.0)),
),
content: Container(
height: 350,
width: 300,
child: ListView.builder(
itemCount: litems.length,
itemBuilder: (_, index) {
return RaisedButton(
onPressed: () => popupAppuieSurUneFiliale( index)
//changementAffiliation(litems[index]),
child: Text(
litems[index],
style: TextStyle(color: Colors.white),
),
color: Colors.black,
);
}
),
),
actions:[
RaisedButton(
child: Text("Annuler",),
onPressed: (){
Navigator.of(context).pop();
},
color: Colors.blue,
),
]
);
}
);
});
} else(){
};
}
);
Demo
You can copy paste run full code below
You can declare a bool _isOn and set to false and then in onChanged change value
code snippet
bool _isOn = false;
...
Switch(
value: _isOn,
onChanged: (bool isOn) {
setState(() {
_isOn = isOn;
});
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<String> litems = ["test"];
bool _isOn = false;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: _isOn,
onChanged: (bool isOn) {
setState(() {
_isOn = isOn;
});
if (isOn) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
//key: _alertDialogKey,
contentPadding:
EdgeInsets.only(left: 25, right: 25),
title:
Center(child: Text("Choisissez une filiale")),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0)),
),
content: Container(
height: 350,
width: 300,
child: ListView.builder(
itemCount: litems.length,
itemBuilder: (_, index) {
return RaisedButton(
onPressed: () => null,
//changementAffiliation(litems[index]),
child: Text(
litems[index],
style: TextStyle(color: Colors.white),
),
color: Colors.black,
);
}),
),
actions: [
RaisedButton(
child: Text(
"Annuler",
),
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blue,
),
]);
});
} else
() {};
}),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter Navigation to new page throwing error

I have created Gridview builder through JSON data but when i navigate to new Page, I am getting Error: Could not find the correct Provider above this SingleItemScreen Widget
To fix, please:
Ensure the Provider is an ancestor to this SingleItemScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Ensure the correct context is being used.
I am not sure where I am going wrong with this.
List<Product> productFromJson(String str) => List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
String productToJson(List<Product> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Product {
String productId;
String sku;
String itemName;
String listPrice;
String publishedPrice;
String onsale;
String stockQuantity;
StockStatus stockStatus;
String ratingCount;
String averageRating;
String totalSales;
String imagePath;
String category;
Product({
this.productId,
this.sku,
this.itemName,
this.listPrice,
this.publishedPrice,
this.onsale,
this.stockQuantity,
this.stockStatus,
this.ratingCount,
this.averageRating,
this.totalSales,
this.imagePath,
this.category,
});
factory Product.fromJson(Map<String, dynamic> json) => Product(
productId: json["product_id"],
sku: json["sku"],
itemName: json["item_name"],
listPrice: json["list_price"],
publishedPrice: json["published_price"],
onsale: json["onsale"],
stockQuantity: json["stock_quantity"],
stockStatus: stockStatusValues.map[json["stock_status"]],
ratingCount: json["rating_count"],
averageRating: json["average_rating"],
totalSales: json["total_sales"],
imagePath: json["image_path"],
category: json["category"],
);
Map<String, dynamic> toJson() => {
"product_id": productId,
"sku": sku,
"item_name": itemName,
"list_price": listPrice,
"published_price": publishedPrice,
"onsale": onsale,
"stock_quantity": stockQuantity,
"stock_status": stockStatusValues.reverse[stockStatus],
"rating_count": ratingCount,
"average_rating": averageRating,
"total_sales": totalSales,
"image_path": imagePath,
"category": category,
};
}
enum StockStatus { INSTOCK }
final stockStatusValues = EnumValues({
"instock": StockStatus.INSTOCK
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
Future<List<Product>> fetchPhotos(http.Client client) async {
final response =
await client.get('http://flutter.bizsupplier.in/product.php');
return compute(parsePhotos, response.body);
}
Future<List<Product>> parsePhotos(String responseBody) async {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Product>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
if (snapshot.hasData) {
return PhotosList(product: snapshot.data);
} else {
return Center(child: CircularProgressIndicator());
}
},
);
}
}
class PhotosList extends StatelessWidget {
final List<Product> product;
PhotosList({Key key, this.product}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: product.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: <Widget>[
Container(
height: 150,
child: GestureDetector(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SingleItemScreen(),
settings: RouteSettings(
arguments: product[index]
)
)
);
},
child: Image.network(product[index].imagePath)),
),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {},
child: Text('Buy Now'),
color: Colors.redAccent,
),
],
),
)
],
),
);
},
);
}
}
class SingleItemScreen extends StatelessWidget {
final List<Product> product;
SingleItemScreen({Key key, this.product}) : super(key: key);
#override
Widget build(BuildContext context) {
final Product product = Provider.of<Product>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: Text('Test PhP Navigation'),
actions: <Widget>[
new IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {}),
new IconButton(
icon: Icon(
Icons.shopping_cart,
color: Colors.white,
),
onPressed: () {}),
],
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: 300,
child: Image.network(product.imagePath),
),
Container(
child: Text(product.productId),
),
],
),
),
bottomNavigationBar: Container(
width: MediaQuery.of(context).size.width,
height: 50.0,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Flexible(
fit: FlexFit.tight,
flex: 1,
child: RaisedButton(
onPressed: () {},
color: Colors.grey,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.list,
color: Colors.white,
),
SizedBox(
width: 4.0,
),
Text(
"SAVE",
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
Flexible(
flex: 2,
child: RaisedButton(
onPressed: (){},
color: Colors.greenAccent,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.card_travel,
color: Colors.white,
),
SizedBox(
width: 4.0,
),
Text(
"ADD TO BAG",
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
],
),
));
}
}
You can copy paste run full code below
Step 1: remark settings and use SingleItemScreen(product: product[index])
MaterialPageRoute(
builder: (context) =>
SingleItemScreen(product: product[index]),
/*settings: RouteSettings(
arguments: product[index]
)*/
));
Step 2: Modify SingleItemScreen to accept product
class SingleItemScreen extends StatelessWidget {
final Product product;
SingleItemScreen({Key key, this.product}) : super(key: key);
Step 3: Remark Provider
//final Product product = Provider.of<Product>(context, listen: false);
working demo
full code
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<Product> productFromJson(String str) =>
List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
String productToJson(List<Product> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Product {
String productId;
String sku;
String itemName;
String listPrice;
String publishedPrice;
String onsale;
String stockQuantity;
StockStatus stockStatus;
String ratingCount;
String averageRating;
String totalSales;
String imagePath;
String category;
Product({
this.productId,
this.sku,
this.itemName,
this.listPrice,
this.publishedPrice,
this.onsale,
this.stockQuantity,
this.stockStatus,
this.ratingCount,
this.averageRating,
this.totalSales,
this.imagePath,
this.category,
});
factory Product.fromJson(Map<String, dynamic> json) => Product(
productId: json["product_id"],
sku: json["sku"],
itemName: json["item_name"],
listPrice: json["list_price"],
publishedPrice: json["published_price"],
onsale: json["onsale"],
stockQuantity: json["stock_quantity"],
stockStatus: stockStatusValues.map[json["stock_status"]],
ratingCount: json["rating_count"],
averageRating: json["average_rating"],
totalSales: json["total_sales"],
imagePath: json["image_path"],
category: json["category"],
);
Map<String, dynamic> toJson() => {
"product_id": productId,
"sku": sku,
"item_name": itemName,
"list_price": listPrice,
"published_price": publishedPrice,
"onsale": onsale,
"stock_quantity": stockQuantity,
"stock_status": stockStatusValues.reverse[stockStatus],
"rating_count": ratingCount,
"average_rating": averageRating,
"total_sales": totalSales,
"image_path": imagePath,
"category": category,
};
}
enum StockStatus { INSTOCK }
final stockStatusValues = EnumValues({"instock": StockStatus.INSTOCK});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
Future<List<Product>> fetchPhotos(http.Client client) async {
final response =
await client.get('http://flutter.bizsupplier.in/product.php');
return compute(parsePhotos, response.body);
}
Future<List<Product>> parsePhotos(String responseBody) async {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Product>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
if (snapshot.hasData) {
return PhotosList(product: snapshot.data);
} else {
return Center(child: CircularProgressIndicator());
}
},
);
}
}
class PhotosList extends StatelessWidget {
final List<Product> product;
PhotosList({Key key, this.product}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: product.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: <Widget>[
Container(
height: 150,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
SingleItemScreen(product: product[index]),
/*settings: RouteSettings(
arguments: product[index]
)*/
));
},
child: Image.network(product[index].imagePath)),
),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {},
child: Text('Buy Now'),
color: Colors.redAccent,
),
],
),
)
],
),
);
},
);
}
}
class SingleItemScreen extends StatelessWidget {
final Product product;
SingleItemScreen({Key key, this.product}) : super(key: key);
#override
Widget build(BuildContext context) {
//final Product product = Provider.of<Product>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: Text('Test PhP Navigation'),
actions: <Widget>[
new IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {}),
new IconButton(
icon: Icon(
Icons.shopping_cart,
color: Colors.white,
),
onPressed: () {}),
],
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: 300,
child: Image.network(product.imagePath),
),
Container(
child: Text(product.productId),
),
],
),
),
bottomNavigationBar: Container(
width: MediaQuery.of(context).size.width,
height: 50.0,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Flexible(
fit: FlexFit.tight,
flex: 1,
child: RaisedButton(
onPressed: () {},
color: Colors.grey,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.list,
color: Colors.white,
),
SizedBox(
width: 4.0,
),
Text(
"SAVE",
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
Flexible(
flex: 2,
child: RaisedButton(
onPressed: () {},
color: Colors.greenAccent,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.card_travel,
color: Colors.white,
),
SizedBox(
width: 4.0,
),
Text(
"ADD TO BAG",
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
],
),
));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}

Close drawer automatically return MaterialApp and Scaffold black screen after Navigator.pop(context);

Hy Guys I'm trying try to close drawer inside material app but it is not working. My code:
#override
Widget build(BuildContext context) {
return MaterialApp(
home: currentLocation == null ? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
):
Scaffold(
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(leading: Icon(Icons.multiline_chart), title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}
),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(currentLocation.latitude,
currentLocation.longitude), zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
)
);
}
But when i press list item 1 ( checkgps ) Navigator.pop(context); going to black screen and not see google maps. Any idea?
I am assuming that you are calling this widget directly from you run app and because of that it is causing error.
Your appbar was also at wrong place.
checkout below code.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(body: DeleteWidget()),
);
}
}
class DeleteWidget extends StatefulWidget {
const DeleteWidget({Key key}) : super(key: key);
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
#override
Widget build(BuildContext context) {
return currentLocation == null
? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
)
: Scaffold(
drawer: Drawer(
child: ListView(children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(
leading: Icon(Icons.multiline_chart),
title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}),
]),
),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(
currentLocation.latitude, currentLocation.longitude),
zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
),
);
}
}
The problem is that you are not popping the Drawer's context, you are popping the MaterialApp's context.
Also it is a good idea to split your app into small piece of widgets, so your drawer content must be placed in another widget. I've made these changes, try out this code:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(body: DeleteWidget()),
);
}
}
class DeleteWidget extends StatefulWidget {
const DeleteWidget({Key key}) : super(key: key);
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
#override
Widget build(BuildContext context) {
return currentLocation == null
? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
)
: Scaffold(
drawer: _DrawerContent(),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(
currentLocation.latitude, currentLocation.longitude),
zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
),
);
}
}
class _DrawerContent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(
leading: Icon(Icons.multiline_chart),
title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}),
]),
);
}
}
With the Drawer content in another widget when you call Navigator.pop(context); it will pop the drawer context not the Page context where the Drawer is.
Instead of calling navigator.pop you can use
Navigator.of(context).maybePop();