How to get data from previous page flutter - flutter

I'm trying to build a page about description of a photo with this code:
import 'package:flutter/material.dart';
import 'description_widget.dart';
class ImageDescription extends StatefulWidget {
#override
_ImageDescriptionState createState() => _ImageDescriptionState();
}
class _ImageDescriptionState extends State<ImageDescription> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.white10,
elevation: 0,
leading: Container(
padding: EdgeInsets.fromLTRB(20, 20, 0, 0),
child: InkWell(
child: Hero(
tag: 'back',
child: Image.asset(
'assets/images/wp_back_button_icon.png',
height: 250,
),
),
onTap: () {
Navigator.pop(context);
},
),
),
actions: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(0, 20, 20, 0),
child: Hero(
tag: 'logo',
child: Image.asset(
'assets/images/wp_logo.png',
height: 250,
),
),
),
],
),
body: SingleChildScrollView(
child: imageDescription(
"assets/images/gallery/Image1.jpg",
"Tittle 1",
"Description 1.",
"Image1"),
),
);
}
}
Using this Widget that i've created:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
Widget imageDescription(String url, title, description, tag) {
return Container(
child: Column(
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Center(
child: Text(title, style: TextStyle(fontSize: 30)),
),
Center(
child: Text("Let's educate in the fun way!"),
)
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10),
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Hero(tag: tag, child: Image.asset(url)),
),
),
Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Card(
child: Container(
margin: const EdgeInsets.all(10),
child: Text(
description,
textAlign: TextAlign.justify,
style: TextStyle(fontSize: 20),
),
),
),
)
],
),
)
],
),
);
}
But instead of manually adding the imageDescription(
"assets/images/gallery/Image1.jpg",
"Tittle 1",
"Description 1.",
"Image1"),
I want to get the variables from the image that i clicked on previous page :
import 'package:flutter/material.dart';
import 'image_description.dart';
import 'show_image.dart';
class Gallery extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.white10,
elevation: 0,
leading: Container(
padding: EdgeInsets.fromLTRB(20, 20, 0, 0),
child: InkWell(
child: Hero(
tag: 'back',
child: Image.asset(
'assets/images/wp_back_button_icon.png',
height: 250,
),
),
onTap: () {
Navigator.pop(context);
},
),
),
actions: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(0, 20, 20, 0),
child: Hero(
tag: 'logo',
child: Image.asset(
'assets/images/wp_logo.png',
height: 250,
),
),
),
],
),
body: SafeArea(
child: Column(
children: <Widget>[
Container(
child: Text(
'AR Gallery',
style: TextStyle(fontSize: 30),
),
),
Container(
child: Text("Let's educate in the fun way"),
),
Expanded(
child: SizedBox(
height: double.infinity,
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 3,
children: <Widget>[
InkWell(
child: Stack(
children: <Widget>[
ShowImage(
url: "assets/images/gallery/Image1.jpg",
tag: "Image1",
title: "Title 1",
)
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ImageDescription()));
},
),
InkWell(
child: Stack(
children: <Widget>[
ShowImage(
url: "assets/images/gallery/Image2.jpg",
tag: "Image2",
title: "Title 2",
)
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ImageDescription()));
},
),
InkWell(
child: Stack(
children: <Widget>[
ShowImage(
url: "assets/images/gallery/Image3.jpg",
tag: "Image3",
title: "Title 3",
)
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ImageDescription()),
);
}),
],
),
),
),
],
),
),
);
}
}
using this widget:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ShowImage extends StatelessWidget {
final String tag;
final String url;
final String title;
const ShowImage({Key key, this.tag, this.url, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
height: double.infinity,
width: double.infinity,
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child:
Hero(tag: tag, child: Image.asset(url, fit: BoxFit.fitHeight)),
),
),
Container(
padding: const EdgeInsets.all(5),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Text(title,
style: TextStyle(
backgroundColor: Colors.deepOrange, color: Colors.white)),
),
)
],
);
}
}
or simply:
open gallery page
click an image
open image description page with title & image path of clicked image
Regards, Slim

I would recommend you to follow this tutorial.
For you this would mean:
Create a class that contains all the data you would like to pass:
class ImageData {
final String title;
final String url;
final String description;
final String tag;
Image(this.title, this.url, this.description, this.tag);
}
Set Up your ImageDescriptionScreen to require an Image object:
import 'package:flutter/material.dart';
import 'description_widget.dart';
import 'image_data.dart';
class ImageDescription extends StatefulWidget {
final ImageData imageData;
// In the constructor, require an Image Object.
ImageDescriptionScreen({Key key, #required this.imageData}) :
super(key: key);
#override
_ImageDescriptionState createState() => _ImageDescriptionState();
}
class _ImageDescriptionState extends State<ImageDescription> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.white10,
elevation: 0,
leading: Container(
padding: EdgeInsets.fromLTRB(20, 20, 0, 0),
child: InkWell(
child: Hero(
tag: 'back',
child: Image.asset(
'assets/images/wp_back_button_icon.png',
height: 250,
),
),
onTap: () {
Navigator.pop(context);
},
),
),
actions: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(0, 20, 20, 0),
child: Hero(
tag: 'logo',
child: Image.asset(
'assets/images/wp_logo.png',
height: 250,
),
),
),
],
),
body: SingleChildScrollView(
child: imageDescription(
widget.imageData.url,
widget.imageData.title,
widget.imageData.description,
widget.imageData.tag
),
),
);
}
}
Pass the image object when navigating to the new page:
Navigator.push(context, MaterialPageRoute(builder: (context) =>
ImageDescription(imageData: ImageData('title', 'url', 'description', 'tag'),)));
EDIT: I put my solution outlined below into dartpad, feel free to try it out there and copy & paste the code.
Short remarks to my dartpad solution:
All image data is maintained and contained in this list of ImageData Objects. Relevant information for other screens is passed via Navigator. With this solution you only need to maintain image data in this list. The grid view automatically expands if more items are added to the list.
final List<ImageData> imageList = [
ImageData(title: 'MacBook',url: 'https://picsum.photos/250?image=9',
description: 'this is a macbook', tag: 'macbook'),
ImageData(title: 'Deer',url: 'https://picsum.photos/250?image=1003',
description: 'this is a deer', tag: 'deer'),
];
Let me know if anything is unclear :)

Related

How to sort functionality & filter data got from restapi

starting my carrer in flutter development for 2 months
while doing this project based in flutter,i get data from rest api with bloc state management & listed it with listvieww builder, but want add sort & filter functionality to it,, can you please explain how to do with an example, excepting valuable suggestions from you guys
search and filter functionilty
class Upcoming extends StatefulWidget {
Upcoming({Key? key}) : super(key: key);
#override
State<Upcoming> createState() => _UpcomingState();
}
class _UpcomingState extends State<Upcoming> {
#override
Widget build(BuildContext context) {
return BlocBuilder<MOdelBloc, MOdelState>(
builder: (context, state) {
if (state is MOdelInitial) {
context.read<MOdelBloc>().add(LoadEVENT());
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is ModelLoading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is ModelLoadedstate) {
return buildupcoming(state.fakestore);
} else if (state is ErrorSatte) {
return const Center(
child: Text('errorstate'),
);
}
return const Center(child: Text('error'));
},
);
}
}
Widget buildupcoming(List<CryptoCurrency> currency) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.yellow.shade400,
leading: const Icon(
Icons.portrait_rounded,
),
title: const Center(
child: Text(
'Upcoming Matches',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
actions: const [
Icon(
Icons.headset,
),
SizedBox(
width: 5,
),
Icon(Icons.message)
],
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
height: double.maxFinite,
margin: const EdgeInsets.all(10),
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {}, child: const Text('CRICKET')),
const SizedBox(
width: 15,
),
ElevatedButton(
onPressed: () {},
child: const Icon(Icons.sports_football))
],
),
const SizedBox(
height: 10,
),
Row(
children: const [
TextWidget(text: 'My Rooms', size: 20),
Spacer(),
Text(
'View all',
style: TextStyle(color: Colors.black45),
)
],
),
const SizedBox(
height: 5,
),
Container(
height: 170,
child: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(left: 5),
child: Column(children: [
SliderCARD(
text1: currency[2].fullname.toString(),
text2: currency[3].fullname,
minitext1: currency[2].price.toString(),
minitext2: currency[4].price.toString(),
color: Colors.indigo,
height: 100,
),
Row(children: [IconButton(onPressed: ( ){},
icon: Icon(Icons.arrow_back)),IconButton(onPressed: (){}, icon: Icon(Icons.arrow_back_outlined))],)]));
})),
ListView.builder(
physics:const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: currency.length,
itemBuilder: (context, index) {
final CryptoCurrency cryptoCurrency = currency[index];
return Container(
margin: const EdgeInsets.only(bottom: 10),
height: 100,
child: SliderCARD(
text1: cryptoCurrency.fullname,
text2: currency[3].fullname,
minitext1: cryptoCurrency.price.toString(),
minitext2: currency[4].price.toString(),
color: Colors.white,
height: 100,
));
})
])),
));
}

Make Listeview work nested inside of column inside of a container in flutter

I am trying and make a Listeview work, which is nested inside of column that is nested inside of a container in flutter. The container is supposed to be a dialog. I think the problem is that the container has no defined hight (it is supposed to adapt to the screen size). With the current code I get a bottom overflow. Maybe because of the padding of the container?
I tried differen variants with expanded, flexible and singlechildscrollview but I can't make it work. The standard tip, wrap the ListView with Expanded seems not to work.
Thanks for your help!
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dialog',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: Center(
child: Column(
children: [
MaCard(mitarbeiterName: "Name"),
CustomDialogBoxRow(
title: "Sturmtruppler",
descriptions: "wird noch weichen",
text: "text")
],
),
),
),
);
}
}
class Constants {
Constants._();
static const double padding = 20;
static const double avatarRadius = 100;
static const double buttonHight = 100;
}
class CustomDialogBoxRow extends StatefulWidget {
final String title, descriptions, text;
const CustomDialogBoxRow({
Key? key,
required this.title,
required this.descriptions,
required this.text,
}) : super(key: key);
#override
_CustomDialogBoxRowState createState() => _CustomDialogBoxRowState();
}
class _CustomDialogBoxRowState extends State<CustomDialogBoxRow> {
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(Constants.padding),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: contentBox(context),
);
}
contentBox(context) {
return Stack(
children: <Widget>[
Container(
constraints: const BoxConstraints(minWidth: 400, maxWidth: 800),
padding: const EdgeInsets.only(
left: Constants.padding,
right: Constants.padding,
bottom: Constants.padding),
margin: const EdgeInsets.only(top: Constants.avatarRadius),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(Constants.padding),
boxShadow: [
const BoxShadow(
color: const Color.fromARGB(255, 79, 73, 73),
offset: const Offset(0, 5),
blurRadius: 5),
]),
child: Column(
children: [
SizedBox(
height: Constants.avatarRadius,
child: Row(
children: [
const SizedBox(
child: const Placeholder(),
),
const Expanded(
child: Placeholder(),
),
],
),
),
SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 50,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
)
],
),
)
],
),
),
Positioned(
left: Constants.padding,
right: Constants.padding,
child: Stack(
children: [
Container(
child: Align(
alignment: Alignment.topLeft,
child: Container(
width: Constants.avatarRadius * 2,
height: Constants.avatarRadius * 2,
child: const CircleAvatar(
radius: Constants.avatarRadius * 2,
backgroundImage: AssetImage('assets/images/SBE.jpg'),
),
),
),
),
],
),
),
],
);
}
}
class MaCard extends StatefulWidget {
MaCard({
Key? key,
required this.mitarbeiterName,
}) : super(key: key);
final String mitarbeiterName;
#override
State<MaCard> createState() => _MaCardState();
}
class _MaCardState extends State<MaCard> {
#override
Widget build(BuildContext context) {
return Card(
child: InkWell(
onTap: () {
print("card taped");
/*showDialog(context: context, builder: (BuildContext context) {
return
})*/
showDialog(
context: context,
builder: (BuildContext context) {
return CustomDialogBoxRow(
title: "Stormtrouper",
descriptions: "Jojo, this is card",
text: "Roger Roger",
);
});
},
child: SizedBox(
height: Constants.buttonHight,
width: 300,
child: Center(child: Text(widget.mitarbeiterName)),
),
));
}
}
Here is picture of what it should look like. My wonderful handdrawing is supposed to be the scrollable content.
Goal
It would be better using LayoutBuilder to get parent constraints and size the inner elements. Also You need to wrap with Expaned to get available spaces for infinite size widget.
I will highly recommend to check this video from Flutter.
Changes are made
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dialog',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: Center(
child: Column(
children: [
MaCard(mitarbeiterName: "Name"),
Expanded( //here
child: CustomDialogBoxRow(
title: "Sturmtruppler",
descriptions: "wird noch weichen",
text: "text"),
)
],
),
),
),
);
}
}
And on contentBox
contentBox(context) {
return LayoutBuilder(builder: (context, constraints) {
print(constraints);
return SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
child: Stack(
children: <Widget>[
Container(
constraints: const BoxConstraints(minWidth: 400, maxWidth: 800),
padding: const EdgeInsets.only(
left: Constants.padding,
right: Constants.padding,
bottom: Constants.padding),
margin: const EdgeInsets.only(top: Constants.avatarRadius),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(Constants.padding),
boxShadow: const [
BoxShadow(
color: Color.fromARGB(255, 79, 73, 73),
offset: Offset(0, 5),
blurRadius: 5),
]),
child: Column(
children: [
SizedBox(
height: Constants.avatarRadius,
child: Row(
children: [
const Expanded(
child: const Placeholder(),
),
const Expanded(
child: Placeholder(),
),
],
),
),
Expanded(
// or sizedBOx ( constraints.maxHeight- Constants.avatarRadius,)
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 450,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
),
SizedBox(
height: 50,
child: Text("bla"),
)
],
),
),
)
],
),
),
// Positioned(
// left: Constants.padding,
// right: Constants.padding,
// child: Stack(
// children: [
// Container(
// child: Align(
// alignment: Alignment.topLeft,
// child: Container(
// width: Constants.avatarRadius * 2,
// height: Constants.avatarRadius * 2,
// child: const CircleAvatar(
// radius: Constants.avatarRadius * 2,
// backgroundImage: AssetImage('assets/images/SBE.jpg'),
// ),
// ),
// ),
// ),
// ],
// ),
// ),
//
],
),
);
});
}

Flutter Navigation shows a black 404 screen when going back from a page

I'm facing this issue with Navigator in Flutter where when I go back from a page I get redirected to a black 404 page.
This is the navigation flow:
Login screen
HomePage screen
After being logged in, I am redirected to the Homepage and I shouldn't be able to go back to a previous screen, but if I swipe to the right I'm shown a black page with a 404 label and I can't move from there. Thank you in advance for any help!
Here I provide some code:
class SignInPage extends StatelessWidget {
static const routeName = '/signIn';
const SignInPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: Stack(
children: [
const Positioned(
left: -20,
top: -20,
child: AnimatedCircle(color: AppColors.lightBlue),
),
const Positioned(
right: -50, top: 150, child: AnimatedCircle(color: AppColors.lightOrange)),
const Positioned(
bottom: 60, left: -70, child: AnimatedCircle(color: AppColors.lightGreen)),
const Positioned(
right: -50, bottom: -60, child: AnimatedCircle(color: AppColors.lightRed)),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/logo.png'),
Container(
width: MediaQuery.of(context).size.width * 8,
margin: const EdgeInsets.symmetric(horizontal: Dimens.SPACING_XL),
child: StyledButton.outlined(
title: 'Sign in with Google',
leading: Image.asset('assets/images/google.png', scale: 30),
onPressed: () async {
final res = await Authentication.signInWithGoogle();
await Authentication.userSetup(res.user!);
Navigator.of(context).popAndPushNamed(HomePage.routeName);
},
),
),
],
),
],
),
),
],
),
);
}
}
class HomePage extends StatelessWidget {
static const routeName = '/homepage';
static const _padding = EdgeInsets.symmetric(horizontal: 20.0, vertical: 6.0);
static const _dividerOptions = 30.0;
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => ItemsProvider(),
child: Consumer<ItemsProvider>(
builder: (_, provider, __) => Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
automaticallyImplyLeading: false,
actions: [
IconButton(
onPressed: () => Navigator.of(context).pushNamed('/user'),
icon: const Icon(Icons.person)),
],
),
floatingActionButton: Visibility(
visible: provider.buttonVisibility,
child: FloatingActionButton(
heroTag: "btn1",
backgroundColor: AppColors.red,
child: const Icon(Icons.add, color: AppColors.splashColor),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => buildModal(context, provider),
);
}),
),
body: Padding(
padding: _padding,
child: Column(
children: [
TopCard(
itemCount: provider.itemsCount,
onPressed: () {
provider.deleteAllItem();
Navigator.of(context).pop();
},
),
const Divider(
height: _dividerOptions,
thickness: 1.0,
indent: _dividerOptions,
endIndent: _dividerOptions,
),
const Expanded(
child: ItemsList(),
),
],
),
),
),
),
);
}
SingleChildScrollView buildModal(
BuildContext context,
ItemsProvider provider,
) {
return SingleChildScrollView(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Container(
decoration: const BoxDecoration(),
child: AddItemScreen(args: AddItemScreenArguments(provider.addItem)),
),
);
}
}

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.

I am getting findAncestorStateOfType error in flutter . What should I do about this? I am stuck here

How to solve findAncestorStateOfType error in Flutter? I am not able to navigate to other page using these codes. What is wrong with this code?
The error which I am getting is this
The method 'findAncestorStateOfType' was called on null.
Receiver: null
Tried calling: findAncestorStateOfType()
My code is this:
// entry point for the app,
// the => operator is shorthand for {} when there is only one line of code
void main() {
runApp(MaterialApp(
home: HomeRoute(),
));
}
// the root widget of our application
class HomeRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xFFFAAC98),
appBar: AppBar(
backgroundColor: Color(0xFFFAAC98),
),
body: myLayoutWidget(),
),
);
}
}
// replace this method with code in the examples below
Widget myLayoutWidget() {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 300,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
color: const Color(0xff89C5CC),
),
child: Center(
child: new Text(
'Gram Panchayat App',
style: TextStyle(
fontSize: 27,
fontWeight: FontWeight.bold,
color: Color(0xFF2F3676)),
),
),
),
),
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 18.0, top: 18.0),
child: Image.asset(
'assets/images/human1.png',
width: 150,
height: 150,
),
),
Padding(
padding: const EdgeInsets.only(left: 58.0),
child: elevatedButton(),
),
],
),
new Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 28.0),
child: elevatedButton1(),
),
Padding(
padding: const EdgeInsets.only(top: 58.0, left: 68.0),
child: new Image.asset(
'assets/images/human2.png',
width: 200,
height: 170,
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 60.0),
child: Row(children: [
new Image.asset(
'assets/images/img3.png',
width: 180,
height: 80,
),
]),
)
],
),
);
}
ElevatedButton elevatedButton() => ElevatedButton(
onPressed: () {
BuildContext context;
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
child: Text('Citizen'),
);
ElevatedButton elevatedButton1() =>
ElevatedButton(onPressed: () {}, child: Text('Staff'));
class SecondRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
);
}
}```
*Please help me I am stuck. I have gone through many sites but couldnt find what is wrong and the solution also.*
make myLayoutWidget() inside your HomeRoute class
and use
Navigator.of(context,rootNavigator:true).pop();
instead of
Navigator.pop(context);