Can not scroll staggered gridview inside listview in flutter - flutter

I have added staggered gridview as a widget inside Listview.Images and everything load perfectly but I can not scroll staggered gridview when pointing to it.but whole page can scroll by point to the other parts of the list view.
I have attached the code below.Could anyone please help me to solve this problem.
import 'package:beata2/services/sign_in.dart';
import 'package:beata2/ui/fashion.dart';
import 'package:beata2/ui/firstScreen.dart';
import 'package:beata2/ui/hotDeals.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'add_card_for_gride.dart';
import 'car_item_model.dart';
class Dashboard extends StatefulWidget {
#override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
String carBand;
String carYear;
String carImage;
CarModel carObjec = new CarModel("carBand","carYear","carImage");
var car;
List<CarModel> _listOfObjects = <CarModel>[];
#override
void initState() {
// TODO: implement initState
carObjec.getData().then((result) {
setState(() {
car = result;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
SizedBox(
height: 350.0,
width: 450.0,
child: Stack(
children: [
SizedBox(
height: 250.0,
child: AppBar(
title: Text("Welcome"),
backgroundColor: Colors.blue,
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () {},
),
elevation: 0.0,
),
),
Positioned(
left: 0.0,
right: 0.0,
top: 100.0,
bottom: 0.0,
child: Container(
child: CarouselSlider(
items: [
'https://www.crn.com/resources/025c-0f3247198c32-7caef631a12d-1000/pets.jpg',
'https://cdn.aohostels.com/img/infos/pets/Header-Pets-C.jpg',
].map((e) {
return ClipRRect(
borderRadius:
BorderRadius.all(Radius.circular(10.0)),
child: Container(
child: GestureDetector(
child: Image.network(e, fit: BoxFit.fill),
onTap: () {
switch (e) {
case "https://www.crn.com/resources/025c-0f3247198c32-7caef631a12d-1000/pets.jpg":
Navigator.push<Widget>(
context,
MaterialPageRoute(
builder: (context) => Fashion(),
),
);
break;
case "https://cdn.aohostels.com/img/infos/pets/Header-Pets-C.jpg":
Navigator.push<Widget>(
context,
MaterialPageRoute(
builder: (context) => HotDeals(),
),
);
break;
default:
return Text(' ');
break;
}
}),
));
}).toList(),
options: CarouselOptions(
height: 350.0,
aspectRatio: 16 / 9,
viewportFraction: 0.8,
initialPage: 0,
enableInfiniteScroll: true,
reverse: false,
autoPlay: true,
autoPlayInterval: Duration(seconds: 3),
autoPlayAnimationDuration: Duration(milliseconds: 800),
autoPlayCurve: Curves.fastOutSlowIn,
enlargeCenterPage: true,
scrollDirection: Axis.horizontal,
)),
),
),
],
),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Categories"),
),
Container(
height: 30.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Category(
image_location: 'assets/interface.png',
image_caption: 'Categories',
),
Category(
image_location: 'assets/interface.png',
image_caption: 'Categories',
),
Category(
image_location: 'assets/interface.png',
image_caption: 'Categories',
),
Icon(Icons.add),
Icon(Icons.add),
Icon(Icons.add),
Icon(Icons.add),
Icon(Icons.add),
Icon(Icons.add),
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Text("All"),
),
StreamBuilder(
stream: car,
builder: (context, snapshot) {
if (snapshot.hasData) {
for (int i = 0; i < snapshot.data.documents.length; i++) {
// DocumentSnapshot snap = snapshot.data.documents[i];
String carBrand =
snapshot.data.documents[i].data['carBrand'];
String caryear = snapshot.data.documents[i].data['carYear'];
String carimage =
snapshot.data.documents[i].data['urls'][0];
_listOfObjects.add(CarModel(carBrand,caryear,carimage));
}
return sliverGridWidget(context);
} else {
return Text("loading");
}
}
),
],
));
}
Widget sliverGridWidget(context) {
return StaggeredGridView.countBuilder(
padding: const EdgeInsets.all(8.0),
shrinkWrap: true,
primary: true,
crossAxisCount: 4,
itemCount: _listOfObjects.length, //staticData.length,
// itemBuilder: (context, index) {
// return Card(
// elevation: 8.0,
// child: InkWell(
// child: Hero(
// tag: index, // staticData[index].images,
// child: new FadeInImage(
// width: MediaQuery.of(context).size.width,
// image: NetworkImage(
// "https://images.unsplash.com/photo-1468327768560-75b778cbb551?ixlib=rb-1.2.1&w=1000&q=80"), // NetworkImage(staticData[index].images),
// fit: BoxFit.cover,
// placeholder: AssetImage("assets/images/app_logo.png"),
// ),
// ),
// onTap: () {
// //
// }
// )
// );
// },
itemBuilder: (BuildContext context, int index) {
return AadCardForGrid(_listOfObjects[index]);
},
staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
);
}
}
class Category extends StatelessWidget {
final String image_location;
final String image_caption;
Category({
this.image_location,
this.image_caption,
});
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(2.0),
child: InkWell(
onTap: () {},
child: Container(
width: 100.0,
child: ListTile(
title: Image.asset(
image_location,
width: 100.0,
height: 80.0,
),
subtitle: Text(image_caption),
),
),
));
}
}

Related

how to scroll search widget along with the list view result flutter

How to scroll the search widget along with the list view result flutter whenever I use singlechildscrollview it gives an error.Help me to solve the issue.
How to scroll the search widget along with the list view result flutter whenever I use singlechildscrollview it gives an error.Help me to solve the issue
import 'package:coronavirus_app/Services/states_services.dart';
import 'package:coronavirus_app/resources/sizeconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shimmer/shimmer.dart';
import '../Modal/world_countries_modal.dart';
import '../resources/colormanager.dart';
import '../resources/routesmanager.dart';
class CountriesListScreen extends ConsumerStatefulWidget {
const CountriesListScreen({Key? key}) : super(key: key);
#override
ConsumerState<CountriesListScreen> createState() =>
_CountriesListScreenState();
}
class _CountriesListScreenState extends ConsumerState<CountriesListScreen> {
final TextEditingController searchcontroller = TextEditingController();
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
StatesServices services = StatesServices();
final countrydata = ref.watch(countrydataProvider);
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
),
body: countrydata.when(
error: (err, stack) => Text('Error: ${err.toString()}'),
loading: () => Shimmer.fromColors(
baseColor: ColorManager.grey,
highlightColor: ColorManager.lightGrey,
child: ListView.builder(
itemCount: 5,
itemBuilder: ((context, index) {
return Column(
children: [
ListTile(
title: Container(
height: getProportionateScreenHeight(20),
width: getProportionateScreenWidth(89),
color: ColorManager.white,
),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Container(
color: ColorManager.white,
)),
subtitle: Container(
height: getProportionateScreenHeight(20),
width: getProportionateScreenWidth(89),
color: ColorManager.white,
),
)
],
);
})),
),
data: ((data) {
List<WorldCountriesModal> countrieslist =
data.map((e) => e).toList();
return Column(children: [
SizedBox(
height: getProportionateScreenHeight(50),
width: double.infinity,
child: TextFormField(
controller: searchcontroller,
onChanged: (value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(vertical: 10),
hintText: 'Search with country name',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50))),
),
),
Expanded(
child: ListView.builder(
itemCount: countrieslist.length,
itemBuilder: ((context, index) {
var data = countrieslist[index];
var countrydata = countrieslist[index].country;
if (searchcontroller.text.isEmpty) {
return Column(
children: [
InkWell(
onTap: (() {
FocusScope.of(context).unfocus();
Navigator.pushNamed(context, Routes.detail,
arguments: data);
}),
child: ListTile(
title: Text(data.country.toString()),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Image(
image: Image.network(data
.countryInfo!.flag
.toString())
.image),
),
subtitle: Text(data.cases.toString()),
),
)
],
);
} else if (countrydata!
.toLowerCase()
.contains(searchcontroller.text.toLowerCase())) {
return Column(
children: [
InkWell(
onTap: (() {
FocusScope.of(context).unfocus();
Navigator.pushNamed(context, Routes.detail,
arguments: data);
}),
child: ListTile(
title: Text(data.country.toString()),
leading: SizedBox(
height: getProportionateScreenHeight(100),
width: getProportionateScreenWidth(50),
child: Image(
image: Image.network(data
.countryInfo!.flag
.toString())
.image),
),
subtitle: Text(data.cases.toString()),
),
)
],
);
} else {
return Container(
height: 0,
);
}
})),
),
]);
})
}
}
ListView.builder(
shrinkWrap: true,
primary: false
Hey If you want to use singlechildscrollview then you need to assign
ListView.builder(
shrinkWrap: true
to your ListView.builder.
Because you can't assign the 2 scroll views to your screen at a time.
Put your widgets in SingleChildScrollView widget as the following example:
return Scaffold(
appBar: AppBar( ..........) ,
body: Container(
margin: const EdgeInsets.only(top: 15, right: 10),
alignment: Alignment.topRight,
width: double.infinity,
height: double.infinity,
==> child:SingleChildScrollView(
scrollDirection: Axis.vertical,
child: .......

How to add 3x3 row of buttons between my slider and floatingbutton

as the title says I want to add a 3x3 buttons grid, but I'm not able to do, I don't understand how to create all of this elements
(I'm thinking in a div way like in html)
Here is my code, at top is my carousel slider and at the bottom is the floatingbutton, I need my 3x3 to be below my carousel slider and top of my floating button
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
final List<String> imgList = [
'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
];
void main() => runApp(CarouselDemo());
final themeMode = ValueNotifier(2);
class CarouselDemo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
builder: (context, value, g) {
return MaterialApp(
initialRoute: '/',
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.values.toList()[value as int],
debugShowCheckedModeBanner: false,
routes: {
'/': (ctx) => ComplicatedImageDemo(),
},
);
},
valueListenable: themeMode,
);
}
}
class DemoItem extends StatelessWidget {
final String title;
final String route;
DemoItem(this.title, this.route);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(title),
onTap: () {
Navigator.pushNamed(context, route);
},
);
}
}
final List<Widget> imageSliders = imgList
.map((item) => Container(
child: Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Stack(
children: <Widget>[
Image.network(item, fit: BoxFit.cover, width: 1000.0),
Positioned(
bottom: 0.0,
left: 0.0,
right: 0.0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(200, 0, 0, 0),
Color.fromARGB(0, 0, 0, 0)
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
),
),
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 20.0),
child: Text(
'No. ${imgList.indexOf(item)} image',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
),
],
)),
),
))
.toList();
class ComplicatedImageDemo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Sayapp 0.2')),
body: Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
label: Text('Alert'),
icon: Icon(Icons.add_alert_sharp),
backgroundColor: Colors.red,
),
);
}
}
body: Column(
children: [
Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
),
Column(
children: [
Row(
children: [
Button1();
Button2();
Button3();
],
),
Row(
children: [
Button1();
Button2();
Button3();
],
),
Row(
children: [
Button1();
Button2();
Button3();
],
),
],
),
],
),
You can use GridView.builder() to do this
List<Widget> buttonList = [Button1(),Button2(),Button3(),Button4(),Button5(),Button6(),Button7(),Button8(),Button9()];
// inside body
body: Column(
children: [
CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // number of widgets in a row
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: (1.0 / 1.2),
),
itemBuilder: (BuildContext context, int index) {
return buttonList[index];
},
itemCount: buttonList.length,
),
],)

Flutter different screen navigation using on onTap uncertain ListView

How can i navigate to a different route in ListView querySnapshot.docs[index].data()['image']. In my case all the cards will navigate to different route.
Relevant code with facing this issue:
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttertravelapp/screens/home.dart';
import 'package:fluttertravelapp/screens/location_list_screen.dart';
import 'package:fluttertravelapp/widgets/nav_drawer.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class SelectedCategoryScreen extends StatefulWidget {
SelectedCategoryScreen();
#override
_SelectedCategoryScreen createState() => _SelectedCategoryScreen();
}
class _SelectedCategoryScreen extends State<SelectedCategoryScreen> {
#override
void initState() {
super.initState();
}
final Query query = FirebaseFirestore.instance
.collection("movies")
.orderBy('year', descending: true);
void gotoPage(String pageName) {
switch (pageName) {
case 'home':
{
// statements;
Navigator.push(
context, CupertinoPageRoute(builder: (redContext) => HomePage()));
}
break;
case 'yard':
{
//statements;
Navigator.push(
context,
CupertinoPageRoute(
builder: (redContext) => LocationListScreen()));
}
break;
default:
{
throw new Exception("Path ${pageName} not supported");
}
break;
}
}
/// Page Controller
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_sharp),
),
title: Container(
width: 170,
child: Image.network(
'https://i.hizliresim.com/sf4asddsau.jpg',
),
),
centerTitle: true,
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.cloud_queue_outlined),
),
],
),
drawer: NavDrawer(),
body: SafeArea(
child: Container(
child: StreamBuilder(
stream: query.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Center(
child: Icon(Icons.error),
);
}
final QuerySnapshot<Map<String, dynamic>> querySnapshot =
snapshot.data;
return ListView(
physics: BouncingScrollPhysics(),
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 28.8, bottom: 16.8),
height: 724.8,
child: ListView.builder(
itemCount: querySnapshot.size,
padding: EdgeInsets.only(left: 28.8, right: 12),
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Container(
height: 214.8,
width: 188.4,
margin: EdgeInsets.only(right: 16.8, bottom: 50),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9.6),
image: DecorationImage(
fit: BoxFit.cover,
image: CachedNetworkImageProvider(
querySnapshot.docs[index].data()['image'],
maxHeight: 200,
maxWidth: 200),
),
),
child: Stack(
children: <Widget>[
GestureDetector(
onTap: () {
GestureDetector(
onTap: () => gotoPage(querySnapshot
.docs[index]
.data()['page']));
/* Navigator.push(
context,
CupertinoPageRoute(
builder: (redContext) => MyApp()));*/
},
),
Positioned(
bottom: 19.2,
left: 19.2,
child: ClipRRect(
borderRadius: BorderRadius.circular(4.8),
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaY: 19.2, sigmaX: 19.2),
child: Container(
height: 26,
padding: EdgeInsets.only(
left: 0.0, right: 0.0),
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
SizedBox(
width: 9.52,
),
SvgPicture.asset(
'assets/svg/icon_location.svg'),
SizedBox(
width: 9.52,
),
SvgPicture.asset(
'assets/svg/icon_location.svg',
height: 50,
),
SizedBox(
width: 9.52,
),
SvgPicture.asset(
'assets/svg/icon_location.svg'),
SizedBox(
width: 9.52,
),
/* Text(
recommendations[index].name,
style: GoogleFonts.lato(
fontWeight: FontWeight.w700,
color: Colors.white,
fontSize: 16.8),
) */
],
),
),
),
),
),
Align(
alignment: Alignment.center,
child: Container(
margin: EdgeInsets.all(70),
child: Text(
querySnapshot.docs[index].data()['title'],
style: TextStyle(
fontSize: 27,
color: Colors.white,
fontWeight: FontWeight.bold),
textAlign: TextAlign.left,
),
),
),
],
),
);
},
),
)
],
);
},
),
),
),
);
}
}
Firestore:
If you look at the picture you can easily understand what I mean.
I am not sure how your document from QuerySnapshot looks like but you could add a field/property that contains the name of the page to be navigated to. Then add a function with a switch-case or if-else statements that control which page to navigate to in your onTap().
void gotoPage(String pageName){
switch(pageName) {
case 'home': {
// statements;
Navigator.push(context,CupertinoPageRoute(builder: (redContext) => HomePage()));
}
break;
case 'yard': {
//statements;
Navigator.push(context,CupertinoPageRoute(builder: (redContext) => YardPage()));
}
break;
default: {
throw new Exception(`Path ${pageName} not supported`);
}
break;
}
}
then call it in onTap.
GestureDetector(onTap: () => gotoPage(querySnapshot.docs[index].data()['page']) ),
where page will be the field/property with the pageName that you would have added to your document

Flutter hero animation not working, same tag but still not animating in new screen

I have memory image in my downloads screen as grid tile and when clicked, it will animated to next full image view page where whole body is imageview so i want to animated to new screen with hero animation but it is not working.
I even provided the same tag but still not animating.
The problem is that it work with Navigator.push method but here i am using Get.toNamed() method as i am passing arguments to next screen controller class , but with this navigation it is not animating. how to do hero animation with Getx navigation?
dowloads.dart
class Downloads extends StatelessWidget {
final photos = DatabaseProvider.db.getPictures();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: brandName('Down', 'loads'),
elevation: 0.0,
),
body: FutureBuilder<List<Picture>>(
future: photos,
builder: (BuildContext context, AsyncSnapshot<List<Picture>> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.length == 0) {
return Center(
child: Text(
'No data available for downloads',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.w300, fontSize: 18),
));
} else {
return AnimationLimiter(
child: GridView.count(
shrinkWrap: true,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 24),
physics: BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics()),
crossAxisCount: 2,
childAspectRatio: 0.6,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
children: snapshot.data.map((wallpaper) {
return AnimationConfiguration.staggeredGrid(
position: 2,
duration: Duration(milliseconds: 500),
columnCount: 3,
child: ScaleAnimation(
duration: Duration(milliseconds: 900),
curve: Curves.fastLinearToSlowEaseIn,
scale: 1.5,
child: FadeInAnimation(
child: GridTile(
child: GestureDetector(
onTap: () {
Get.toNamed(
'/image_view',
arguments: [
wallpapers[index].src.portrait,
wallpapers[index].photographer,
wallpapers[index].photographerUrl
],
);
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Hero(
tag: 'picture:${wallpaper.imageUrl}',
child: Image.memory(
wallpaper.picture,
fit: BoxFit.cover,
),
),
),
),
),
),
),
),
);
}).toList(),
),
);
}
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
imageVeiw.dart
class LocalImageView extends StatelessWidget {
final Uint8List pictureBytes;
final String imageUrl;
final String title;
LocalImageView({this.pictureBytes, this.imageUrl, this.title});
#override
Widget build(BuildContext context) {
print(imageUrl);
return Container(
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
reverse: true,
scrollDirection: Axis.horizontal,
child: SizedBox(
height: constraints.biggest.height,
child: Hero(
tag: 'picture:$imageUrl',
child: Image.memory(
pictureBytes,
fit: BoxFit.cover,
),
),
),
),
),
);
}
}

How to create multiple horizontal `GridView` in the same screen using flutter

Is there's a way to create a lists of GridViews as the below image in one screen...
I have a some Screen as the below one:
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
var _showOnlyFavorites = false;
AnimationController animationController;
bool multiple = true;
#override
void initState() {
animationController = AnimationController(
duration: const Duration(milliseconds: 2000), vsync: this);
super.initState();
}
Future<bool> getData() async {
await Future<dynamic>.delayed(const Duration(milliseconds: 0));
return true;
}
#override
void dispose() {
animationController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppTheme.white,
body: FutureBuilder<bool>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
} else {
return Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
appBar(),
Expanded(
child: FutureBuilder<bool>(
future: getData(),
builder:
(BuildContext context, AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return const SizedBox();
} else {
return PropertiesGrid(_showOnlyFavorites);
}
},
),
),
],
),
);
}
},
),
);
}
Widget appBar() {
return SizedBox(
height: AppBar().preferredSize.height,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 8, left: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
),
),
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.only(top: 4),
child:
Image.asset('assets/images/logo.png', fit: BoxFit.contain),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 8, right: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
color: Colors.white,
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius:
BorderRadius.circular(AppBar().preferredSize.height),
child: Icon(
multiple ? Icons.dashboard : Icons.view_agenda,
color: AppTheme.dark_grey,
),
onTap: () {
setState(() {
multiple = !multiple;
});
},
),
),
),
),
],
),
);
}
}
as I have a widget which have the GridView.builder as the below code:
import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/properties.dart';
import './property_item.dart';
class PropertiesGrid extends StatelessWidget {
final bool showFavs;
PropertiesGrid(this.showFavs);
#override
Widget build(BuildContext context) {
final productsData = Provider.of<Properties>(context);
final products = showFavs ? productsData.favoriteItems : productsData.items;
return GridView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: products.length,
itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
// builder: (c) => products[i],
value: products[i],
child: PropertyItem(
// products[i].id,
// products[i].title,
// products[i].imageUrl,
),
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
childAspectRatio: 3 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
), scrollDirection: Axis.horizontal,
);
}
}
I tried to set the height of the grid by wrapping it with a Container and set the height of it as to add more grids but it doesn't work.
and here's my Grid Item widget code:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/property.dart';
class PropertyItem extends StatelessWidget {
#override
Widget build(BuildContext context) {
final property = Provider.of<Property>(context, listen: false);
return InkWell(
onTap: () => {},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 7,
margin: EdgeInsets.all(2),
child: Stack(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
),
// color: Colors.transparent,
child: Image.asset(
property.image,
fit: BoxFit.fill,
),
),
Positioned(
top: 8,
right: 8,
child: Consumer<Property>(
builder: (ctx, property, _) => IconButton(
icon: Icon(
property.isFavorite ? Icons.favorite : Icons.favorite_border,
),
color: Colors.red,
onPressed: () {
property.toggleFavoriteStatus();
},
),
),
),
Positioned(
right: 20,
top: 100,
child: Container(
width: 300,
color: Colors.black54,
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 20,
),
child: Text(
property.title,
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
softWrap: true,
overflow: TextOverflow.fade,
),
),
)
],
),
),
);
}
}
You'll need a column where each ListView or GridView is wrapped inside a SizedBox (if you have a specific height) and you also can use Expanded to take whatever available space (like the last one in the given example):
You can post the code below in dartpad.dev and see how it works:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
SizedBox(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 10,
itemBuilder: (c, i) {
return Card(
child: Container(
height: 100,
width: 100,
child: Center(child: Text("$i")),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Align(
child: Text("The Second List"),
alignment: Alignment.centerRight,
),
),
SizedBox(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 10,
itemBuilder: (c, i) {
return Card(
child: Container(
height: 100,
width: 100,
child: Center(child: Text("$i")),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Align(
child: Text("The Third List"),
alignment: Alignment.centerRight,
),
),
Expanded(
//height: 200,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 3 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
scrollDirection: Axis.vertical,
itemCount: 20,
itemBuilder: (c, i) {
return Card(
child: Container(
height: 100,
width: 100,
child: Center(child: Text("$i")),
),
);
},
),
),
],
),
);
}
}