I recently started programming in flutter. I want to add second container in my app. When i duplicate the container code in my class, i get an error dead code in this part of the text. Could you please help me with adding the second container?
NewsBoxFavourit(this._num);
#override
State<StatefulWidget> createState() => MyFormState();
}
class MyFormState extends State {
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Expanded(
child: Column(
children: <Widget>[
Text('Выполнено кругов'),
TextFormField(validator: (value){if (value.isEmpty) return 'Введите количество кругов';}),
],
),
);
}
}
class NewsBox extends StatelessWidget {
final String _title;
final String _text;
String _imageurl;
int _num;
NewsBox(this._title, this._text, {String imageurl, int num = 0,}) {
_imageurl = imageurl;
_num = num;
}
#override
Widget build(BuildContext context) {
if (_imageurl != null && _imageurl != '') return new Container(
color: Colors.black12,
height: 100.0,
child: Row(children: [
Image.network(_imageurl, width: 100.0, height: 100.0, fit: BoxFit.cover,),
Expanded(child: Container(padding: EdgeInsets.all(5.0), child: Column(children: [
Text('Дата'),
TextFormField(validator: (value){if (value.isEmpty) return 'Введите количество кругов';}),
Expanded(child: Text(_text, softWrap: true, textAlign: TextAlign.justify,))
]
))
), NewsBoxFavourit(_num,)
])
);
return Container(
color: Colors.black12,
height: 100.0,
child: Row(children: [
Expanded(child: Container(padding: EdgeInsets.all(5.0), child: Column(children: [
Text(_title, style: TextStyle(fontSize: 20.0), overflow: TextOverflow.ellipsis),
Expanded(child: Text(_text, softWrap: true, textAlign: TextAlign.justify,))
]
))
), NewsBoxFavourit(_num,)
])
);
#override
Widget build(BuildContext context) {
if (_imageurl != null && _imageurl != '') return new Container(
color: Colors.black12,
height: 100.0,
child: Row(children: [
Image.network(_imageurl, width: 100.0, height: 100.0, fit: BoxFit.cover,),
Expanded(child: Container(padding: EdgeInsets.all(5.0), child: Column(children: [
Text('Дата'),
TextFormField(validator: (value){if (value.isEmpty) return 'Введите количество кругов';}),
Expanded(child: Text(_text, softWrap: true, textAlign: TextAlign.justify,))
]
))
), NewsBoxFavourit(_num,)
])
);
return Container(color:Colors.black12,
height: 100.0,
child: Row(children: [
Expanded(child: Container(padding: EdgeInsets.all(5.0), child: Column(children: [
Text(_title, style: TextStyle(fontSize: 20.0), overflow: TextOverflow.ellipsis),
Expanded(child: Text(_text, softWrap: true, textAlign: TextAlign.justify,))
]
))
), NewsBoxFavourit(_num,)
])
);
}
}
Please, explain why it does not execute the code? How to make second Conteiner? What i need to do with dead code?
Flutter does not work like what your code is showing. Your NewsBox custom widget can only have 1 build method. If you want 2 containers in a single widget then try using Column, Row, Stack and many other widgets. These can be found under the Multi-child layout widgets in the flutter documentation. I'd assume you'd want the Stack widget though I do not know what design you'd like to achieve.
Related
This is my code, I am passing the "Keyname" to the stateless widget, this widget is wrapped with Flexible widget in a different dart file.
I am getting this error:
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.
Here is the code:
Flexible(
flex: 2,
child: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
KeyBoardButtonFirstRow(
width: deviceWidth / 6,
color: Color(0xfffdc40d),
keyName: '2nF',
),
KeyBoardButtonFirstRow(
width: deviceWidth / 6,
color: Color(0xff52e2fe),
),
KeyBoardButtonFirstRow(
width: deviceWidth / 2,
color: Color(0xffabbfc5),
),
],
),
class KeyBoardButtonFirstRow extends StatelessWidget {
final String keyName;
final double width;
final Color color;
KeyBoardButtonFirstRow({this.keyName, this.width, this.color});
#override
Widget build(BuildContext context) {
return Container(
height: 30.0,
width: width,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(10.0),
boxShadow: [BoxShadow(
color: Colors.white.withOpacity(0.5),
blurRadius: 2.0,
)],
),
child: Text(keyName),
);
}
}
These are the changes you you need to make to your code,
class Test0 extends StatefulWidget {
#override
_Test0State createState() => _Test0State();
}
class _Test0State extends State<Test0> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Flexible(
flex: 2,
child: Container(
height: MediaQuery.of(context).size.width,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
KeyBoardButtonFirstRow(
width: MediaQuery.of(context).size.width / 6,
color: Color(0xfffdc40d),
keyName: '2nF',
),
],
)
])
))
],
),
);
}
}
class KeyBoardButtonFirstRow extends StatelessWidget {
final String keyName;
final double width;
final Color color;
KeyBoardButtonFirstRow({this.keyName, this.width, this.color});
#override
Widget build(BuildContext context) {
return Container(
height: 30.0,
width: width,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.white.withOpacity(0.5),
blurRadius: 2.0,
)
],
),
child: Text(keyName),
);
}
}
Here I have Scaffold, in your case, it could be any constrained widget.
I have several modalBottomSheet in my app to show, most of them have simple widget tree except only one that has 10 DropDownBottom widgets in it
Each one of them load about 200 items, each item is a widget consist of two main widgets a text and an image
when I Press
onPressed: () {
showModalBottomSheet(context: context, builder: picksWidget, isScrollControlled: true);
}
It take about 3 seconds to open load the modalBottomSheet and it just appear into the emulator without the sliding up animation, other modalBottomSheets in the app load perfectly fine, here is an example of the code I use.
import 'package:flutter/material.dart';
import 'package:myapp/data/picked.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:myapp/data/picks.dart';
import 'package:myapp/data/Icons.dart';
Widget buildPickerBottomSheet(BuildContext context) {
return Wrap(children: <Widget>[
PickerList(),
]);
}
class PickerList extends StatelessWidget {
const PickerList({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
padding: EdgeInsets.all(20),
child: Row(
children: <Widget>[
AutoSizeText(
'Pick ',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
textAlign: TextAlign.right,
maxLines: 1,
),
],
),
),
SizedBox(
height: 5,
),
PickerRow(
typeOne: 'vr',
typeTwo: 'er',
type: 'r',
),
PickerRow(
typeOne: 'vq',
typeTwo: 'eq',
type: 'q',
),
PickerRow(
typeOne: 'vw',
typeTwo: 'ew',
type: 'w',
),
PickerRow(
typeOne: 'vz',
typeTwo: 'ez',
type: 'z',
),
PickerRow(
typeOne: 'vy',
typeTwo: 'ey',
type: 'y',
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
child: Text('Add'),
onPressed: () async {
print('added');
},
),
RaisedButton(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
)
],
),
SizedBox(
height: 50,
)
],
);
}
}
class PickerRow extends StatelessWidget {
final String typeOne;
final String typeTwo;
final String type;
PickerRow({#required this.typeOne, #required this.typeTwo, #required this.type});
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
DropDownMenu(
pickType: typeOne,
),
Container(
width: 2,
height: 30,
color: Colors.blue,
),
Container(
height: 30,
width: 30,
child: Image(
image: AssetImage(AppIcons.types[type]),
),
),
Container(
width: 2,
height: 30,
color: Colors.red,
),
DropDownMenu(
pickType: typeTwo,
),
],
),
);
}
}
class DropDownMenu extends StatefulWidget {
//which position will this pick for
final String pickType;
DropDownMenu({#required this.pickType});
#override
_DropDownMenuState createState() => _DropDownMenuState();
}
class _DropDownMenuState extends State<DropDownMenu> {
//get a list of the picks to display in the drop down
static List<DropdownMenuItem> getDropDownItems() {
List<DropdownMenuItem<String>> dropDownItems = [];
for (int i = 0; i < Picks.picksNames.length; i++) {
String pick = Picks.picksNames[i];
var newItem = DropdownMenuItem(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
CircleAvatar(
backgroundImage: AssetImage(AppIcons.picks[pick]),
radius: 15,
),
SizedBox(
width: 4,
),
AutoSizeText(
pick,
maxLines: 1,
),
],
),
value: pick,
);
dropDownItems.add(newItem);
}
return dropDownItems;
}
var items = getDropDownItems();
#override
Widget build(BuildContext context) {
String chosenItem = Picked.selection[widget.pickType];
return DropdownButton<String>(
value: chosenItem,
items: items,
onChanged: (value) {
setState(() {
chosenItem = value;
});
Picked.selection[widget.pickType] = value;
},
);
}
}
I am new to development in general so I appreciate if there is any resources on how to measure and improve performance on flutter apps.
Thanks.
It seems like your bottomModalSheet is too heavy. It loads only after the children have completed building.
Resize the images that you use inside the bottomModalSheet.
Usually the debug app is very slow compared to the release app.
Generate the apk of the app: flutter build apk --split-per-abi.
Install the generated apk build/app/outputs/apk/release/app-armeabi-v7a-release.apk and see if the problem still persists.
You should avoid rendering 2000 widgets at once.
First of all look at ListView widget and it's builder(). Try to refactor your code and put all your items inside this ListView. It will increase your performance a lot due to the reason that ListView.builder() allows you not to store all your widgets in memory all the time.
https://api.flutter.dev/flutter/widgets/ListView/ListView.builder.html
I made a Login screen,
want to Launch camera(font) on click of Activate Button , then how to show the capture image in next page?
I am done with the camera open part , onPressed of Activate Button and also done routing to the next page
----> that's mean in my case Activate button , doing 2 things--> (1) its captured image and (2) going to the next page
Now how can I Show the Capture image in next page which I routing with loginPage Activate button
class LoginFormState extends State<LoginForm> {
File imagefile;
_openCamera(BuildContext context)async{
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
imagefile = picture;
});
}
showImage(){
if(imagefile == null){
return Text("No Image selected here");
}else {
Image.file(imagefile,width:400,height:400);
}
}
var textLength = 6;
var mobileLength = 10;
#override
Widget build(context) {
return Container(
margin: EdgeInsets.only(
top: 0.0,
right: 43.0,
left: 43),
child: Column(
children: [
userField(),
Container(margin: EdgeInsets.only(top: 40.0)),
numberField(),
Container(margin: EdgeInsets.only(top: 60.0, )),
activateButton(),
Container(margin: EdgeInsets.only(top: 60.0, )),
showImage(),
],
),
);
}
Widget activateButton() {
return RaisedButton(
color: Color(0xFFF4D3AE),
child: Text('Activate',
style: TextStyle(
fontFamily: 'Californian FB',
color: Colors.black, //Color(0xFF425c5a),
fontWeight: FontWeight.normal, //bold
letterSpacing: 2.0,
fontSize: 17.0,
)),
padding: EdgeInsets.symmetric(
horizontal: 75.0,
vertical:
15.0), //Activate button box will take more space horizontally & vertically.
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20),
topRight: Radius.circular(20),
topLeft: Radius.circular(20),
),
),
onPressed: () {
_openCamera(context);
Navigator.of(context).pushNamed("/CameraAccess");
},
);
}
}
----------------------- This is my second page code:-----------------------------------
import 'package:flutter/material.dart';
class CameraAccess extends StatefulWidget{
#override
createState() {
return CameraAccessState();
}
}
class CameraAccessState extends State<CameraAccess>{
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF425c5a),
body: ListView(
children: <Widget>[
Center(
child: Container(child:
Text('Your Image here',
style: TextStyle(
fontFamily: 'Californian FB',
color: Colors.black, //Color(0xFF425c5a),
fontWeight: FontWeight.normal, //bold
letterSpacing: 2.0,
fontSize: 27.0,
)
),
),
),
]
)
);
}
}
I have been experimenting with Flutter trying to recreate an app that I wrote for Android 5 years ago. But I can't seem to get the layout to work very well.
I have tried a number of different widgets, but each time I try something, it seems like I am taking 2 steps forward and 3 steps back.
The app is going to be vertical position only.
Simple banner image at the top.
A trivia question.
Radio button group with 4 answers.
Then 2 buttons - 'Check Answer' and 'Skip Question'
Bottom bar
I am trying to make sure that the radio buttons and the buttons don't bounce around when the question changes.
This is what I have
This is what I would like
And this is the code that I have been fighting with.
Any help or tips would be greatly appreciated.
class _MyHomePageState extends State<MyHomePage> {
final TriviaBloc _triviaBloc = TriviaBloc();
TriviaQuestion _initTriviaQuestion = new TriviaQuestion('', '', '', '', '', 1, 1);
String _selectedAnswer = "";
TextStyle _answerStyle = new TextStyle(textBaseline: TextBaseline.alphabetic, fontStyle: FontStyle.normal, fontFamily: 'QarmicsansAbridged', fontSize: 16);
#override
void dispose() {
_triviaBloc.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.orangeAccent,
body: SafeArea(
minimum: const EdgeInsets.all(16.0),
child:
Column(children: [
ImageBanner("assets/header_2.jpg"),
Expanded(
child:
StreamBuilder<TriviaQuestion>(
initialData: _triviaBloc.getInitialTriviaQuestion(),
//_initTriviaQuestion,
stream: _triviaBloc.triviaQuestionStream,
//initialData: _triviaBloc.getInitialTriviaQuestion(),
//builder: (BuildContext context, AsyncSnapshot<TriviaQuestion> snapshot)
builder: (BuildContext context, snapshot) {
//_triviaBloc.getTriviaQuestion(snapshot, context);
if (snapshot.data != null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(height: 15),
Padding(
padding: EdgeInsets.all(2.0),
child: TriviaAutoSizeText(context, snapshot.data.Question),
),
RadioButtonGroup(
labels: <String>[
snapshot.data.IncorrectAnswer1,
snapshot.data.IncorrectAnswer2,
snapshot.data.CorrectAnswer,
snapshot.data.IncorrectAnswer3
],
labelStyle: _answerStyle,
onSelected: (String selected) => _selectedAnswer = selected),
//),
SizedBox(height: 10),
new InkWell(
onTap: () => {_triviaBloc.checkAnswer(QuestionAnswered(_selectedAnswer))},
child: new Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 50.0,
decoration: new BoxDecoration(
color: _butttonInteriorColour,
//Colors.blueAccent,
border:
new Border.all(color: Colors.white, width: 1.0),
borderRadius: new BorderRadius.circular(20.0),
),
child: new Center(
child: new Text(
'Check Answer',
style: new TextStyle(
fontSize: 18.0, color: Colors.white),
),
),
),
),
SizedBox(height: 10),
new InkWell(
onTap: () =>
{_triviaBloc.getTriviaQuestion(snapshot, context)},
child: new Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 50.0,
decoration: new BoxDecoration(
color: _butttonInteriorColour,
//Colors.blueAccent,
border:
new Border.all(color: Colors.white, width: 1.0),
borderRadius: new BorderRadius.circular(20.0),
),
child: new Center(
child: new Text(
'Next Question',
style: new TextStyle(
fontSize: 18.0, color: Colors.white),
),
),
),
),
],
);
} else {
return Center(child: CircularProgressIndicator());
}
;
}),
)]),
),
bottomNavigationBar: buildBottomNav(context),
);
}
}
So you want the 4 button group and the 2 buttons at the bottom without changing position ?
Maybe a Spacer will help with that
if (snapshot.data != null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max, //replace this to fill everything
children: <Widget>[
SizedBox(height: 15),
Padding(
padding: EdgeInsets.all(2.0),
child: TriviaAutoSizeText(context, snapshot.data.Question),
),
Spacer(), //add the spacer here
RadioButtonGroup(
labels: <String>[
My problem is that : The listview does not appear at the first launch of app but after a hot reload it appears.
It's the first time I meet this bug.
That's my code :
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.black,
body: new ListView.builder(
itemCount: toutesLesCartes.length,
itemBuilder: (context, count) {
Carte carte = toutesLesCartes[count];
String nom = carte.nomCarte;
String image = carte.imageCarte;
return new Dismissible(
key: new Key(nom),
direction: DismissDirection.endToStart,
child: new Container(
margin: EdgeInsets.all(5.0),
child: new Card(
color: Colors.transparent,
elevation: 10.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Image.network(image, width: 150.0, height: 150.0,),
new CustomText(nom, factor: 2.0,),
],
),
),
),
background: new Container(
padding: EdgeInsets.only(right: 20.0),
color: Colors.red,
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new CustomText("Supprimer"),
new Icon(Icons.delete, color: Colors.white,)
],
),
),
onDismissed: (direction) {
setState(() {
toutesLesCartes.removeAt(count);
nombreCarteChoisiValeur--;
});
},
);
}
),
);
}
I have an idea but it's strange : before, I using the Visibility widget so it is possible that it comes from a possible "cache" of the application?
All that will look at this post and help me, thank you very much!
Have a nice day !
Likely because toutesLesCartes.length is 0.
you can check this using the debugger or display something when the length is 0 eg
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.black,
body: new ListView.builder(
itemCount: toutesLesCartes.length, //* place breakpoint here
itemBuilder: (context, count) {
Carte carte = toutesLesCartes[count];
String nom = carte.nomCarte;
String image = carte.imageCarte;
if(toutesLesCartes == null || toutesLesCartes.length == 0){
return CircularProgressIndicator(); //you should see loading animation if list is empty
}
return new Dismissible(
key: new Key(nom),
direction: DismissDirection.endToStart,
child: new Container(
margin: EdgeInsets.all(5.0),
child: new Card(
color: Colors.transparent,
elevation: 10.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Image.network(image, width: 150.0, height: 150.0,),
new CustomText(nom, factor: 2.0,),
],
),
),
),
background: new Container(
padding: EdgeInsets.only(right: 20.0),
color: Colors.red,
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new CustomText("Supprimer"),
new Icon(Icons.delete, color: Colors.white,)
],
),
),
onDismissed: (direction) {
setState(() {
toutesLesCartes.removeAt(count);
nombreCarteChoisiValeur--;
});
},
);
}
),
);
}
The solution would be to use a FutureBuilder
Word of warning: The application will run the build method multiple times, it's good practice to place anything you don't want to be repeatedly called (like database calls) outside of the method.