How to create a TextField on a Card - flutter

How can i create a TextField on a Card.
In a Function i return a Card. Here i needed to implement a TextField.
This is my Code:
return new Card(
color: Colors.white70,
child: new Container(
padding: EdgeInsets.all(10.0),
child: new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(child: new Text("Bemerkung", style: style,)),
new TextField(
),
],
),
],
),
),
);
everytime i wanted to debug, this Exception was thrown:
I/flutter (17588): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (17588): The following assertion was thrown during performLayout():
I/flutter (17588): BoxConstraints forces an infinite width.
I/flutter (17588): These invalid constraints were provided to RenderRepaintBoundary's layout() function by the
I/flutter (17588): following function, which probably computed the invalid constraints in question:
I/flutter (17588): _RenderDecoration._layout.layoutLineBox (package:flutter/src/material/input_decorator.dart:747:11)
I/flutter (17588): The offending constraints were:
I/flutter (17588): BoxConstraints(w=Infinity, 0.0<=h<=Infinity)
i dont know why it didn't work.

Just wrap TextField with Expanded widget,
new Card(
color: Colors.white70,
child: new Container(
padding: EdgeInsets.all(10.0),
child: new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(child: new Text("Bemerkung",)),
new Expanded(
child: new TextField(
),
),
],
),
],
),
),
);

Related

Expanded and FittedBox in Row and Column

Expanded and FittedBox in Row and Column.
══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
The following assertion was thrown during a scheduler callback:
'package:flutter/src/widgets/binding.dart': Failed assertion: line 849 pos 12:
'!debugBuildingDirtyElements': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially
more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
When the exception was thrown, this was the stack:
#2 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:849:12)
#3 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:378:5)
#4 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1175:15)
#5 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1104:9)
#6 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:881:7)
(elided 6 frames from class _AssertionError, class _RawReceivePortImpl, class _Timer, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
Performing hot reload...
Reloaded 0 libraries in 31ms (compile: 7 ms, reload: 0 ms, reassemble: 13 ms).
Another exception was thrown: 'package:flutter/src/widgets/binding.dart': Failed assertion: line 849 pos 12: '!debugBuildingDirtyElements': is not true.
Another exception was thrown: 'package:flutter/src/widgets/binding.dart': Failed assertion: line 849 pos 12: '!debugBuildingDirtyElements': is not true.
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
color: Color.fromRGBO(0, 0, 0, 1),
child: SafeArea(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: IntrinsicWidth(
child: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FittedBox(
fit: BoxFit.fitWidth,
child: Text(
_localeDate,
style: TextStyle(
color: Colors.white,
),
),
),
SizedBox(
height: 20,
),
FittedBox(
fit: BoxFit.fitWidth,
child: Text(
_time,
style: TextStyle(
color: Colors.white,
),
),
),
],
),
],
),
),
),
),
Expanded(
flex: 2,
child: Image(fit: BoxFit.cover, image: NetworkImage(img)))
],
),
),
),
);
}
When hot start is pressed, a screen appears and the following error is output.
The following RenderObject was being processed when the exception was fired: RenderFittedBox#e50d7 relayoutBoundary=up15 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE:
creator: FittedBox ← Column ← Stack ← IntrinsicWidth ← Padding ← SizedBox ← Row ← MediaQuery ←
Padding ← SafeArea ← Align ← ColoredBox ← ⋯
parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
constraints: BoxConstraints(w=237.2, 0.0<=h<=Infinity)
size: MISSING
fit: fitWidth
alignment: Alignment.center
textDirection: ltr
This RenderObject had the following descendants (showing up to depth 5):
child: RenderParagraph#39ce4 relayoutBoundary=up16 NEEDS-PAINT
text: TextSpan
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: RenderBox was not laid out: RenderFittedBox#e50d7 relayoutBoundary=up15 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
Another exception was thrown: RenderBox was not laid out: RenderFlex#e77d9 relayoutBoundary=up14 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I would like to do this.
I use FitBox because I need to change the font size for each device.
Characters must be in a single column.
I want to display the maximum number of images.
This is because they are easy to see.
It doesn't make sense for a Row() to contain two Expanded(), since you also have no control over their widths.
It is recommended to fix the width of the text on the left
this is example
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:koreajob/view/common/funciton_of_print.dart';
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
#override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
Widget _buildLandScreenView(BuildContext context, Orientation orientation) {
return Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
color: Color.fromRGBO(0, 0, 0, 1),
child: SafeArea(
child: Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width * .5,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: IntrinsicWidth(
child: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FittedBox(
fit: BoxFit.fitWidth,
child: Text(
"""Easy to use, """,
style: TextStyle(
color: Colors.white,
),
),
),
SizedBox(
height: 20,
),
FittedBox(
fit: BoxFit.fitWidth,
child: Text(
"""Just add Just add Just add Just add Just add Just add """,
style: TextStyle(
color: Colors.white,
),
),
),
],
),
],
),
),
),
),
Expanded(
child: Image(
fit: BoxFit.cover,
image: NetworkImage('https://picsum.photos/200')))
],
),
),
);
}
Widget _buildPortaraitScreenView(
BuildContext context, Orientation orientation) {
return _buildLandScreenView(context, orientation);
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
body: OrientationBuilder(builder: (context, orientation) {
if (orientation == Orientation.portrait) {
return _buildPortaraitScreenView(context, orientation);
} else if (orientation == Orientation.landscape) {
return _buildLandScreenView(context, orientation);
}
return Container();
}));
}
}

How to use Image inside Stack widget in Flutter?

I got an error when using Image inside Stack widget :
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
...
this is my code :
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Flexible(
child: Image.asset(itemData["image"])
),
),
const Positioned(
...
),
],
),
],
),
);
}
of course, I defined my image assets in pubspec.yaml and I try to remove flexible widget also add Row layer above it, but it's still not working either...
this is my error when I remove flexible widget :
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/images/image2.jpg
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:675:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "assets/images/image2.jpg")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#898db(), name:
"assets/images/image2.jpg", scale: 1.0)
So, How I can use (multiple) Images inside Stack Widget, and what's wrong with my code?
thank you for coming and I hope you have the solution. cheers
You have done everything perfect. but the one mistake was you wraped Image Widget by flexible. thats why flutter throws error. below code will work fine.
just remove flexible widget.
Container(
margin: const EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Image.network(
"https://www.writerswrite.co.za/wp-content/uploads/2017/04/how-long-to-read.png",
),
),
Positioned(
child: Container(
height: 20,
color: Colors.red,
width: 20,
),
),
],
),
],
),
);
Flexible Widget used to adjust the available space near the widgets...
so renderobject not able to paint what you construct in UI because of you wraped flexible over Image
to learn more about flexible refer : https://api.flutter.dev/flutter/widgets/Flexible-class.html
above code will working fine...
for image rendering issue : refer https://docs.flutter.dev/development/platform-integration/web-images
Wrap the Stack with expanded widget. I tried with the example below and it worked for me
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Flexible(
child: Image.network(
"https://www.writerswrite.co.za/wp-content/uploads/2017/04/how-long-to-read.png",
),
),
),
Positioned(
child: Container(
height: 20,
color: Colors.red,
width: 20,
),
),
],
),
),
],
),
);
}

I can not create a SingleChildScrollView screen on Flutter

I was trying to create a scrollable screen, not the widgets inside but the whole screen on Flutter but I get some errors like below:
======== Exception caught by rendering library ===================================================== RenderBox was not laid out: RenderFlex#f643b relayoutBoundary=up13 NEEDS-PAINT
NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart': Failed assertion: line 1920
pos 12: 'hasSize' The relevant error-causing widget was:
SingleChildScrollView
Here is the code of one of the shown widgets:
var _settingsPage = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Row(
children: [
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
children: [
FloatingActionButton(
child: Icon(Icons.casino),
onPressed: changeHome,
),
],
),
Flexible(
fit: FlexFit.loose,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Text(
_helpString,
textAlign: TextAlign.center,
),
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Is your character epic?'),
Checkbox(
value: _epic,
onChanged: (bool epic) {
setState(
() {
_epic = epic;
},
);
},
),
],
),
),
],
),
),
],
),
),
],
),
);
},
);
Try wrapping your SingleChildScrollView in a SizedBox with a defined height and width.
This will make sure your view is constructed to a defined space
To set SizedBox height to screen height you can use media query like
MediaQuery.of(context).size.height and you can replace height with width to set the widget size to your screen width
If issue still persists feel free to comment
Regards,
Rachan

My drawer is throwing " Incorrect use of ParentDataWidget." using a list

I'm trying to implement a ListView inside my drawer so when the screen orientation change i don't get an overflow error.
But as soon i add my ListView to the drawer it do not render anymore and i'm getting the errors :
I/flutter (13071): Another exception was thrown: Incorrect use of ParentDataWidget.
I/flutter (13071): Another exception was thrown: RenderBox was not laid out: RenderShrinkWrappingViewport#91f4f relayoutBoundary=up11 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
And i couldn't figure out hwy my code do not work. Doew someone has an idea why ?
Thank you !
This is my code :
Widget build(BuildContext context) {
return Drawer(
child: Container(
child: Flex(
direction: Axis.vertical,
children: <Widget>[
Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: const EdgeInsets.only(left: 40, bottom: 20),
child: Text(
"test",
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(
color: Colors.white,
fontSize: 25,
),
),
),
),
Expanded(
child: ListView(
shrinkWrap: true,
children: <Widget>[],
),
)
],
),
),
);
}

Flutter RenderFlex overflowed by 15 pixels on the right inside Column Widget

I created a custom ListTile which should have two score centered in the middle and information on the left and right of this (screenshot).
The information on the left can have arbitrary length and should use TextOverflow.ellipsis when it's too long.
I cannot get this to work since the Text does not seem to know the width it is supposed to have and overflows.
I have tried wrapping the Text widgets into SizedBox, Expanded, etc. This has not worked.
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following message was thrown during layout:
flutter: A RenderFlex overflowed by 15 pixels on the right.
flutter:
flutter: The overflowing RenderFlex has an orientation of Axis.horizontal.
flutter: The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
flutter: black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
flutter: Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
flutter: RenderFlex to fit within the available space instead of being sized to their natural size.
flutter: This is considered an error condition because it indicates that there is content that cannot be
flutter: seen. If the content is legitimately bigger than the available space, consider clipping it with a
flutter: ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
flutter: like a ListView.
flutter: The specific RenderFlex in question is:
flutter: RenderFlex#c64e4 relayoutBoundary=up11 OVERFLOWING
flutter: creator: Row ← Expanded ← Row ← Column ← ConstrainedBox ← Container ← Listener ← _GestureSemantics
flutter: ← RawGestureDetector ← GestureDetector ← InkWell ← ScopedModelDescendant<BaseballModel> ← ⋯
flutter: parentData: offset=Offset(0.0, 0.0); flex=1; fit=FlexFit.tight (can use size)
flutter: constraints: BoxConstraints(w=143.0, 0.0<=h<=Infinity)
flutter: size: Size(143.0, 70.0)
flutter: direction: horizontal
flutter: mainAxisAlignment: start
flutter: mainAxisSize: max
flutter: crossAxisAlignment: center
flutter: textDirection: ltr
flutter: verticalDirection: down
flutter: ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
My Code is the following:
#immutable
class GameTile extends StatelessWidget {
final Game game;
Color highligtColor = Colors.red;
GameTile({this.game});
#override
Widget build(BuildContext context) {
return InkWell(
child: Container(
height: 70.0,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Container(
width: 8.0,
height: 70.0,
color: highligtColor,
),
Padding(
padding: EdgeInsets.only(left: 15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
game.awayTeam.name,
overflow: TextOverflow.ellipsis,
),
Text(
game.homeTeam.name,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Column(
children: [
Text(
game.awayRuns,
style: TextStyle(fontWeight: FontWeight.w900),
),
Text(
game.homeRuns,
style: TextStyle(fontWeight: FontWeight.w900),
),
],
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(game.getFormattedDate()),
Text(game.getFormattedTime()),
]),
Padding(
padding: EdgeInsets.only(left: 8.0, right: 10.0),
child: Container(),
)
],
),
)
],
)
],
),
),
);
}
}
Just wrap the overflowed widget with Flexible
new Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Checkbox(
onChanged: (bool){},
),
Flexible(
child: new Text(
"This text can be so loooooooooooooong",
),
),
],
),
Explanation of Flexible or Expanded Solution
Inside a Row, a Text widget will never line-wrap nor show ellipses when not inside an Expanded or Flexible widget (or another widget which constrains width).
When Flutter performs layout for Row or Column, any non-flex factor widgets get laid out in unbounded space. i.e. without any constraints. (Flexible, Expanded and Spacer are the only flex-factor widgets.)
So when Text is being laid out inside the Row, it will never be so wide as to hit a width constraint and get wrapped because...
... there are no constraints during Row layout for non-flex factor widgets.
Placing the Text widget inside a Flexible or Expanded will cause Flutter to calculate remaining space during Row layout and impose that constraint. This will cause wrapping if needed & ellipses if specified: Text("blahblah", overflow: TextOverflow.ellipsis).
More details in a related RenderFlex overflowed question.
Example Code
import 'package:flutter/material.dart';
class FlexTextWrapPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flex Text Wrap'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
width: 400,
child: Row(
children: [
MySpacer(width: 100),
Text("This should easily wrap, but doesn't because I'm in INFINITE SPACE"),
MySpacer(width: 100),
],
),
),
SizedBox(
width: 400,
child: Row(
children: [
MySpacer(width: 100),
Expanded(child: Text("This should easily wrap, and DOES because I'm in BOUNDED SPACE")),
MySpacer(width: 100),
],
),
),
SizedBox(
width: 400,
child: Row(
children: [
MySpacer(width: 100),
Expanded(
child: Text("This should easily wrap, and DOES because I'm in BOUNDED SPACE",
overflow: TextOverflow.ellipsis, // default is .clip
maxLines: 2,),// default is 1
),
MySpacer(width: 100),
],
),
),
],
),
);
}
}
class MySpacer extends StatelessWidget {
final double width;
MySpacer({this.width});
#override
Widget build(BuildContext context) {
return Container(child: SizedBox(width: width, height: 16,), color: Colors.lightBlueAccent,);
}
}
Result
If you want the child content to just fit the content without being expanded. You must use Flexible in combination with MainAxisSize.min inside Row:
Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Flexible(
child: Padding(
padding: const EdgeInsets.only(right: 2),
child: Text("abc",
style: TextStyle(
color: Colors.white,
fontSize: 13),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
Icon(Icons.arrow_drop_down, size: 10, color: Colors.white,)
],
)
About the exception
I ran your code on my phone and an exception occurred only after meddling with the teams names and the width of the widget.
I think this problem arises because your code doesn't adapt to different display sizes well enough, especially if the team names have a different length:
Concrete solution for a more flexible and dynamic widget
I created a modified widget that adapts well to constraint changes and uses the available space in a more clever way. I did this by flattening your nested Rows and Columns as far as possible, resulting in a more shallow, more flexible widget tree:
return InkWell(
child: Container(
height: 70.0,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(width: 8.0, height: 70.0, color: highlightColor),
SizedBox(width: 15.0),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(game.awayTeam.name, overflow: TextOverflow.ellipsis),
Text(game.homeTeam.name, overflow: TextOverflow.ellipsis),
],
),
Spacer(),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(game.awayRuns, style: TextStyle(fontWeight: FontWeight.w900)),
Text(game.homeRuns, style: TextStyle(fontWeight: FontWeight.w900)),
],
),
Spacer(),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(game.getFormattedDate()),
Text(game.getFormattedTime()),
]
),
SizedBox(width: 18.0),
],
),
),
);
General tip when dealing with difficult constraints
Most of the time, it's better to use just a few widgets in a shallow tree. Nesting all kinds of "organizational" widgets, especially Columns, Rows and Expandeds often creates situations where an Expanded always requests the same size (or ratio of the parent size) without even considering the dimensions of its content.
That can lead to content overflowing, while there is unused negative space at other parts of the widget.
use Expanded or Flexible in your parent widget,