for a while now, I was trying to learn Flutter for mobile development. So, everything is straight forward and easy to grasp.
But, the following issues I cannot seem to solve:
Resizing the CircleAvatar() in the AppBar: I tried using scale, size, nothing worked.
Whatever I added after the 1st ListView.builder(), the emulator does not read/ display
my flutter is up-to-date and no errors/issues are shown when I run flutter doctor or my run the app.
Thanks
Code Used:
class MessageScreen extends StatefulWidget {
static Route<dynamic> route() => MaterialPageRoute(
builder: (context) => MessageScreen(),
);
#override
_MessageScreenState createState() => _MessageScreenState();
}
class _MessageScreenState extends State<MessageScreen> {
String tempLink =
'https://images.unsplash.com/photo-1599566150163-29194dcaad36?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[400],
appBar: AppBar(
elevation: 0.0,
leading: CircleAvatar(
backgroundImage: NetworkImage(tempLink),
radius: 15.0,
child: tempLink == null ? Text('HH') : null,
),
title: Text('Chats'),
backgroundColor: Colors.blue[400],
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.search),
),
],
),
body: Column(
children: [
Row(
children: [
Container(
child: ListView.builder(
itemCount: newMatching.length,
padding: EdgeInsets.only(left: 6),
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ChatScreen(
user: newMatching[index],
),
),
),
child: _profileButton(tempLink),
);
},
),
),
],
),
SizedBox(
height: 18,
),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
),
child: ListView.builder(
itemCount: chats.length,
itemBuilder: (BuildContext context, int index) {
final Message chat = chats[index];
return GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ChatScreen(
user: chat.sender,
),
),
),
child: Container(
margin: EdgeInsets.only(top: 5, bottom: 5, right: 1),
padding:
EdgeInsets.symmetric(horizontal: 2, vertical: 5),
decoration: BoxDecoration(
color: chat.unread ? Color(0xFFFFEFEE) : Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(20.0),
bottomRight: Radius.circular(20.0),
),
),
child: _chatNavigatorButton(
chat.sender.imgAvatar,
chat.sender.fname,
chat.text,
chat.time,
chat.unread)),
);
}),
),
],
),
);
}
}
Try wrapping the CircleAvatar with a Container:
Container(height: 10, width: 10, child: CircleAvatar(...))
Is there a chance that chats simply has the length of 0 and no elements? Maybe the second ListView.builder() does display correctly but includes no items. At least that's what I can retrieve from the given code.
Related
im facing a problem with TextFormField which when i type anything on the keyboard it doesn't appear in the text field, im trying doing a chat application with BLOC. Note : when i remove this line...emit(SocialGetMessageSuccessState()); i can type normaly and the problem is gone but 2 bugs appear..first one is that when i enter chat with someone the older messages don't appear unless i send him a new message...second one is when i enter a different chat with someone else the messages of the first user appears to the other user and to solve this one i should exit the chat page and enter again to see the messages of the wanted user that i currenlty chatting him/
the problem is when i type any character on the keyboard it won't print in the text field and it gives me this :
getTextBeforeCursor on inactive InputConnection
getSelectedText on inactive InputConnection
getTextAfterCursor on inactive InputConnection
here is my code
List<SocialUserModel> users =[];
void getUsers()
{
if(users.length ==0)
FirebaseFirestore.instance.collection('users').get().then((value)
{
value.docs.forEach((element)
{
if(element.data()['uId'] != userModel!.uId)
users.add(SocialUserModel.fromJson(element.data()));
});
emit(SocialGetAllUsersSuccessState());
})
.catchError((error){
emit(SocialGetAllUsersErrorState(error.toString()));
});
}
void sendMessage({
required String receiverId,
required String dateTime,
required String text,
})
{
MessageModel model = MessageModel(
text: text,
senderId: userModel!.uId,
receiverId: receiverId,
dateTime: dateTime,
);
// set my chats
FirebaseFirestore.instance
.collection('users')
.doc(userModel!.uId)
.collection('chats')
.doc(receiverId)
.collection('messages')
.add(model.toMap())
.then((value){
emit(SocialSendMessageSuccessState());
})
.catchError((error)
{
emit(SocialSendMessageErrorState());
});
// set receiver chats
FirebaseFirestore.instance
.collection('users')
.doc(receiverId)
.collection('chats')
.doc(userModel!.uId)
.collection('messages')
.add(model.toMap())
.then((value){
emit(SocialSendMessageSuccessState());
})
.catchError((error)
{
emit(SocialSendMessageErrorState());
});
}
List<MessageModel> messages = [];
void getMessages({
required String receiverId,
})
{
FirebaseFirestore.instance
.collection('users')
.doc(userModel!.uId!)
.collection('chats')
.doc(receiverId)
.collection('messages')
.orderBy('dateTime')
.snapshots()
.listen((event)
{
messages=[];
event.docs.forEach((element)
{
messages.add(MessageModel.fromJson(element.data()));
});
emit(SocialGetMessageSuccessState());
});
}
//getUser screen
class ChatsScreen extends StatelessWidget {
const ChatsScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocConsumer<SocialCubit,SocialStates>(
listener: (context,state){},
builder: (context,state)
{
return ConditionalBuilder(
condition: SocialCubit.get(context).users.length > 0,
builder: (context) => ListView.separated(
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) => buildChatItem(context,SocialCubit.get(context).users[index]),
separatorBuilder: (context, index) => SizedBox(height:1),
itemCount: SocialCubit.get(context).users.length
),
fallback: (context) => Center(child: CircularProgressIndicator()),
);
}
);
}
Widget buildChatItem(BuildContext context,SocialUserModel model) => InkWell(
onTap: ()
{
Navigator.push(context, MaterialPageRoute(builder: (context) => ChatDetailsScreen(userModel: model)));
},
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children:
[
CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(
'${model.image}'
),
),
SizedBox(width: 15,),
Row(
children: [
Text(
'${model.name}',
),
],
),
],
),
),
);
}
//ChatScreen
class ChatDetailsScreen extends StatelessWidget {
SocialUserModel? userModel;
final messageController = TextEditingController();
ChatDetailsScreen({this.userModel}) {}
#override
Widget build (context) {
return Builder(
builder: (context)
{
SocialCubit.get(context).getMessages(receiverId: userModel!.uId!);
return BlocConsumer<SocialCubit,SocialStates>(
listener: (context,state) {},
builder: (context,state)
{
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: Row(
children: [
CircleAvatar(
radius: 20,
backgroundImage: NetworkImage(userModel!.image!),
),
SizedBox(
width: 15,
),
Text(
userModel!.name!,
)
],
),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Expanded(
child: ListView.separated(
physics: BouncingScrollPhysics(),
itemBuilder: (context,index)
{
var message = SocialCubit.get(context).messages[index];
if(SocialCubit.get(context).userModel!.uId == message.senderId)
return buildMyMessage(message);
return buildMessage(message);
},
separatorBuilder: (context,index) => SizedBox(height: 7,),
itemCount: SocialCubit.get(context).messages.length
),
),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey[300]!,
width: 1,
),
borderRadius: BorderRadius.circular(15)
),
clipBehavior: Clip.antiAliasWithSaveLayer,
child: Row(
children:
[
SizedBox(width: 10,),
Expanded(
child: TextFormField(
controller: messageController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'type your message here...',
),
),
),
Container(
height: 50,
color: Colors.blue,
child: MaterialButton(onPressed:()
{
SocialCubit.get(context).sendMessage(
receiverId: userModel!.uId!,
dateTime: DateTime.now().toString(),
text: messageController.text,
);
},
minWidth: 1,
child: Icon(
IconBroken.Send,
size: 16,
color: Colors.white,
),),
)
],
),
)
],
),
),
);
}
);
}
);
}
Widget buildMessage(MessageModel model) => Align(
alignment: AlignmentDirectional.centerStart,
child: Container(
decoration:BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadiusDirectional.only(
bottomEnd: Radius.circular(10),
topEnd: Radius.circular(10),
topStart: Radius.circular(10),
)
),
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: Text(
model.text!,
),
),
);
Widget buildMyMessage(MessageModel model) => Align(
alignment: AlignmentDirectional.centerEnd,
child: Container(
decoration:BoxDecoration(
color: Colors.blue.withOpacity(.2),
borderRadius: BorderRadiusDirectional.only(
bottomStart: Radius.circular(10),
topEnd: Radius.circular(10),
topStart: Radius.circular(10),
)
),
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: Text(
model.text!,
),
),
);
}
sory if i can't explain..still newbie here
i solved the problem
i converted the stateless widget into stateful
I have a working filter button in search page of my app
I need to add it as floating button in other pages such as category, view all products etc
Here is the working filter button code for searchscreen.
class SearchProductWidget extends StatelessWidget {
final bool isViewScrollable;
final List<Product> products;
SearchProductWidget({this.isViewScrollable, this.products});
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
child: Column(
children: [
Row(
children: [
Expanded(
child: Text(
'Search result for \"${Provider.of<SearchProvider>(context).searchText}\" (${products.length} items)',
style: titilliumRegular.copyWith(
fontSize: Dimensions.FONT_SIZE_DEFAULT),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
InkWell(
onTap: () => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (c) => SearchFilterBottomSheet()),
child: Container(
padding: EdgeInsets.symmetric(
vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL,
horizontal: Dimensions.PADDING_SIZE_SMALL),
decoration: BoxDecoration(
color: ColorResources.getLowGreen(context),
borderRadius: BorderRadius.circular(5),
border: Border.all(
width: 1, color: Theme.of(context).hintColor),
),
child: Row(children: [
///Image.asset(Images.filter_image, width: 10, height: 10, color: ColorResources.getPrimary(context)),
SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
Text('Filter'),
]),
),
),
],
),
SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
Expanded(
child: StaggeredGridView.countBuilder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(0),
crossAxisCount: 2,
itemCount: products.length,
//shrinkWrap: true,
staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
itemBuilder: (BuildContext context, int index) {
return ProductWidget(productModel: products[index]);
},
),
),
],
),
);
}
}
I'm trying to create a floating action button to work as a filter in different screens
Here is one of the screen which I need the filter button working-
class AllProductScreen extends StatelessWidget {
final ScrollController _scrollController = ScrollController();
final ProductType productType;
AllProductScreen({#required this.productType});
// Future<void> _loadData(BuildContext context, bool reload) async {
// String _languageCode = Provider.of<LocalizationProvider>(context, listen: false).locale.countryCode;
// await Provider.of<BrandProvider>(context, listen: false).getBrandList(reload, context);
// await Provider.of<ProductProvider>(context, listen: false).getLatestProductList('1', context, _languageCode, reload: reload);
//
//
//
// }
#override
Widget build(BuildContext context) {
// _loadData(context, false);
return Scaffold(
backgroundColor: ColorResources.getHomeBg(context),
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Provider.of<ThemeProvider>(context).darkTheme
? Colors.black
: Theme.of(context).primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(5),
bottomLeft: Radius.circular(5))),
leading: IconButton(
icon:
Icon(Icons.arrow_back_ios, size: 20, color: ColorResources.WHITE),
onPressed: () => Navigator.of(context).pop(),
),
title: Text(
productType == ProductType.FEATURED_PRODUCT
? 'Featured Product'
: 'Latest Product',
style: titilliumRegular.copyWith(
fontSize: 20, color: ColorResources.WHITE)),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (c) => SearchFilterBottomSheet()),
icon: const Icon(Icons.filter_list),
label: const Text('Filter'),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: SafeArea(
child: RefreshIndicator(
backgroundColor: Theme.of(context).primaryColor,
onRefresh: () async {
// await _loadData(context, true);
return true;
},
child: CustomScrollView(
controller: _scrollController,
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
child: ProductView(
isHomePage: false,
productType: productType,
scrollController: _scrollController),
),
),
],
),
),
),
);
}
}
The exception I'm getting is
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by gesture ═══════════════════════════════════════════
The getter 'iterator' was called on null.
Receiver: null
Tried calling: iterator
I am trying to show two future builders with gridview in the column widget, but it is showing me one future builder of the department and not showing the other future builder when scrolling it. how to show the future builder of hot product? it will be helpful for me
import 'dart:convert';
import 'package:apipractice/Models/Category_model.dart';
import 'package:apipractice/Models/Department_model.dart';
import 'package:apipractice/Models/HotProduct_model.dart';
import 'package:apipractice/Screens/Department.dart';
import 'package:apipractice/Screens/cart.dart';
import 'package:apipractice/Screens/categorry.dart';
import 'package:apipractice/Screens/products.dart';
import 'package:apipractice/Screens/selected_Category.dart';
import 'package:apipractice/Screens/subCategory.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<HotProductModel> getHotProducts() async {
var data = jsonDecode(response.body);
if (response.statusCode == 200) {
return HotProductModel.fromJson(data[0]);
} else {
throw Exception('Failed to load album');
}
}
List images = [
"assets/Image1.jpeg",
"assets/Image2.jpeg",
"assets/Image3.jpeg",
"assets/Image4.jpeg",
"assets/Image5.jpeg",
"assets/Image6.jpeg",
];
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
child: ListTile(
leading: CircleAvatar(
child: Image(image: AssetImage("images/user.png")),
radius: 25,
),
title: Text(
"Username",
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text("abcuser#gmail.com"),
),
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Show Product'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Products()),
);
},
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Show Category'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Categorry()),
);
},
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Department'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Department()),
);
},
),
],
),
),
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 24, 119, 197),
title: Text("Dubai Super Store"),
actions: [
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => Cart()),
),
);
},
icon: Icon(Icons.shopping_cart))
],
),
body: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: EdgeInsets.all(10),
height: 35,
width: double.infinity,
child: TextField(
decoration: InputDecoration(
hoverColor: Colors.blue,
prefixIconColor: Colors.blue,
labelText: "Search Product",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
),
Text(
"Note: Free Delivery Above Rs.2000",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red.shade700,
fontSize: 17),
),
Container(
height: 200,
width: double.infinity,
child: CarouselSlider.builder(
itemCount: images.length,
options: CarouselOptions(
height: 400,
viewportFraction: 1,
autoPlay: true,
),
itemBuilder: (context, index, realindex) {
final urlImages = images[index];
return buildImage(urlImages, index);
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child: Column(
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Categorry()),
);
},
child: Image(
height: 70,
width: 70,
image: AssetImage("assets/Categories.jpeg"),
),
),
Text("Categories")
],
),
),
Container(
child: Column(
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SubCategory()),
);
},
child: Image(
height: 70,
width: 70,
image: AssetImage("assets/SubCategory.jpeg")),
),
Text("Sub Category")
],
),
)
],
),
SizedBox(height: 20),
Text(
"Department",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Color.fromARGB(255, 16, 113, 192)),
),
FutureBuilder<DepartmentModel>(
future: getDepartment(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: snapshot.data!.sKUDepartmentDetail!.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
var fetchid =
"${snapshot.data!.sKUDepartmentDetail![index].sKUDeptId}";
fetchCategory = fetchid;
setState(() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SelectedCategory()),
);
});
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
),
elevation: 10.0,
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
child: Stack(children: [
CachedNetworkImage(
imageUrl: snapshot
.data!
.sKUDepartmentDetail![index]
.imageUrl1!,
height: 150,
width: 200,
fit: BoxFit.fitWidth,
errorWidget: (context, url, error) {
return Image(
image: AssetImage(
"assets/placeholder.jpg"));
},
),
]),
),
Text(
snapshot
.data!.sKUDepartmentDetail![index].name!,
style: TextStyle(fontWeight: FontWeight.bold),
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
// SizedBox(height: 20),
Text(
"Hot Product",
style: TextStyle(fontSize: 20),
),
FutureBuilder<HotProductModel>(
future: getHotProducts(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data!.productDetail!.length,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(10),
),
boxShadow: [
BoxShadow(
color: Colors.black,
blurRadius: 3,
offset: Offset(1.0, 1.0),
)
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CachedNetworkImage(
imageUrl: snapshot.data!.productDetail![index]
.sKUImageURL1!,
height:
MediaQuery.of(context).size.height * 0.12,
width: double.infinity,
fit: BoxFit.fitWidth,
errorWidget: (context, url, error) {
return Image(
image: AssetImage(
"assets/placeholder.jpg"));
},
),
SizedBox(
height: 10,
),
Text(
"${snapshot.data!.productDetail![index].sKUName!}"),
Text(
"Rs: ${snapshot.data!.productDetail![index].salePrice!}",
style: TextStyle(
color: Colors.blue,
fontSize: 20,
fontWeight: FontWeight.bold),
),
Text(
"Rs: ${snapshot.data!.productDetail![index].retailPrice!}",
style: TextStyle(
decoration: TextDecoration.lineThrough,
color: Colors.red),
),
ElevatedButton(
onPressed: () {
var product = snapshot
.data!.productDetail![index].sKUId;
if (cartList.contains(product)) {
print("already exist");
} else {
cartList.add({
"Id": snapshot
.data!.productDetail![index].sKUId
});
}
},
child: Text("Add to Cart"))
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return CircularProgressIndicator();
}
})
],
),
),
);
}
This is the output of the code
[![output image][1]][1]
The problem is solved it is only not showing because of screen navigation bar now its fine
I was trying things out with ModalBottomSheet. How can I achieve 90% height of device screen size for modal sheet. I did mediaquery but still it does not give me more than half of the screen size. How do I solve this?
Here is the code:
class _TestFileState extends State<TestFile> {
modalSheet() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0), topRight: Radius.circular(15.0)),
),
builder: (context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
ListTile(
leading: Icon(Icons.email),
title: Text('Send email'),
onTap: () {
print('Send email');
},
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Call phone'),
onTap: () {
print('Call phone');
},
),
],
);
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Center(child: Text('Testing Modal Sheet')),
),
body: Center(
child: InkWell(
onTap: () {
modalSheet();
},
child: Container(
color: Colors.indigo,
height: 40,
width: 100,
child: Center(
child: Text(
'Click Me',
style: TextStyle(color: Colors.white),
),
)),
),
),
),
);
}
}
Here is the output:
you have to pass isScrollControlled: true and use mediaquery as given below
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) {
return Container(
height: MediaQuery.of(context).size.height * 0.5,
color: Colors.red,
//height: MediaQuery.of(context).size.height,
);
});
As I remember that's a restriction about the native implementation of Flutter modal bottom sheet.
You can use the package modal_bottom_sheet to achieve that.
Install:
dependencies:
modal_bottom_sheet: ^0.2.2
And minimal example:
showMaterialModalBottomSheet(
context: context,
expand: true, //this param expands full screen
builder: (context, scrollController) => Container(),
)
i need help to build a quiz app with flutter,
i use firestore for my data, and i want to add a multi choices question, so when a user tap on one choice, this one is highlighted, like this example
(i use this gif from another question, because i didn't know how to explain)
this is what i have for now
this is my code :
Widget _buildListItem(BuildContext context, DocumentSnapshot document) {
return ListTile(
title: Container(
margin: EdgeInsets.all(8.0),
padding: EdgeInsets.fromLTRB(210, 0.0, 0.0, 0.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.pink[800], // set border color
width: 3.0), // set border width
borderRadius: BorderRadius.all(
Radius.circular(10.0)), // set rounded corner radius
boxShadow: [
BoxShadow(
blurRadius: 5,
color: Colors.black,
offset: Offset(0.5, 1))
] // make rounded corner of border
),
child: Row(
children: <Widget>[
Container(
child: Text(
document['rep'],
style: TextStyle(
fontSize: 50.0,
color: Colors.black,
),
),
)
]
),
),
onTap: () {
Firestore.instance.runTransaction(
(transaction) async {
DocumentSnapshot freshSnap =
await transaction.get(document.reference);
await transaction.update(freshSnap.reference, {
'votes': freshSnap['votes'] + 1,
});
});
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: StreamBuilder(
stream: Firestore.instance.collection('questions').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Loading ...');
return ListView.builder(
padding: EdgeInsets.fromLTRB(50.0, 300.0, 50.0, 0.0),
itemExtent: 100.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListItem(context, snapshot.data.documents[index]),
);
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => new Home()));
},
child: Text("Home"),
),
);
}
thank you so much !
Wrap list tile with colored container :
itemBuilder: (context, index){
return Container(
color: isSelected[index] ? Colors.blue : null,
child: ListTile(title:'test'),
);
}
Change selection status when item is taped.
ListTile(
title: Text('test'),
selected: isSelected[index],
onTap: () {
setState(() {
isSelected[index] = !isSelected[index];
});
},
),
final List<bool> isSelected;
Try it on DartPad