Listviewbuilder implementation inside Column won't work - flutter

I want to have a scrollable list on my home screen. I tried to implement my Listviewbuilder called Cardslist() into the home screen, but I always get this exception thrown: RenderFlex children have non-zero flex, incoming height constraints are unbounded. Heres the code for the home screen:
import 'package:biminda_app/Components/cards_list.dart';
import 'package:biminda_app/Components/real_new_finished_card.dart';
import 'package:flutter/material.dart';
import 'package:biminda_app/Components/custom_Buttons.dart';
import 'package:biminda_app/Components/constants.dart';
import 'package:flutter/rendering.dart';
import 'package:biminda_app/Screens/new_card_screen1.dart';
import 'package:biminda_app/Screens/settings.dart';
import 'package:biminda_app/Components/card_data.dart';
import 'package:biminda_app/Components/cards_list.dart';
class HomeScreen extends StatefulWidget {
static const String id = 'home_screen';
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String individualsName;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(
20,
40,
20,
0,
),
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kTextFieldInputDecoration,
onChanged: (value) {
individualsName = value;
// TODO: Der Input muss das Individum in der Liste
// TODO: erkennen und anzeigen
},
),
),
//TODO HIER
Expanded(
child: Column(
children: <Widget>[
CardsList(),
],
)),
Center(
child: Container(
child: MainButton(
functionality: 'New',
onPressed: () {
Navigator.pushNamed(context, NewCard.id);
}),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SideButton(
functionality: 'Settings',
onPressed: () {
Navigator.pushNamed(context, Settings.id);
}),
SideButton(
functionality: 'Calendar',
onPressed: () {
Navigator.pushNamed(context, Settings.id);
}),
],
),
),
],
),
);
}
}
And here's the code for Cardslist():
class CardsList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<CardData>(builder: (context, cardData, child) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) {
final card = cardData.cards[index];
return FinalCardCreation(
finalname: card.cname,
finalbirthday: card.cbirthday,
);
});
});
}
}
The code for the created card FinalCardCreation():
class CardFinish extends StatefulWidget {
#override
CardFinishState createState() => CardFinishState();
}
class CardFinishState extends State<CardFinish> {
#override
Widget build(BuildContext context) {
return SizedBox(
height:
MediaQuery.of(context).size.height * 0.5, //<-- set height of the card
child: FinalCardCreation(),
);
}
}
class FinalCardCreation extends StatelessWidget {
String finalname;
String finalbirthday;
FinalCardCreation({
Key key,
#required this.finalname,
#required this.finalbirthday,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
color: Color(0xFFef9a9a),
margin: EdgeInsets.all(2),
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
child: Column(
children: <Widget>[
SizedBox(height: 8),
Expanded(
child: FinalCardContent(
name: finalname,
birthday: finalbirthday,
),
)
],
),
);
}
}
class FinalCardContent extends StatelessWidget {
String name;
String birthday;
FinalCardContent({Key key, #required this.name, #required this.birthday})
: super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'$name',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50.0,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'$birthday',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50.0,
color: Colors.black,
),
),
),
],
),
);
}
}
I tried to wrap my Cardslist() multiple ways but I always got this exception. Thank you for your time and answer.

Column is a widget that can grow infinitely in height. It does not impose any height constraints to its children. Expanded are a smart way to include ListViews in Column since they fit all the possible space of the Column on screen, but impose a constraint to their children.
You can either remove the Column wrapping your CardList or, if you really need that Column for other stuff later, try wrapping CardList in another Expanded.

Related

How do I fix my problem with routes in Flutter?

good evening. I am currently doing a To-do List in Flutter and I want to pass the Title of my List and the Description of my List when I click on a new screen but upon setting up Routes and and declaring the values on my next, it shows the "2 positional arguments expected, but 0 found" on the routes I've set up. Here are my codes:
Here is my 1st screen:
import 'package:flutter/material.dart';
import 'package:todo_list/details.dart';
import 'package:todo_list/note.dart';
class MyApp extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const MyApp(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
DetailsPage.routeName: (ctx) => DetailsPage(),
},
home: CustomListTile(
text: text,
number: number,
listDescription: listDescription,
),
);
}
}
class CustomListTile extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const CustomListTile(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, DetailsPage.routeName,
arguments: Note(title: text, description: listDescription));
},
/* onTap: () {
Widget okButton = TextButton(
child: const Text("CLOSE"),
onPressed: () {
Navigator.of(context).pop();
},
);
AlertDialog alert = AlertDialog(
title: Text(text),
content: Text('This item in the list contains $listDescription'),
actions: [
okButton,
]);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
});
}, */
child: Padding(
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("$number. $text",
style: const TextStyle(
fontSize: 20,
)),
const Icon(Icons.chevron_right)
],
),
Text(
listDescription,
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
const Divider()
],
),
),
);
}
}
and here is my 2nd screen:
import 'package:flutter/material.dart';
import 'note.dart';
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
#override
State<DetailsPage> createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
late Note params;
#override
void didChangeDependencies() {
params = ModalRoute.of(context)!.settings.arguments! as Note;
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
Widget titleSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(bottom: 0),
child: Text(
params.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
),
],
),
),
],
),
);
Color color = Theme.of(context).primaryColor;
Widget buttonSection = Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(
color,
Icons.edit,
'EDIT',
),
_buildButtonColumn(color, Icons.delete, 'DELETE'),
],
);
Widget textSection = Padding(
padding: const EdgeInsets.all(20),
child: Text(
params.description,
softWrap: true,
),
);
return MaterialApp(
title: 'Layout for a New Screen',
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(params.title),
),
body: ListView(
children: [
Image.asset(
'lib/images/placeholder.jpg',
width: 600,
height: 240,
fit: BoxFit.cover,
),
titleSection,
buttonSection,
textSection,
],
),
),
);
}
Column _buildButtonColumn(
Color color,
IconData icon,
String label,
) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
}
/* return Scaffold(
appBar: AppBar(title: Text(text)),
body: Center(
child: Row(
children: [Text(description)],
),
));
}
} */
How do I make it so that the data I'll pass such as the Title and the Description will appear on the 2nd screen without the error "2 positional argument(s) expected, but 0 found.
Try adding the missing arguments." appearing.
I tried the Quick Fixes on VS Code such as adding a const modifier but I think the const modifier wouldn't do a fix since both data I'm trying to pass are dynamic and may change from time to time.
As you've define details page
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
You need to pass two string as positional argument.
So it can be
routes: {
DetailsPage.routeName: (ctx) => DetailsPage("text","description"),
},
also while you are using route arguments, you can remove theses from widget class and just accept from state class context with ModalRoute.
You can check this example and development/ui/navigation .

How to change the colour of button on press to green and other buttons in row back to neutral

The idea behind this is i would like users to select their sex, sexual orientation and relationship status. So there would be a button in the first row saying "Male" another one saying "female" and another one saying "other". Below that there would be 3 other buttons saying "straight" "gay/lesbian" and "other" and below that another row with 3 buttons (options). Once the user clicks a button the button toggles on essentially and it goes from e.g black to green. I created the boolean toggleOn and will be setting to true or false on button press. The issue is right now i am getting an error on the screen and i think it is because i am going over the available pixels and singleChildScrollView does not work. Any ideas?
Also i am sorry if you are cringing right now i am just making a personal project to learn to code.
This is the screen where i would like to have 3 rows with 3 buttons each
import 'package:./components/rounded_button.dart';
import 'package:./screens/register_screen.dart';
import 'package:flutter/material.dart';
class UserRegisterPreferences extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Scaffold(
backgroundColor: Color(0xff1e1e1e),
body: Body(),
),
);
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
#override
Widget build(BuildContext context) {
bool toggleOn = false;
Size size = MediaQuery.of(context).size;
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
verticalDirection: VerticalDirection.down,
children: <Widget>[
Container(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
roundedButton(
press: () => setState(() => toggleOn = !toggleOn),
),
roundedButton(
press: () => setState(() => toggleOn = !toggleOn),
),
roundedButton(),
],
),
),
),
Column(
children: <Widget>[
roundedButton(),
roundedButton(),
roundedButton(),
],
),
Column(children: <Widget>[
roundedButton(),
roundedButton(),
roundedButton(),
]),
],
);
}
}
This is the file that contains the button so i can keep reusing on the app
import 'package:./constants.dart';
import 'package:flutter/material.dart';
// ignore: camel_case_types
class roundedButton extends StatelessWidget {
final String text;
final Function press;
final Color color, textColor;
const roundedButton({
Key key,
this.text,
this.press,
this.color = kPrimaryColor,
this.textColor = Colors.white,
}) : super(key: key);
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
width: size.width * 0.7,
child: ClipRRect(
borderRadius: BorderRadius.circular(29),
child: TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 40),
primary: Colors.white,
backgroundColor: kPrimaryColor,
),
onPressed: press,
child: Text(text),
),
),
);
}
}

Listview scrolling and selecting Textfield afterwards is freezing my app

I am using the package
country_code_picker: ^1.4.0
https://pub.dev/packages/country_code_picker#-installing-tab-
with flutter 1.17.3
Which is pretty much one of the only country code picker packages. But I have one serious problem an I don't have a clue what it could be.
When I run this code
import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
App();
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: TestWidget(),
);
}
}
class TestWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(body: _buildCountryPicker(context));
}
Widget _buildCountryPicker(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Center(
child: CountryCodePicker(
initialSelection: 'NL',
),
),
);
}
}
And I open the dialog to select a country. I scroll in the list and then select the TextField my keyboard opens and when I try to type something my entire app freezes. I can't even hot reload. I don't get a single error.
I am running this on my Huawei P30, but I also experience this on other android devices. I don't know if this is a flutter bug or a country code picker bug.
I think it is probably in this widget somewhere. If anyone could point me in the right direction it would help me alot!
class SelectionDialog extends StatefulWidget {
final List<CountryCode> elements;
final bool showCountryOnly;
final InputDecoration searchDecoration;
final TextStyle searchStyle;
final TextStyle textStyle;
final WidgetBuilder emptySearchBuilder;
final bool showFlag;
final double flagWidth;
final Size size;
final bool hideSearch;
/// elements passed as favorite
final List<CountryCode> favoriteElements;
SelectionDialog(
this.elements,
this.favoriteElements, {
Key key,
this.showCountryOnly,
this.emptySearchBuilder,
InputDecoration searchDecoration = const InputDecoration(),
this.searchStyle,
this.textStyle,
this.showFlag,
this.flagWidth = 32,
this.size,
this.hideSearch = false,
}) : assert(searchDecoration != null, 'searchDecoration must not be null!'),
this.searchDecoration =
searchDecoration.copyWith(prefixIcon: Icon(Icons.search)),
super(key: key);
#override
State<StatefulWidget> createState() => _SelectionDialogState();
}
class _SelectionDialogState extends State<SelectionDialog> {
/// this is useful for filtering purpose
List<CountryCode> filteredElements;
#override
Widget build(BuildContext context) => SimpleDialog(
titlePadding: const EdgeInsets.all(0),
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
IconButton(
padding: const EdgeInsets.all(0),
iconSize: 20,
icon: Icon(
Icons.close,
),
onPressed: () => Navigator.pop(context),
),
if (!widget.hideSearch)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextField(
style: widget.searchStyle,
decoration: widget.searchDecoration,
onChanged: _filterElements,
),
),
],
),
children: [
Container(
width: widget.size?.width ?? MediaQuery.of(context).size.width,
height:
widget.size?.height ?? MediaQuery.of(context).size.height * 0.7,
child: ListView(
children: [
widget.favoriteElements.isEmpty
? const DecoratedBox(decoration: BoxDecoration())
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...widget.favoriteElements.map(
(f) => SimpleDialogOption(
child: _buildOption(f),
onPressed: () {
_selectItem(f);
},
),
),
const Divider(),
],
),
if (filteredElements.isEmpty)
_buildEmptySearchWidget(context)
else
...filteredElements.map(
(e) => SimpleDialogOption(
key: Key(e.toLongString()),
child: _buildOption(e),
onPressed: () {
_selectItem(e);
},
),
),
],
),
),
],
);
Widget _buildOption(CountryCode e) {
return Container(
width: 400,
child: Flex(
direction: Axis.horizontal,
children: <Widget>[
if (widget.showFlag)
Flexible(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Image.asset(
e.flagUri,
package: 'country_code_picker',
width: widget.flagWidth,
),
),
),
Expanded(
flex: 4,
child: Text(
widget.showCountryOnly
? e.toCountryStringOnly()
: e.toLongString(),
overflow: TextOverflow.fade,
style: widget.textStyle,
),
),
],
),
);
}
Widget _buildEmptySearchWidget(BuildContext context) {
if (widget.emptySearchBuilder != null) {
return widget.emptySearchBuilder(context);
}
return Center(
child: Text('No country found'),
);
}
#override
void initState() {
filteredElements = widget.elements;
super.initState();
}
void _filterElements(String s) {
s = s.toUpperCase();
setState(() {
filteredElements = widget.elements
.where((e) =>
e.code.contains(s) ||
e.dialCode.contains(s) ||
e.name.toUpperCase().contains(s))
.toList();
});
}
void _selectItem(CountryCode e) {
Navigator.pop(context, e);
}
}
Also filed an issue on the flutter github https://github.com/flutter/flutter/issues/59886
Edit:
I have a video of it right here
https://www.youtube.com/watch?v=669KitFG9ek&feature=youtu.be
I just had to remove the keys, so there probably was a duplicate key
...filteredElements.map(
(e) => SimpleDialogOption(
//key: Key(e.toLongString()),
child: _buildOption(e),
onPressed: () {
_selectItem(e);
},
),
),

Using a variables information in other classes / Flutter

Thank you so much for reading and helping me out.
I'm currently building an app, where the user has to create a Card, which then will be displayed on the homepage inside a list. My problem is that I cant send the information of the two variables which save the user's input (name & birthday date) to the finished Card.
The desired variables which I want to navigate are contentname and contentbirthday.
Here's the part where the user enters the pieces of information:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'constants.dart';
class CardBasic extends StatefulWidget {
#override
_CardBasicState createState() => _CardBasicState();
}
class _CardBasicState extends State<CardBasic> {
#override
Widget build(BuildContext context) {
return SizedBox(
height: MediaQuery.of(context).size.height *
0.58, //<-- set height of the card
child: FirstCardCreation(
//<-- new widget
name: 'Erick Holz',
birthday: '08.12.1998',
),
);
}
}
class FirstCardCreation extends StatelessWidget {
final String name;
final String birthday;
const FirstCardCreation({
Key key,
#required this.name,
#required this.birthday,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
color: Color(0xFFef9a9a),
margin: EdgeInsets.all(8),
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(32)),
child: Column(
children: <Widget>[
SizedBox(height: 8),
Expanded(
child:
FirstCardContent(contentname: name, contentbirthday: birthday),
)
],
),
);
}
}
class FirstCardContent extends StatelessWidget {
String contentname;
String contentbirthday;
FirstCardContent(
{Key key, #required this.contentname, #required this.contentbirthday})
: super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kNameInput,
onChanged: (value1) {
contentname = value1;
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kBirthdayInput,
onChanged: (value2) {
contentbirthday = value2;
},
),
),
],
),
);
}
}
Later on, I want the user to add another input, that's why I created a separate finishedCard. But first of all, I would like to be able to create this finished card without the third input for general functionality. (In the future, my App should work like this: User presses the Button 'new' on the homescreen -> gets directed to the card creation, where he/she gives the name and birhtday as an input -> user taps the next button -> gets directed to the next site where the third and last input gets entered -> user presses finish and the user gets redirected to the homescreen, where the finished Card gets displayed inside a list.)
Heres the Code of the finished Card where I want the information of the variables contentname & contentbirthday from above getting stored inside the variables finalname & finalbirthday:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'real_new_card.dart';
import 'real_new_algorithm_card.dart';
class CardFinish extends StatefulWidget {
#override
_CardFinishState createState() => _CardFinishState();
}
class _CardFinishState extends State<CardFinish> {
#override
Widget build(BuildContext context) {
return SizedBox(
height:
MediaQuery.of(context).size.height * 0.5, //<-- set height of the card
child: FinalCardCreation(),
);
}
}
class FinalCardCreation extends StatelessWidget {
final String finalname;
final String finalbirthday;
const FinalCardCreation({
Key key,
#required this.finalname,
#required this.finalbirthday,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
color: Color(0xFFef9a9a),
margin: EdgeInsets.all(8),
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(32)),
child: Column(
children: <Widget>[
SizedBox(height: 8),
Expanded(
child: FinalCardContent(
name: finalname,
birthday: finalbirthday,
),
)
],
),
);
}
}
class FinalCardContent extends StatelessWidget {
String name;
String birthday;
FinalCardContent({Key key, #required this.name, #required this.birthday})
: super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'$name',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50.0,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'$birthday',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50.0,
color: Colors.black,
),
),
),
],
),
);
}
}
Thank you so much for your help. I hope I formatted everything correctly.
Maybe my general approach is completely false.
If you have a better idea to let the user create a card with this functionality, which than gets displayed on a new card I would be very interested.
I'm sorry but maybe you can show some code that dosen't work. The explanation is in my eyes not quite helpful.
The only thing I noticed is that there are variables missing
child: FinalCardCreation(/*name and birthday here*/);
as you set that these fields are required.

Can't make bottom textfield stick on top of keyboard when it show up in chat app, Flutter

So I m developing a chat app which read and write data from firebase.
I have a streambuilder(that shows the messages)which is above a Container widget(which hold the input text field)
My problem is when I tap the input field and the keyboard pop ups, it cover the message textfield.
I have done many solutions from Stackoverflow and none of them seems to work in my case. The technique i have tried are
-resizeToAvoidBottomInset: true
-Expanded(when I try this the messages no longer show up)
-Flexible
I test the same code in my other project and it works. The text field stick on top of the keyboard. It just doesn't work in a particular project which use Bloc Pattern. There might have been some scaffold error or I don't know. Please help
import 'chat_design.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final _firestore = Firestore.instance;
FirebaseUser loggedInUser;
class ChatScreen extends StatefulWidget {
static const String id = 'chat_screen';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final messageTextController = TextEditingController();
final _auth = FirebaseAuth.instance;
String messageText;
#override
void initState() {
// TODO: implement initState
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
}
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
_auth.signOut();
Navigator.pop(context);
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MessagesStream(),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: messageTextController,
onChanged: (value) {
//Do something with the user input.
messageText = value;
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
messageTextController.clear();
//Implement send functionality.
_firestore.collection('messages').add({
'text': messageText,
'sender': loggedInUser.email,
});
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
class MessagesStream extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').limit(100).snapshots(),
builder: (context, snapshot) {
//wait before data is loaded
if(snapshot.data == null) return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator(strokeWidth: 7,),
),
],
);
final messages = snapshot.data.documents.reversed;
List<MessageBubble> messageBubbles = [];
for (var message in messages) {
final messageText = message.data['text'];
final messageSender = message.data['sender'];
final currentUser = loggedInUser.email;
final messageBubble = MessageBubble(
sender: messageSender,
text: messageText,
isMe :currentUser == messageSender,
);
messageBubbles.add(messageBubble);
}
return Expanded(
child: ListView(
reverse: true,
padding:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
children: messageBubbles,
),
);
},
);
}
}
class MessageBubble extends StatelessWidget {
MessageBubble({this.sender, this.text,this.isMe});
final String sender;
final String text;
final bool isMe;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: <Widget>[
Text(
sender,
style: TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),
Material(
borderRadius: isMe ? BorderRadius.only(topLeft: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(15.0))
:BorderRadius.only(topRight: Radius.circular(30.0),
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(30.0)),
color: isMe ? Colors.lightBlueAccent: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
child: Text(
'$text',
style: TextStyle(
color: isMe ? Colors.white : Colors.black,
fontSize: 15.0,
),
),
),
),
],
),
);
}
}
Take ListView or SingleChildScrollView under Body. And then use bottomNavigationBar in Scaffold.
Scaffold(
body: ListView(
children: [],
),
bottomNavigationBar: Container(
padding: MediaQuery.of(context).viewInsets,
color: Colors.grey[300],
child: Container(
padding: EdgeInsets.symmetric(vertical: 2),
margin: EdgeInsets.symmetric(horizontal: 5),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Type a message',
),
))
),
);
I think what you need is use a SingleChildScrollView, the content will scroll when the keyboard show up, will let you two examples:
// Flutter code sample for
// In this example, the children are spaced out equally, unless there's no more
// room, in which case they stack vertically and scroll.
//
// When using this technique, [Expanded] and [Flexible] are not useful, because
// in both cases the "available space" is infinite (since this is in a viewport).
// The next section describes a technique for providing a maximum height constraint.
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return WidgetsApp(
title: 'Flutter Code Sample',
builder: (BuildContext context, Widget navigator) {
return MyStatelessWidget();
},
color: const Color(0xffffffff),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
MyStatelessWidget({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return Scrollbar(
child: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
// A fixed-height child.
color: const Color(0xff808000), // Yellow
height: 120.0,
),
Container(
// Another fixed-height child.
color: const Color(0xff008000), // Green
height: 120.0,
),
],
),
),
),
);
},
);
}
}
Another example for SingleChildScrollView
// Flutter code sample for
// In this example, the column becomes either as big as viewport, or as big as
// the contents, whichever is biggest.
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return WidgetsApp(
title: 'Flutter Code Sample',
builder: (BuildContext context, Widget navigator) {
return MyStatelessWidget();
},
color: const Color(0xffffffff),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
MyStatelessWidget({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: IntrinsicHeight(
child: Column(
children: <Widget>[
Container(
// A fixed-height child.
color: const Color(0xff808000), // Yellow
height: 120.0,
),
Expanded(
// A flexible child that will grow to fit the viewport but
// still be at least as big as necessary to fit its contents.
child: Container(
color: const Color(0xff800000), // Red
height: 120.0,
),
),
],
),
),
),
);
},
);
}
}
Try this: Go to your AndroidManifest.xml and remove:
android:windowSoftInputMode="adjustResize" under the application-activity tag.
Basically, just change this:
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
to this:
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
>
Worked for one of my apps.
This is the correct way to do this:
Widget _buildContent(BuildContext context) {
return Stack(
children: [
Column(
children: [
Expanded(
child: YOUR_SCROLLING_AREA_HERE,
),
YOUR_PINNED_WIDGET_HERE,
],
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: _buildContent(context),
);
}