how create GridView with ViewPager in flutter - flutter

I am trying to create the grid view inside the page view, what I want is,
In grid view, I want to display only 6 items and other items I want go to another page of the page view, what I mean is I only want 6 items on each page of the page view,
To clarify more, if I have 6 items, the page view will create only one page in which 6 items will appear from the gridview, or if I have 12 items, the page view will create two pages and each page will display 6 items from the gridview, or if I have 16 items, the page view will create three Pages per page 6 items, etc.,
This is the code that I tried to do, but it did not work. Can someone help me with it? Thank you
Expanded(
child: Container(
decoration: const BoxDecoration(
color: Color(0xFFE6E6E6),
image: DecorationImage(
image: AssetImage('assets/images/background_image.png'),
fit: BoxFit.fill,
),
),
child: PageView.builder(
controller: _controller,
physics: const BouncingScrollPhysics(),
itemCount: items.length % 6,
itemBuilder: (context, index) => GridView.builder(
padding:
EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 20.w,
mainAxisSpacing: 20.h,
childAspectRatio: 4 / 1.5,
),
itemCount: items.length,
primary: false,
itemBuilder: (context, index) => Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.r),
),
child: Row(
children: [
Container(
width: 140.w,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.r),
image: DecorationImage(
image: NetworkImage(
items[index].photoUrl,
),
fit: BoxFit.cover,
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 16.w,
vertical: 18.h,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
items[index].categoryName,
style: TextStyle(
fontSize: 10.sp,
color: const Color(0xFFBCBCBC),
),
),
Text(
items[index].itemName,
style: TextStyle(
fontSize: 12.sp,
color: const Color(0xFFFC4747),
fontWeight: FontWeight.bold,
),
),
const Spacer(),
Text(
'${items[index].price}د.ع',
style: TextStyle(
color: const Color(0xFF40484E),
fontSize: 12.sp,
),
),
Row(
children: [
Icon(
CupertinoIcons.time,
size: 8.sp,
color: const Color(0xFFBCBCBC),
),
Text(
'${items[index].time}m',
style: TextStyle(
fontSize: 8.sp,
color: const Color(0xFFBCBCBC),
),
),
],
)
],
),
),
)
],
),
),
),
),
),
),
A picture showing the shape of the elements

I modified your code the way you wanted Here is the solution :
My modified code will divide your main list into to small lists with 6 items. Here I take main list length is 16 so it's divide into 6 : 6 : 4 items lists.
Output :
Code :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<int> items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var gridViewLists = [];
int listBreakerSize = 6;
#override
void initState() {
for (var i = 0; i < items.length; i += listBreakerSize) {
gridViewLists.add(items.sublist(
i, i + listBreakerSize > items.length ? items.length : i + listBreakerSize));
}
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: Container(
margin: EdgeInsets.only(top: 40),
decoration: const BoxDecoration(
color: Color(0xFFE6E6E6),
),
child: PageView.builder(
// controller: _controller,
physics: const BouncingScrollPhysics(),
itemCount: (items.length / 6).ceil(),
itemBuilder: (context, i) => GridView.builder(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 4 / 1.5,
),
itemCount: gridViewLists[i].length,
primary: false,
itemBuilder: (context, index) => Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
),
child: Row(
children: [
Container(
width: 116,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(15),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 18,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
//items[index].categoryName,
'categoryName',
style: TextStyle(
fontSize: 10,
color: const Color(0xFFBCBCBC),
),
),
Text(
//items[index].itemName,
'itemName',
style: TextStyle(
fontSize: 12,
color: const Color(0xFFFC4747),
fontWeight: FontWeight.bold,
),
),
const Spacer(),
Text(
// '${items[index].price}د.ع',
'price',
style: TextStyle(
color: const Color(0xFF40484E),
fontSize: 12,
),
),
Row(
children: [
Icon(
CupertinoIcons.time,
size: 8,
color: const Color(0xFFBCBCBC),
),
Text(
//'${items[index].time}m',
'time',
style: TextStyle(
fontSize: 8,
color: const Color(0xFFBCBCBC),
),
),
],
)
],
),
),
)
],
),
),
),
),
),
),
],
);
}
}

Related

How to set number of elements to show in a CarouselSlider per page, using carousel_slider in flutter

I'm creating a vertical carousel slider using carousel_slider but there's a huge empty space between elements and I can't display the previous element on the screen. What is the best way to remove the empty space and also show the previous element.
My screen is set as follows
Column(
children: [
Container(
margin: const EdgeInsets.fromLTRB(16, 16, 16, 16),
child: TextField(
controller: controller,
),
),
//Carousel built here
Expanded(
child: CarouselSlider.builder(
itemCount: cars.length,
itemBuilder: (context, index, pageViewIndex) => CarTile(
car: cars[index],
onpress: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CarDetailsScreen(car: cars[index]))),
),
options: CarouselOptions(
scrollDirection: Axis.vertical,
enlargeCenterPage: true,
),
),
),
],
);
CarTile code is as follows:
class CarTile extends StatelessWidget {
final Car car;
final VoidCallback onpress;
const CarTile({super.key, required this.onpress, required this.car});
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return GestureDetector(
onTap: onpress,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
child: Column(
children: [
Image.network(
height: 150,
width: size.width,
fit: BoxFit.fitWidth,
car.image,
),
const SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Row(
children: [
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(5)),
child: Text(
car.features[0],
style: const TextStyle(fontWeight: FontWeight.w500),
),
),
const SizedBox(
width: 5,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(5)),
child: Text(
car.features[1],
style: const TextStyle(fontWeight: FontWeight.w500),
),
),
],
),
),
Row(
children: [
Text(
'${car.brand} ${car.model}',
style: const TextStyle(fontWeight: FontWeight.w900),
),
const Spacer(),
Text(
'Tsh. ${NumberFormat.decimalPattern().format(car.price)} / hr',
style: const TextStyle(fontWeight: FontWeight.w900),
),
],
),
Align(alignment: Alignment.centerLeft, child: Text('${car.year}'))
],
),
),
);
}
}
And this is my current results

When i run my code it show error like this one i dont really what went wrong.FlutterError (setState() or markNeedsBuild() called during build

Exception has occurred.
FlutterError (setState() or markNeedsBuild() called during build.
This Obx widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
Obx
The widget which was currently being built when the offending call was made was:
MediaQuery)
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final HomeController homeController = Get.find();
final String title;
final db = DatabaseHelper();
#override
Widget build(context) {
return Scaffold(
extendBodyBehindAppBar: true,
body: CustomScrollView(shrinkWrap: true, slivers: [
SliverAppBar(
shadowColor: Colors.transparent,
stretch: true,
pinned: true,
backgroundColor: Colors.white.withAlpha(0).withOpacity(0),
flexibleSpace: ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: Container(color: Colors.transparent),
),
),
actions: [
TextButton(
onPressed: () {
Get.toNamed('/temp');
},
child: const Text(
"Today",
style: TextStyle(
color: Color.fromARGB(255, 1, 132, 127), fontSize: 16),
),
)
],
title: Text(
title,
style: const TextStyle(color: Colors.teal),
),
),
SliverPersistentHeader(
pinned: true,
delegate: MyDelegate(header()),
),
adapter(sliverBuild()),
]),
floatingActionButton: FloatingActionButton(
onPressed: () {
Get.toNamed('/addSchedule');
},
tooltip: 'Add New Schedule',
child: const Icon(Icons.add),
),
);
}
//////////////////////////////////////////////////////////////////////////////
Widget adapter(Widget widget) {
return SliverToBoxAdapter(
child: widget,
);
}
///////////////////////////////// sliverheader//////////////////////////////////
Widget header() {
List<String> tabs = ["S", "M", "T", "W", "T", "F", "S"];
return ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: Container(
color: Colors.white.withOpacity(0.8).withAlpha(0),
child: Column(
children: [
GridView.builder(
itemCount: 7,
itemBuilder: (context, index) {
return Obx(
() => Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
margin: const EdgeInsets.only(left: 4, right: 4),
color: homeController.isDay[index]
? Colors.amber
: Colors.white,
child: InkWell(
splashColor: Colors.teal,
onTap: () {},
child: Column(
children: [
Text(
style: TextStyle(
color: homeController.isDay[index]
? Colors.white
: const Color.fromARGB(
255, 188, 193, 205),
fontSize: 20),
tabs[index],
),
Text(homeController
.theDays()[index]
.toString()
.padLeft(2, '0'))
],
),
),
),
);
},
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 7,
),
shrinkWrap: true,
),
Padding(
padding: const EdgeInsets.only(left: 10, top: 5),
child: Row(children: [
const Text("Time",
style: TextStyle(
color: Color.fromARGB(255, 188, 193, 205),
fontSize: 16)),
const SizedBox(width: 100),
const Text("Subject",
style: TextStyle(
color: Color.fromARGB(255, 188, 193, 205),
fontSize: 16)),
const SizedBox(width: 130),
IconButton(
onPressed: () {},
splashColor: Colors.teal,
icon: const FaIcon(
FontAwesomeIcons.arrowDownWideShort,
color: Color.fromARGB(255, 188, 193, 205),
),
)
]),
),
],
),
),
),
);
}
Widget subDetail(int index) {
var shour = homeController.scheduleList[index].dateTimeRange!.start.hour
.toString()
.padLeft(2, '0');
var sminute = homeController.scheduleList[index].dateTimeRange!.start.minute
.toString()
.padLeft(2, '0');
var ehour = homeController.scheduleList[index].dateTimeRange!.end.hour
.toString()
.padLeft(2, '0');
var eminute = homeController.scheduleList[index].dateTimeRange!.end.minute
.toString()
.padLeft(2, '0');
var duration = homeController.scheduleList[index].dateTimeRange!.end
.difference(homeController.dateTime.value)
.inDays;
if (duration < 0) {
homeController.removeSchedule(homeController.scheduleList[index]);
}
return Row(
children: [
Column(children: [
Container(
margin: const EdgeInsets.only(top: 10),
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text("$shour:$sminute",
style: TextStyle(
color: Colors.black.withAlpha(180), fontSize: 16)),
),
),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(
"$ehour:$eminute",
style: const TextStyle(
color: Color.fromARGB(255, 188, 193, 205), fontSize: 16),
),
)
]),
VerticalDivider(
color: Colors.black.withOpacity(0.5),
thickness: 2,
),
Card(
margin: const EdgeInsets.all(10),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
color: const Color.fromARGB(255, 230, 243, 242),
child: SizedBox(
height: 220,
width: 280,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
margin: const EdgeInsets.only(left: 10, top: 10),
child: Text(
homeController.scheduleList[index].subject,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
),
const Expanded(child: SizedBox(width: 160)),
PopupMenuButton(
onSelected: (value) {
if (value == 0) {
homeController.removeSchedule(
homeController.scheduleList[index]);
}
},
itemBuilder: (context) => const [
PopupMenuItem(value: 0, child: Text("Delete")),
PopupMenuItem(value: 1, child: Text("Update")),
PopupMenuItem(value: 2, child: Text("Extend")),
],
icon: const Icon(Icons.more_vert),
),
],
),
const SizedBox(height: 20),
Expanded(
child: Container(
margin: const EdgeInsets.only(left: 10, top: 10),
child: Text(
homeController.scheduleList[index].chapter,
style: const TextStyle(
color: Color.fromARGB(255, 112, 112, 112),
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
),
const SizedBox(height: 60),
Row(
children: [
const SizedBox(width: 10),
const Icon(
Icons.timer,
size: 18,
),
Text(" $duration days left for the Chapter",
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 112, 112, 112)))
],
),
Row(
children: const [
SizedBox(width: 240),
Icon(Icons.radio_button_off,
size: 20, color: Color.fromARGB(255, 196, 196, 196)),
],
),
const SizedBox(height: 10),
],
),
),
),
],
);
}
Widget sliverBuild() {
return Column(
children: [
Obx(
() => GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1),
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: homeController.scheduleList.length,
itemBuilder: (context, index) {
return subDetail(index);
}),
),
const SizedBox(height: 20)
],
);
}
}

Flutter-Renderflex overflow error on each item in GridView.builder()

In my project i need to display a grid of products,2 in each row. For that I am using GridView.builder() as follows :
#override
Widget build(BuildContext context) {
return Column(
children: [
const Text('New Arrivals'),
const SizedBox(height: 10),
Expanded(
child: Consumer<HomeViewModel>(
builder: (context, model, child) {
if (model.state == ViewState.idle) {
if (model.products.isEmpty) {
return const Center(
child: CircularProgressIndicator(color: Colors.black),
);
}
return GridView.builder(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemBuilder: (context, index) =>
ProductItem(product: model.products[index]),
itemCount: model.products.length,
);
}
return const Center(
child: CircularProgressIndicator(color: Colors.black),
);
},
),
),
],
);
}
However, this is giving an A RenderFlex overflowed by 49 pixels on the bottom. error on each item. The no. of pixels overflowed is different for different item.I have attached the screenshot for reference. What am I doing wrong and how do I fix it?
product_item.dart:
class ProductItem extends StatelessWidget {
const ProductItem({Key? key, required this.product}) : super(key: key);
final Product product;
#override
Widget build(BuildContext context) {
return Container(
width: 200,
color: Colors.white,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
height: 150,
child: Image.network(product.imageUrl!),
),
const SizedBox(height: 13),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(
product.category!,
softWrap: true,
style: const TextStyle(
fontSize: 10,
color: Colors.deepPurple,
height: 1.5,
fontWeight: FontWeight.w500,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(
product.title!,
softWrap: true,
style: const TextStyle(
color: Colors.black54,
fontSize: 12,
height: 1.8,
fontWeight: FontWeight.w500,
),
),
),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'\$ ${product.price!}',
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w600,
height: 2.4,
),
),
Image.asset('assets/icons/cart_icon.png',
width: 40, height: 40),
],
),
)
],
),
);
}
}
the problem "should" lie within:
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(
product.title!,
softWrap: true,
style: const TextStyle(
color: Colors.black54,
fontSize: 12,
height: 1.8,
fontWeight: FontWeight.w500,
),
),
),
try using: AutoSizeText instead of Text
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: AutoSizeText(
product.title!,
softWrap: true,
maxLines: 1,
style: const TextStyle(
color: Colors.black54,
fontSize: 12,
height: 1.8,
fontWeight: FontWeight.w500,
),
),
),
Default childAspectRatio is 1 on GridView. The issue arise because it is not fitting inside the square. Item's size is depending on screen width. And width is controlling the height,=> aspect ratio.
You can play with size of grid item using childAspectRatio:width/height. Alternative, you can follow #Maurizio Mancini's answer.
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 3 / 4,//this
),
I have used your code to reproduce the issue. If I understood your needs right, here is the fix:
The main problem is related to childAspectRatio.
return GridView.builder(
shrinkWrap: true,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 0.75,
),
itemBuilder: (context, index) =>
ProductItem(product: model.products[index]),
itemCount: model.products.length,
);
So you need to set the aspect ratio similar to this to fix the problem.
You can access the working source code through GitHub.

flutter i get a spacing in my listview design

i keep getting spacing like this on my app when i use the code below
class SellerProductList extends StatelessWidget {
const SellerProductList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final userId = ModalRoute.of(context)!.settings.arguments as String;
final productProvider = Provider.of<ProductProvider>(context);
List<Product> productsList = productProvider.getBySellerIds(userId);
return Column(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Suggestion Products',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
TextButton(
onPressed: () {
Navigator.of(context).pushNamed(
FeedsScreen.routeName,
arguments: 'popular',
);
},
child: const Text('view all')),
],
),
),
Container(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: SizedBox(
width: double.infinity,
child: GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: productsList.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 2 / 3,
mainAxisSpacing: 0,
crossAxisSpacing: 10),
itemBuilder: (ctx, i) {
return ChangeNotifierProvider.value(
value: productsList[i],
child: const MainProduct(),
);
},
),
),
),
),
],
),
],
);
}
}
and this is the code that i use for the MainProduct()
the design of my listview product
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:toko_kita/models%20&%20providers/product.dart';
import 'package:toko_kita/screens/inner_screens/product_details_screen.dart';
class MainProduct extends StatefulWidget {
const MainProduct({Key? key}) : super(key: key);
#override
_MainProductState createState() => _MainProductState();
}
class _MainProductState extends State<MainProduct> {
#override
Widget build(BuildContext context) {
final productAttribute = Provider.of<Product>(context);
return InkWell(
onTap: () {
Navigator.of(context).pushNamed(ProductDetailsScreen.routeName,
arguments: productAttribute.id);
},
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
),
child: Column(
children: [
Stack(
children: [
Column(
children: [
Positioned(
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: SizedBox(
height: 210,
width: 210,
child: FittedBox(
clipBehavior: Clip.hardEdge,
fit: BoxFit.cover,
child: Image.network(productAttribute.imageUrl)),
),
),
),
],
),
],
),
Padding(
padding: const EdgeInsets.only(left: 8, right: 8),
child: Container(
width: double.infinity,
height: 60,
decoration: const BoxDecoration(
color: Colors.white,
),
child: Column(
children: [
const SizedBox(
height: 8,
),
Container(
alignment: Alignment.centerLeft,
child: Text(
productAttribute.title,
maxLines: 2,
style: const TextStyle(
fontSize: 15,
overflow: TextOverflow.ellipsis,
),
textAlign: TextAlign.start,
),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'\$ ${productAttribute.price}',
maxLines: 1,
style: const TextStyle(
fontSize: 16,
color: Colors.red,
overflow: TextOverflow.ellipsis,
),
),
Text(
'Sisa ${productAttribute.quantity}',
maxLines: 1,
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
overflow: TextOverflow.ellipsis,
),
),
],
),
],
),
),
),
],
),
),
);
}
}
i havent use any sizedBox or any container widget to make of the top spacing. this just show on the top my listview. the other item didnt have any spacing that far. this is the listview i got in my phone
GridView widget has a default padding, try to remove the padding by giving it a padding of EgdeInsets.zero or the one you want.

when i use ListView.builder it show error

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class GameQuiz extends StatefulWidget {
const GameQuiz({Key? key}) : super(key: key);
#override
_GameQuizState createState() => _GameQuizState();
}
class _GameQuizState extends State<GameQuiz> {
List options = ["option 1", "option 2", "option 3", "option 4"];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
color: Colors.deepPurple,
image: DecorationImage(
image: AssetImage(
"assets/images/background.jpg",
),
fit: BoxFit.cover),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 100, 20, 0),
child: Column(children: [
Text(
"Animal Kingdom Quiz",
style: GoogleFonts.fredokaOne(
color: Colors.white,
fontSize: 40,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 60, 20, 20),
child: Container(
width: MediaQuery.of(context).size.width - 40,
decoration:
BoxDecoration(color: Colors.purple.withOpacity(0.3)),
child: Padding(
padding: const EdgeInsets.only(top: 30),
child: Column(
children: [
Text(
"My Question",
style: GoogleFonts.fredokaOne(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold),
)
ListView.builder(
itemCount: options.length,
itemBuilder: (context , index){
return Text(options[index]);
}),
],
),
),
),
),
]),
),
),
);
}
}
inside your ListView.builder use 'shrinkWrap: true' like this
class GameQuiz extends StatefulWidget {
const GameQuiz({Key? key}) : super(key: key);
#override
_GameQuizState createState() => _GameQuizState();
}
class _GameQuizState extends State<GameQuiz> {
List options = ["option 1", "option 2", "option 3", "option 4"];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
color: Colors.deepPurple,
image: DecorationImage(
image: AssetImage(
"assets/images/background.jpg",
),
fit: BoxFit.cover),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 100, 20, 0),
child: Column(children: [
Text(
"Animal Kingdom Quiz",
style: GoogleFonts.fredokaOne(
color: Colors.white,
fontSize: 40,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 60, 20, 20),
child: Container(
width: MediaQuery.of(context).size.width - 40,
decoration:
BoxDecoration(color: Colors.purple.withOpacity(0.3)),
child: Padding(
padding: const EdgeInsets.only(top: 30),
child: Column(
children: [
Text(
"My Question",
style: GoogleFonts.fredokaOne(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold),
),
ListView.builder(
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (context , index){
return Text(options[index]);
}),
],
),
),
),
),
]),
),
),
);
}
}
You can use shrinkWrap: true, on ListView.
ListView.builder(
itemCount: options.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return Text(options[index]);
},
),
More about shrinkWrap.