flutter: navigator.pop() is not working properly in my code - flutter

I have code below in flutter and when i press on back arrow button it crashes the app and white screen appear however in appears by default in other pages and i implemented it in other pages manually ... can someone please tell me what is the problem here cuz i couldn't figure it out?
thanks in advance
// ignore_for_file: avoid_function_literals_in_foreach_calls, prefer_const_constructors, prefer_const_literals_to_create_immutables, use_key_in_widget_constructors, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, sized_box_for_whitespace, deprecated_member_use, file_names
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
// ignore: unused_import
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
// ignore: unused_import
import 'package:localize_and_translate/localize_and_translate.dart';
import 'package:menu_app/About.dart';
void main() => runApp(HotDrinks());
class HotDrinks extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var screenHeight = MediaQuery.of(context).size.height;
var screenWidth = MediaQuery.of(context).size.width;
Future<List<Widget>> createList() async {
List<Widget> items = <Widget>[];
String dataString = await rootBundle
.loadString(translator.translate("assets/hotDrinks.json"));
List<dynamic> dataJSON = jsonDecode(dataString);
dataJSON.forEach((object) {
String finalString = "";
List<dynamic> dataList = object["placeItems"];
dataList.forEach((item) {
finalString = finalString + item + " | ";
});
items.add(Padding(
padding: EdgeInsets.all(2.0),
child: Container(
decoration: BoxDecoration(
color: Color.fromRGBO(255, 255, 255, 0.7),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.black12,
spreadRadius: 2.0,
blurRadius: 5.0),
]),
margin: EdgeInsets.all(5.0),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ClipRRect(
child: Image.asset(
object["placeImage"],
fit: BoxFit.cover,
width: 280,
height: 180,
),
),
SizedBox(
width: 250,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
translator.translate(object["placeName"]),
style: GoogleFonts.elMessiri(
textStyle: TextStyle(
fontSize: 15.0, color: Colors.black54)),
),
Text(
translator.translate(" ${object["minOrder"]} IQD"),
style:
TextStyle(fontSize: 12.0, color: Colors.black54),
)
],
),
),
)
],
),
),
));
});
return items;
}
return Scaffold(
appBar: AppBar(
backgroundColor: HexColor("#242424"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
iconSize: 20.0,
onPressed: () {
Navigator.pop(context); //not working
},
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
fit: BoxFit.contain,
height: 40,
),
],
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // set min
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/backg.png"),
fit: BoxFit.cover,
),
),
height: 3000,
width: screenWidth,
child: FutureBuilder<List<Widget>>(
initialData: [Text("")],
future: createList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Text("Loading");
if (snapshot.hasError) {
return Text("Error ${snapshot.error}");
}
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(8.0),
child: GridView.count(
childAspectRatio: 1, // items' width/height
crossAxisCount: 2,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
// ignore: sdk_version_ui_as_code
...?snapshot.data,
],
));
} else {
return CircularProgressIndicator();
}
}),
)
],
),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
backgroundColor: Colors.black,
child: Icon(
MdiIcons.information,
color: Colors.white,
)),
);
}
}

It's because there's nothing "underneath" MyHomePage.
Here's how routing works in Flutter - think of it as a stack of screens. The initial route (bottom of the stack) is the first screen you see when you open the app, in your case it's MyHomePage. If you push a route on top of this screen, the old screen (MyHomePage) is still there, but hidden underneath the new screen that you just pushed. So if you use pop() in this new screen, it will kill it and take you back to the route that's underneath - MyHomePage.
In your example, when you open the app, the home screen is MyHomePage and there's nothing underneath, hence why there's nothing to display.
To visualise this, take a look at this video at the 11:00 mark.

Related

Flutter: responsive height and width

in my flutter code below i'm suffering from height and width problem which appears different on each device, for ex in my below code i set a background image and it appears on half screen if i didn't set a height, and ofc this height appears different on each device.
also in child: Image.asset( object["placeImage"], fit: BoxFit.cover,width: 280,height: 180,) i wanted the image to appear one size on all devices without setting a specific height and width.. is there a way to do this in flutter?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:localize_and_translate/localize_and_translate.dart';
import 'package:menu_app/About.dart';
import 'package:menu_app/Drinks.dart';
import 'package:flutter/gestures.dart';
class FoodDetailsPage extends StatefulWidget {
final String pageId;
//The string of each meal will be passed when calling this page.
FoodDetailsPage({required this.pageId});
#override
_FoodDetailsPageState createState() => _FoodDetailsPageState();
}
class _FoodDetailsPageState extends State<FoodDetailsPage> {
late Future<List<Widget>> myCreateList;
#override
void initState() {
super.initState();
myCreateList = createList();
//THIS IS NECESSARY TO AVOID THE FUTUREBUILDER FROM FIRING EVERYTIME THE PAGE REBUILDS.
// You can check more at
// https://stackoverflow.com/questions/57793479/flutter-futurebuilder-gets-constantly-called
}
Future<List<Widget>> createList() async {
List<Widget> items = <Widget>[];
String dataString = await rootBundle.loadString(translator.translate(
"assets/${widget.pageId}.json")); //view JSON file depending on pageId
List<dynamic> dataJSON = jsonDecode(dataString);
dataJSON.forEach((object) {
String finalString = "";
List<dynamic> dataList = object["placeItems"];
dataList.forEach((item) {
finalString = finalString + item + " | ";
});
items.add(Padding(
padding: EdgeInsets.all(2.0),
child: Container(
decoration: BoxDecoration(
color: Color.fromRGBO(255, 255, 255, 0.7),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.black12, spreadRadius: 2.0, blurRadius: 5.0),
]),
margin: EdgeInsets.all(5.0),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
child: Image.asset(
object["placeImage"], // also here i need to set a astatic height and width on each device
fit: BoxFit.cover,
width: 280,
height: 180,
),
),
SizedBox(
width: 250,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
translator.translate(object["placeName"]),
style: GoogleFonts.elMessiri(
textStyle: TextStyle(
fontSize: 15.0, color: Colors.black54)),
),
// Padding(
// padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
// child: Text(
// finalString,
// overflow: TextOverflow.ellipsis,
// style: TextStyle(
// fontSize: 12.0,
// color: Colors.black54,
// ),
// maxLines: 1,
// ),
// ),
Text(
translator.translate(" ${object["minOrder"]} IQD"),
style: TextStyle(fontSize: 12.0, color: Colors.black54),
)
],
),
),
)
],
),
),
));
});
return items;
}
Widget build(BuildContext context) {
// ignore: unused_local_variable
var size = MediaQuery.of(context).size;
var screenHeight = MediaQuery.of(context).size.height;
var screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: HexColor("#242424"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
iconSize: 20.0,
onPressed: () {
Navigator.pop(context);
},
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
fit: BoxFit.contain,
height: 40,
),
],
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // set min
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/images/backg.png", // i have to set a static height for each device to get the full backfround
),
fit: BoxFit.fill)),
height: 3000,
width: screenWidth,
child: FutureBuilder<List<Widget>>(
initialData: [Text("")],
future: myCreateList,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Text(translator.translate("Loading"));
if (snapshot.hasError) {
return Text("Error ${snapshot.error}");
}
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(8.0),
child: GridView.count(
childAspectRatio: 1, // items' width/height
crossAxisCount: 2,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
// ignore: sdk_version_ui_as_code
...?snapshot.data,
],
));
} else {
return CircularProgressIndicator();
}
}),
)
],
),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
backgroundColor: Colors.black,
child: Icon(
MdiIcons.information,
color: Colors.white,
)),
);
}
}
if you want you image to same size in every device wrap it with a container and give static height and width use the fit property according to your needs but if you want the size of the image should change according to device height and width you can use media query for that ....for eg
Container(
color: Colors.yellow,
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width,
)
put your image in child parameter ......
let me know if this help

flutter: GridView not showing properly

i'm trying to create a restaurant menu app in flutter language, and i wanted to view my saved data inside json file as gridView but sadly i'm getting error while running the app.. However, i tried to change the gridView to listView and its showing good..
so is there a way to show them as gridView?
thanks in advance
[
{
"placeImage": "assets/images/wood.jpg",
"placeName": "The Hawkers",
"placeItems": ["Burgers","Chinese","Fast Food","Italian","Juice"],
"minOrder": 20
},
{
"placeImage": "assets/images/wood.jpg",
"placeName": "Flipping Noodles",
"placeItems": ["Burgers","Chinese","Fast Food","Italian","Juice"],
"minOrder": 50
},
{
"placeImage": "assets/images/wood.jpg",
"placeName": "Pizza Hut",
"placeItems": ["Pizza","Chinese","Fast Food","Italian","Juice"],
"minOrder": 20
},
{
"placeImage": "assets/images/wood.jpg",
"placeName": "Blue Hill",
"placeItems": ["Burgers","Chinese","Fast Food","Italian","Juice"],
"minOrder": 40
},
{
"placeImage": "imagess/bluehill.jpg",
"placeName": "Blue Hill",
"placeItems": ["Burgers","Chinese","Fast Food","Italian","Juice"],
"minOrder": 40
}
]
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
void main() => runApp(Breakfast());
class Breakfast extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
var bannerItems = ["Burger", "Cheese Chilly", "Noodles", "Pizza"];
var bannerImage = [
"images/burger.jpg",
"images/cheesechilly.jpg",
"images/noodles.jpg",
"images/pizza.jpg"
];
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var screenHeight = MediaQuery.of(context).size.height;
var screenWidth = MediaQuery.of(context).size.width;
Future<List<Widget>> createList() async {
List<Widget> items = new List<Widget>();
String dataString =
await DefaultAssetBundle.of(context).loadString("assets/data.json");
List<dynamic> dataJSON = jsonDecode(dataString);
dataJSON.forEach((object) {
String finalString = "";
List<dynamic> dataList = object["placeItems"];
dataList.forEach((item) {
finalString = finalString + item + " | ";
});
items.add(Padding(
padding: EdgeInsets.all(2.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.black12,
spreadRadius: 2.0,
blurRadius: 5.0),
]),
margin: EdgeInsets.all(5.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0),
bottomLeft: Radius.circular(10.0)),
child: Image.asset(
object["placeImage"],
width: 80,
height: 80,
fit: BoxFit.cover,
),
),
SizedBox(
width: 250,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(object["placeName"]),
Padding(
padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
child: Text(
finalString,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
maxLines: 1,
),
),
Text(
"Min. Order: ${object["minOrder"]}",
style:
TextStyle(fontSize: 12.0, color: Colors.black54),
)
],
),
),
)
],
),
),
));
});
return items;
}
return Scaffold(
body: Container(
height: screenHeight,
width: screenWidth,
child: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(icon: Icon(Icons.menu), onPressed: () {}),
Text(
"Foodies",
style: TextStyle(fontSize: 50, fontFamily: "Samantha"),
),
IconButton(icon: Icon(Icons.person), onPressed: () {})
],
),
),
BannerWidgetArea(),
Container(
child: FutureBuilder(
initialData: <Widget>[Text("")],
future: createList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(8.0),
child: GridView.count(
crossAxisCount: 3,
crossAxisSpacing: 4.0,
mainAxisSpacing: 2.0,
children: snapshot.data,
),
);
} else {
return CircularProgressIndicator();
}
}),
)
],
),
)),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.black,
child: Icon(
MdiIcons.food,
color: Colors.white,
)),
);
}
}
class BannerWidgetArea extends StatelessWidget {
#override
Widget build(BuildContext context) {
var screenWidth = MediaQuery.of(context).size.width;
PageController controller =
PageController(viewportFraction: 0.8, initialPage: 1);
List<Widget> banners = new List<Widget>();
for (int x = 0; x < bannerItems.length; x++) {
var bannerView = Padding(
padding: EdgeInsets.all(10.0),
child: Container(
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
boxShadow: [
BoxShadow(
color: Colors.black38,
offset: Offset(2.0, 2.0),
blurRadius: 5.0,
spreadRadius: 1.0)
]),
),
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
child: Image.asset(
bannerImage[x],
fit: BoxFit.cover,
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black])),
),
Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
bannerItems[x],
style: TextStyle(fontSize: 25.0, color: Colors.white),
),
Text(
"More than 40% Off",
style: TextStyle(fontSize: 12.0, color: Colors.white),
)
],
),
)
],
),
),
);
banners.add(bannerView);
}
return Container(
width: screenWidth,
height: screenWidth * 9 / 16,
child: PageView(
controller: controller,
scrollDirection: Axis.horizontal,
children: banners,
),
);
}
}
Firstly I would prefer having data from Future instead of <Widget> and will avoid forEach method to handle complex and bigger computation.
Lets processed with current condition of code-structure. According to your question, main issue is using ListView/GridView.
While SingleChildScrollView is handling the scroll, use GridView.count or ListView
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
About the top level-column
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // set min
children: <Widget>[
To check error, define states of FutureBuilder
child: FutureBuilder<List<Widget>>(
initialData: [Text("")],
future: createList(context),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Text("Loading");
if (snapshot.hasError) {
return Text("Error ${snapshot.error}");
}
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(8.0),
child: GridView.count(
childAspectRatio: 1 // items' width/height
crossAxisCount: 3,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
...snapshot.data!,
],
),
To load JSON, I've used like String dataString = await rootBundle.loadString("json/data.json");
To handle item size use childAspectRatio.
Assuming you don't have issue with loading images/BannerWidgetArea() widgets.
Does it solve the issue?

large image when clicking - flutter

I have an algorithm working, and I need to click on the image to show it on the entire screen, I have not succeeded, I send all the code, add a comment "// THIS IS THE IMAGE I NEED TO LOOK BIG WHEN I CLICK" which is the image that I want to make it look large when I click it, I have tried in several ways but I have not been able to solve it, and the only thing I am missing is this functionality.
import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:tienda/models/productos_model.dart';
import 'package:tienda/pages/otra_pagina.dart';
import 'package:tienda/pages/crear_productos.dart';
import 'package:tienda/pages/pedido_lista.dart';
import 'package:tienda/services/firebase_services.dart';
import 'package:tienda/widgets/header.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
//title: 'Flutter Demo',
theme: ThemeData(
//primarySwatch: Colors.yellow,
primaryColor: Colors.yellow[800],
),
home: MyHomePage(title: 'RETO SAN JOSE CHAPARRAL'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<ProductosModel> _productosModel = List<ProductosModel>();
List<ProductosModel> _listaCarro = [];
FirebaseService db = new FirebaseService();
StreamSubscription<QuerySnapshot> productSub;
#override
void initState() {
super.initState();
_productosModel = new List();
productSub?.cancel();
productSub = db.getProductList().listen((QuerySnapshot snapshot) {
final List<ProductosModel> products = snapshot.documents
.map((documentSnapshot) =>
ProductosModel.fromMap(documentSnapshot.data))
.toList();
setState(() {
this._productosModel = products;
});
});
}
#override
void dispose() {
productSub?.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 16.0, top: 8.0),
child: GestureDetector(
child: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
Icon(
Icons.shopping_cart,
size: 38,
),
if (_listaCarro.length > 0)
Padding(
padding: const EdgeInsets.only(left: 2.0),
child: CircleAvatar(
radius: 8.0,
backgroundColor: Colors.red,
foregroundColor: Colors.white,
child: Text(
_listaCarro.length.toString(),
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 12.0),
),
),
),
],
),
onTap: () {
if (_listaCarro.isNotEmpty)
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Cart(_listaCarro),
),
);
},
),
)
],
),
drawer: Container(
width: 170.0,
child: Drawer(
child: Container(
width: MediaQuery.of(context).size.width * 0.5,
//color: Colors.black, //color de menu principal
color: Colors.yellow[800],
child: new ListView(
padding: EdgeInsets.only(top: 30.0),
children: <Widget>[
Container(
height: 120,
child: new UserAccountsDrawerHeader(
accountName: new Text(''),
accountEmail: new Text(''),
decoration: new BoxDecoration(
image: new DecorationImage(
fit: BoxFit.fill,
image: AssetImage('assets/images/food1x.png'),
),
),
),
),
new Divider(),
new ListTile(
title: new Text(
'productos',
style: TextStyle(color: Colors.white),
),
trailing: new Icon(
Icons.fastfood,
size: 30.0,
color: Colors.white,
),
onTap: () =>
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) => CrearProductos(),
)),
),
new Divider(),
],
),
),
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
WaveClip(),
Container(
color: Colors.transparent,
padding: const EdgeInsets.only(left: 24, top: 48),
height: 170,
child: ListView.builder(
itemCount: _productosModel.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Row(
children: <Widget>[
Container(
height: 300,
padding: new EdgeInsets.only(
left: 10.0, bottom: 10.0),
child: Card(
elevation: 7.0,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(24)),
child: AspectRatio(
aspectRatio: 1,
child: CachedNetworkImage(
imageUrl:
'${_productosModel[index].image}' +
'?alt=media',
fit: BoxFit.cover,
placeholder: (_, __) {
return Center(
child:
CupertinoActivityIndicator(
radius: 15,
));
}),
),
),
),
],
);
},
))
],
),
Container(height: 3.0, color: Colors.grey),
SizedBox(
height: 5.0,
),
Container(
color: Colors.grey[300],
height: MediaQuery.of(context).size.height / 1.5,
child: GridView.builder(
padding: const EdgeInsets.all(4.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: _productosModel.length,
itemBuilder: (context, index) {
final String imagen = _productosModel[index].image;
var item = _productosModel[index];
return Card(
elevation: 4.0,
child: Stack(
fit: StackFit.loose,
alignment: Alignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: CachedNetworkImage(
// THIS IS THE IMAGE I NEED TO LOOK BIG WHEN I CLICK
imageUrl:
'${_productosModel[index].image}' +
'?alt=media',
fit: BoxFit.cover,
placeholder: (_, __) {
return Center(
child:
CupertinoActivityIndicator(
radius: 15,
));
}),
),
Text(
'${_productosModel[index].name}',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20.0),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
SizedBox(
height: 25,
),
Text(
'${_productosModel[index].price.toString()}COP',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.black),
),
Padding(
padding: const EdgeInsets.only(
right: 8.0,
bottom: 8.0,
),
child: Align(
alignment: Alignment.bottomRight,
child: GestureDetector(
child: (!_listaCarro
.contains(item))
? Icon(
Icons.shopping_cart,
color: Colors.yellow[800],
size: 38,
)
: Icon(
Icons.shopping_cart,
color: Colors.red,
size: 38,
),
onTap: () {
setState(() {
if (!_listaCarro
.contains(item))
_listaCarro.add(item);
else
_listaCarro.remove(item);
});
},
),
),
),
],
)
],
),
],
));
},
)),
],
),
)),
));
}
}
Another solution is to show the larger image on the same screen using the dialog below.
InkWell(
onTap: () => showDialog(
builder: (BuildContext context) => AlertDialog(
backgroundColor: Colors.transparent,
insetPadding: EdgeInsets.all(2),
title: Container(
decoration: BoxDecoration(),
width: MediaQuery.of(context).size.width,
child: Expanded(
child: Image.network(
'${_productosModel[index].image}' +
'?alt=media',
fit: BoxFit.fitWidth,
),
),
),
),
context: context),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
BaseUrl.host + posts!.imageUrl!,
fit: BoxFit.cover,
),
),
)
You can create a new page, wrap the image widget in a InkWell widget, and when tapped navigate to the new page showing the image.
EDIT:
Your widget image would become:
// THIS IS THE IMAGE I NEED TO LOOK BIG WHEN I CLICK
return InkWell(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => ImageScreen(
url: '${_productosModel[index].image}' + '?alt=media',
),
),
),
child: Expanded(
child: CachedNetworkImage(
imageUrl: '${_productosModel[index].image}' + '?alt=media',
fit: BoxFit.cover,
placeholder: (_, __) {
return Center(
child: CupertinoActivityIndicator(
radius: 15,
),
);
},
),
),
),
And then you create a new stateless widget which it builds a:
import 'package:flutter/material.dart';
class ImageScreen extends StatelessWidget {
final String? url;
ImageScreen({
Key? key,
#required this.url,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Expanded(
child: CachedNetworkImage(
imageUrl: '${this.url}',
// Ajust the image changing the box fit attributte
fit: BoxFit.cover,
placeholder: (_, __) {
return Center(
child: CupertinoActivityIndicator(
radius: 15,
),
);
},
),
),
);
}
}
After that when you click the app navigates to a new screen rendering only the image. You can add a back button later.

No Material widget found in flutter

this screenshot of an No Material widget found
I try to add stars RateBar as below code but i got an error no material widget found.
what i need to do is that when i pressed on this flatButton i got a window to rate the order and submit this rate, how can i do that through my code below, or to inform me how to handle it
this is the widget of StarRating
import 'package:flutter/material.dart';
typedef void RatingChangeCallback(double rating);
class StarRating extends StatelessWidget {
final int starCount;
final double rating;
final RatingChangeCallback onRatingchanged;
final Color color;
StarRating({this.starCount=5, this.rating = .0, this.onRatingchanged, this.color});
Widget buildStar(BuildContext context, int index){
Icon icon;
if (index >= rating) {
icon = Icon(
Icons.star_border,
color: Theme.of(context).buttonColor
);
}
else if(index > rating - 1 && index < rating){
icon = Icon(
Icons.star_half,
color: Theme.of(context).primaryColor,
);
}else{
icon = Icon(
Icons.stars,
color: Theme.of(context).primaryColor,
);
}
return InkResponse(
onTap: onRatingchanged==null ? null : ()=> onRatingchanged(index+1.0),
child: icon,
);
}
#override
Widget build(BuildContext context) {
return Row(
children: List.generate(starCount, (index)=>buildStar(context, index)),
);
}
}
and this is the Screen to view the starBar:
import 'package:felsaree/widgets/star.rating.dart';
import 'package:flutter/material.dart';
class StarRatingScreen extends StatefulWidget {
static const routeName = '/starRating';
#override
_StarRatingScreenState createState() => _StarRatingScreenState();
}
class _StarRatingScreenState extends State<StarRatingScreen> {
double rating =3.5;
#override
Widget build(BuildContext context) {
return StarRating(
rating: rating,
onRatingchanged: (rating) => setState(() => this.rating = rating),
);
}
}
and in orderDetails screen through the flatbutton i need to show this Star Rate:
import 'package:felsaree/providers/order_provider.dart';
import 'package:felsaree/screens/star_rating_screen.dart';
import 'package:felsaree/widgets/star.rating.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class OrderDetails extends StatefulWidget {
static const routeName = '/orderDetails';
#override
_OrderDetailsState createState() => _OrderDetailsState();
}
class _OrderDetailsState extends State<OrderDetails> {
double rating = 3.5;
// Widget ratingChange(double rating){
// return StarRating(
// rating: rating,
// onRatingchanged: (rating)=>this.rating = rating,);
// }
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context).size.height;
final orderId = ModalRoute.of(context).settings.arguments as int;
final orderProvider = Provider.of<OrderProvider>(context, listen: false);
final order = orderProvider.findOrderById(orderId);
AppBar appBar = AppBar(title: Text(order.restaurantName),);
double _totalPrice =orderProvider.totalItemsPrice(order.orderItems);
bool _isAddress = orderProvider.checkUserAdress(order.address);
return Scaffold(
appBar: appBar,
body: Column(
children: <Widget>[
Card(
elevation: 4,
margin: EdgeInsets.all(10),
child: Padding(
padding: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
children: <Widget>[
Text(order.id.toString()),
SizedBox(height: 4,),
Text(order.restaurantName),
SizedBox(height: 4,),
Text(order.branchName),
SizedBox(height: 4,),
],
),
Column(
children: <Widget>[
Text(DateFormat.yMd().format(DateTime.now())),
SizedBox(height: 15,),
Text('InProgress'),
SizedBox(height: 15,)
],
)
],
),),
),
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.grey[100],
border: Border.all(width: 2, color: Colors.grey)
) ,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Price'),
Text('${_totalPrice}L.E'),
Text('Total: ${order.price}L.E')
],
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('PC Discount'),
Text('${order.discountValue}L.E'),
Text(''),
],
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('service Tax'),
Text('${order.serviceTax}L.E'),
Text(''),
],
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Delivery'),
Text('${order.delivery}L.E'),
Text(''),
],
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Vat'),
Text('${order.vatAmount}L.E'),
Text(''),
],
),
],
),
),
Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(10),
),
padding: EdgeInsets.all(10),
margin: EdgeInsets.only(bottom: 20),
height: (mediaQuery
- appBar.preferredSize.height
- MediaQuery.of(context).padding.top)*0.30,
width: MediaQuery.of(context).size.width*.8,
child: ListView.builder(
itemCount: order.orderItems.length,
itemBuilder: (ctx, index){
final item = order.orderItems[index];
if(item.userComments == ''){
String userComment= 'no comment';
item.userComments = userComment;
}
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(item.image,),
),
title: Text(item.itemName),
subtitle: Text('count: ${item.count}'),
trailing: Text(item.userComments),
);
}
),
),
Container(
width: double.infinity,
margin: EdgeInsets.only(right: 10, left: 10),
padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
color: Colors.grey[100],
child: Text('Delivery Address', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),),
),
SizedBox(height: 8),
Container(
width: double.infinity,
padding: EdgeInsets.all(10),
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[100])
),
child: _isAddress? Text(order.address) : Text('no address found'),
),
FlatButton(
onPressed: ()=>Navigator.of(context).pushNamed(StarRatingScreen.routeName),
child: Text('Rate The Order', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),))
],
),
);
}
}
This can be fixed by ensuring that your main includes MaterialApp() and Scaffold() as ancestors of your widgets as so:
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: YourWidget(),
),
));
}
If, for whatever reason you don't want to use MaterialApp... you can use Material():
void main() {
runApp(
home: Scaffold(
appBar: AppBar(),
body: Material( child: YourWidget()),
),
);
}

I want to add a new element after my horizontal listview how can I add it

This is the projected picture that shows how I am able to add an element.
Below is my code in which I want to add an element so that if my list is not present it also shows the element and if it present then the element is the last element.
I have tried this in some different ways.
Can anyone please help me?
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'alllist.dart';
List<Alllist> _alllist = [];
List<Alllist> get alllist => _alllist;
class EduCategory extends StatefulWidget{
final String listcategory;
final int intp;
EduCategory({this.listcategory,this.intp});
#override
EduCategoryState createState() {
return new EduCategoryState();
}
}
class EduCategoryState extends State<EduCategory> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return Container(child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
widget.listcategory,
style: TextStyle(fontWeight: FontWeight.bold),
),
new Row(
children: <Widget>[
new Icon(Icons.play_arrow),
new Text("Watch All", style: TextStyle(fontWeight: FontWeight.bold))
],
)
],
),
Expanded(
child: new Padding(
padding: const EdgeInsets.only(top: 8.0),
child:new StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('all list').where("listcategory",isEqualTo: widget.listcategory).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text("no");
if (snapshot.data.documents.length == 0) return InkWell(
child: Stack(
children: <Widget>[
new Container(
width: 80.0,
height: 80.0,
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
border: Border.all(color: Colors.blueGrey),
borderRadius: BorderRadius.circular(5.0),
image: new DecorationImage(
fit: BoxFit.fill,
image: new AssetImage("assets/Plus.png")),
),
margin: const EdgeInsets.symmetric(horizontal: 20.0),
// child: Text(name),
),
Padding(padding: EdgeInsets.only(top: 80.0,left: 20.0),
child: Text("Add Lession",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blueGrey),),
),
],
),
onTap: (){},
);
return new ListView(
scrollDirection: Axis.horizontal,
children: buildGrid(snapshot.data.documents)
);;
}
),
))
],
),
);
}
List<Widget> buildGrid(List<DocumentSnapshot> documents) {
List<Widget> _gridItems = [];
_alllist.clear();
for (DocumentSnapshot document in documents) {
_alllist.add(Alllist.fromDocument(document));
}
for (Alllist alllist in _alllist) {
_gridItems.add(buildGridItem(alllist));
}
return _gridItems;
}
Widget buildGridItem(Alllist alllist,) {
return widget.intp==0?
InkWell(
child: Stack(
children: <Widget>[
new Container(
width: 80.0,
height: 80.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.blue,width: 4.0,style: BorderStyle.solid),
image: new DecorationImage(
fit: BoxFit.fill,
image: new NetworkImage(
alllist.imageUrl)),
),
margin: const EdgeInsets.symmetric(horizontal: 20.0),
// child: Text(name),
),
Padding(padding: EdgeInsets.only(top: 80.0,left: 10.0),
child: Text(alllist.title,style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blueGrey),),
),
],
),
onTap: (){},
):new Row(
children: <Widget>[
InkWell(
child: Stack(
children: <Widget>[
new Container(
width: 80.0,
height: 80.0,
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(5.0),
image: new DecorationImage(
fit: BoxFit.fill,
image: new NetworkImage(
alllist.imageUrl)),
),
margin: const EdgeInsets.symmetric(horizontal: 20.0),
// child: Text(name),
),
Padding(padding: EdgeInsets.only(top: 80.0,left: 10.0),
child: Text(alllist.title,style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blueGrey),),
),
],
),
onTap: (){},
)
]
);
}
}
You can use the ListView.builder with itemCount as snapshot.data.documents.length + 1.
Code sample:
new StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('all list').where("listcategory",isEqualTo: widget.listcategory).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text("no");
var documentsLength = snapshot.data.documents.length;
ListView.builder(itemCount: documentsLength + 1, // +1 for last element
itemBuilder: (context, index) {
if (index == documentsLength) {
//last view which have plus button
} else {
return buildGridItem((Alllist.fromDocument(snapshot.data.documents[index]))
}
});
})
I think that you have to just add condition in itemBuilder checkout in below code;
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final List<int> items=[1,2,3,4,5,6];
#override
Widget build(BuildContext context) {
final title = 'Mixed List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Container(
height: 100.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: items.length + 1 ,
itemBuilder: (context, index) {
if(index < items.length )
{ return Container(
color: Colors.blue,
width: 100.0,
padding: EdgeInsets.all(8.0),
child: new Center(
child: new Text(index.toString()),
),
);
}
else {
return new Container(
color: Colors.blue,
width: 100.0,
child: new Center(
child: new Text(index.toString() + "differnt"),
),
);
}
},
),
),
),
);
}
}