Flutter: Using Expanded - flutter

I have a function that returns a list of Widget like this:
buildCaption() {
List<String> splittedCaption = caption.split(' ');
List<Widget> mergedCaption = new List<Widget>();
for (String captionSplit in splittedCaption) {
print(captionSplit);
if (captionSplit.contains('#')) {
mergedCaption.add(Text(
'$captionSplit ',
style: TextStyle(color: Colors.blue)
));
} else {
mergedCaption.add(Text('$captionSplit '));
}
}
return mergedCaption;
}
Then, I have a Row Widget that looks like this:
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(child: Row(children: buildCaption())
]
)
However, the Expanded doesn't prevent the row from overflowing the screen size. Please how do I display the List of Widgets returned from the buildCaption method while still preventing it from overflowing the screen size?
Whole code:
buildPostFooter() {
return Column(
children: <Widget>[
mediaUrl.length > 1 ? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: map<Widget>(
mediaUrl,
(index, media) {
return Container(
width: 8.0,
height: 8.0,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: currentMedia == index
? Theme.of(context).primaryColor
: Color.fromRGBO(0, 0, 0, 0.4)
)
);
}
)
) : Text(''),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 40.0, left: 15.0)),
GestureDetector(
onTap: handleLikePost,
child: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
size: 28.0,
color: Colors.pink
)
),
Padding(padding: EdgeInsets.only(right: 5.0)),
Text(
'$likeCount likes',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold
)
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => showComments(
context,
postId: postId,
ownerId: ownerId,
mediaUrl: mediaUrl
),
child: Icon(
Icons.chat,
size: 28.0,
color: Colors.blue[900]
)
),
Padding(padding: EdgeInsets.only(right: 5.0)),
Text(
'$commentCount comments',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold
)
)
],
),
Padding(
padding: EdgeInsets.only(
top: mediaUrl.length > 0 && caption.isNotEmpty ? 10.0 : 0.0
)
),
mediaUrl.length > 0 && caption.isNotEmpty ? Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
'$username ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold
)
)
),
Expanded(child: Row(children: buildCaption()))
],
) : timeWidget(),
mediaUrl.length > 0 && caption.isNotEmpty ? timeWidget() : Text('')
],
);
}

Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: RichText(
text: TextSpan(
children: caption.split(' ').map(
(item) {
if (item.contains('#')) {
return TextSpan(
text: '$item ',
recognizer: new TapGestureRecognizer()
..onTap = () => print('hashtag$item'),
style: TextStyle(color: Colors.blue),
);
} else if (item.contains('.')) {
return TextSpan(
text: '$item ',
recognizer: new TapGestureRecognizer()
..onTap = () => print('https://www.$item'),
style: TextStyle(color: Colors.blue),
);
} else {
return TextSpan(
text: '$item ',
);
}
},
).toList(),
),
),
)
]
)

you can`t use row for multiple text widget and expect line breaks
you should use Rich Text for multiple style in one text
try below code:
buildCaption() {
List<String> splittedCaption = caption.split(' ');
List<TextSpan> mergedCaption = List<TextSpan>();
for (String captionSplit in splittedCaption) {
print(captionSplit);
if (captionSplit.contains('#')) {
mergedCaption.add(TextSpan(
text: '$captionSplit ',
style: TextStyle(color: Colors.blue)
));
} else {
mergedCaption.add(TextSpan(text: '$captionSplit '));
}
}
return mergedCaption;
}
 
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: buildCaption(),
),
))
]
)

Try using SingleChildScrollView instead of Expanded

I dont know what you are trying to do, but here you have a horizontal scrollable list. If you want to use row I will suggest using the Wrap. widget.
final List<Widget> widgetList = buildCaption();
#override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(8),
itemCount: widgetList.length,
itemBuilder: (BuildContext context, int index) {
return index;
}
);
}
suggestion: Regarding the overflow you can use a Container instead of Expanded, and set width: MediaQuery.of(context).size.width*0.5 on the Container, this is eqvivalent to 50% of screen width.
suggestion: You can use Grid-list and set crossAxisCount: widgetList().length if you want everything to be in one line, se example here:
https://flutter.dev/docs/cookbook/lists/grid-lists

Related

after setstate ui is not changing in flutter

I am making a simple app and I want to show and hide reply of particular comment on button pressed of respective comment.
But the UI is not changing after the state is changing.
How to solve this issue ,suggest me an idea and thanks in advance.
The snapchatReply list have commentId and isShown field,I want to toggle based on isShown value.
toggleReply(String commentId){
for(int a=0;a<snapchatReply.length;a++){
print(snapchatReply.length);
if(commentId==snapchatReply[a]['commentId']){
if(snapchatReply[a]['isShown']==false){
setState(() {
snapchatReply[a]['isShown']=true;
});
}
else{
print("else");
setState(() {
snapchatReply[a]['isShown']=false;
});
}
}
}
print(snapchatReply);
}
It give following outpit:
2
I/flutter ( 8112): 2
I/flutter ( 8112): [{commentId: 6312c32e842444a707b6903f, isShown: true}, {commentId: 6318257479bcbf779df08816, isShown: false}]
I/flutter ( 8112): 4
I/flutter ( 8112): else
I/flutter ( 8112): 4
I/chatty ( 8112): uid=10154(com.example.fbclone) 1.ui identical 1 line
I/flutter ( 8112): 4
I/flutter ( 8112): [{commentId: 6312c32e842444a707b6903f, isShown: false}, {commentId: 6318257479bcbf779df08816, isShown: false}, {commentId: 6312c32e842444a707b6903f, isShown: true}, {commentId: 6318257479bcbf779df08816, isShown: false}]
Full code:
ListView.builder(
itemCount: widget.snapshot.comments.length,
padding: EdgeInsets.only(bottom: 20),
scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, j) {
commentLike.add({"index":j,
"like":widget.snapshot.comments[j].commentlikes.length,
"commentId":widget.snapshot.comments[j].id});
snapchatReply.add({
"commentId":widget.snapshot.comments[j].id,
"isShown":false
});
return SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width-150,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
iconSize: 50,
onPressed: () {},
icon: CircleAvatar(
radius: 80,
backgroundImage: NetworkImage(
widget.snapshot.comments![j].user.profile),
)),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: MediaQuery.of(context).size.width - 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey[300]),
padding: EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.snapshot.comments![j].user.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.bold),
),
Text(widget.snapshot.comments![j].commentText),
// Text(widget.snapshot.comments![j].commentText,
// style: TextStyle(
// fontSize: 16,
// color: Colors.grey[700])),
])),
Row(
children: [
Text(convertToAgo(
widget.snapshot.comments![j].commentAt)),
TextButton(
onPressed: () {
likeComment(
widget.snapshot.comments![j].id,
widget.postId,
);
},
child: Text("Like", style: myStyle)),
TextButton(
onPressed: () {
print("isReply");
setState(() {
isReply=true;
commentId=widget.snapshot.comments![j].id;
userName=widget.snapshot.comments![j].user.name;
});
},
child: Text("Reply", style: myStyle),
),
TextButton(onPressed: (){
toggleReply(widget.snapshot.comments![j].id);
},
child: Text("view reply"),
),
if(widget.snapshot.comments![j].commentlikes!.length!=0)...[
if(commentLike[j]['like']!=0)...[
Text(totalLikes(commentLike[j]['like']))
]
],
// Text(totalLikes(widget.snapshot.comments![j].commentlikes!.length),
// style: myStyle),
],
),
reply(snapchatReply: snapchatReply, snapshot: widget.snapshot.comments[j])
],
),
]),
),
),
);
}),
reply.dart
import 'package:flutter/material.dart';
class reply extends StatefulWidget {
const reply({Key? key,required this.snapchatReply,required this.snapshot}) : super(key: key);
final snapshot;
final snapchatReply;
#override
State<reply> createState() => _replyState();
}
class _replyState extends State<reply> {
#override
Widget build(BuildContext context) {
return Column(
children:[
for (int k = 0;k < widget.snapshot.reply!.length;k++) ...[
for(int l=0;l<widget.snapchatReply.length;l++) ...[
if(widget.snapchatReply[l]["commentId"]==widget.snapshot.id && widget.snapchatReply[l]["isShown"]==true) ...[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
iconSize: 50,
onPressed: () {},
icon: CircleAvatar(
radius: 80,
backgroundImage: NetworkImage(widget.snapshot.reply![k].user.profile),
)),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: MediaQuery.of(context).size.width -200,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(10),
color: Colors.grey[300]),
padding: EdgeInsets.all(8),
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
widget.snapshot
.reply![k].user.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight:
FontWeight.bold),
),
RichText(
text: TextSpan(
style: TextStyle( fontSize:18,color:Colors.grey[700],fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(text:widget.snapshot.user.name + " ", style: TextStyle(color: Colors.black)),
TextSpan(text:widget.snapshot.reply[k].replyText,style: TextStyle(fontWeight: FontWeight.normal) ),
],
),
),
])),
])
])
]
]
]
],
);
}
}
You can not use snapchatReply[a]['isShown'] to change variable inside map inside the list, you should pass new variable to it, try this:
toggleReply(String commentId) {
for (int a = 0; a < snapchatReply.length; a++) {
print(snapchatReply.length);
if (commentId == snapchatReply[a]['commentId']) {
if (snapchatReply[a]['isShown'] == false) {
setState(() {
snapchatReply[a] = {
'commentId': snapchatReply[a]['commentId'],
'isShown': true
};
});
} else {
print("else");
setState(() {
snapchatReply[a] = {
'commentId': snapchatReply[a]['commentId'],
'isShown': false
};
});
}
}
}
}
your main issue is every time you call setstate this:
snapchatReply.add({
"commentId":widget.snapshot.comments[j].id,
"isShown":false
});
will call, so this is cause doubling you list length every time, what you need to do is, rest you list before it. so try call snapchatReply = []; before returning your ListView.builder.

create a fixed sized widget on flutter

I'm currently trying to create a row that consist of maximum 3 column widget with each of them have the property of profile picture, nickname, and status. I wanted each of them to have fixed size so that even when the nickname is long it will still take the same amount of space.
Currently I just make the column to be spaced-evenly and some of the widget still take more space than the other 2. How can I fixed this ? maybe make the nickname turned into dotted (...) when it's too long.
here's my current code:
solverWidgets.add(
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
BuildRoundedRectProfile(
height: 40,
width: 40,
name: solverTicket[solver]['nickname'],
profileLink: solverTicket[solver]['profile_picture_link'] ?? '',
),
SizedBox(height: 3),
Text(
solverTicket[solver]['nickname'],
style: weight600Style.copyWith(
color: primaryColor,
fontSize: 13,
),
),
if (solversStatus[solver] != null && (povStatus == 'pic' || povStatus == 'pic-client'))
GestureDetector(
onTap: () {
if (solversStatus[solver] == 'Done') {
setState(() {
needToLoadSolverWidgets = true;
isNotExpandedSolverWidgets[solver] = !isNotExpandedSolverWidgets[solver];
});
if (isExpandedSolverWidgetsContent[solver]) {
Future.delayed(Duration(milliseconds: 300), () {
setState(() {
needToLoadSolverWidgets = true;
isExpandedSolverWidgetsContent[solver] = false;
});
});
} else {
setState(() {
needToLoadSolverWidgets = true;
isExpandedSolverWidgetsContent[solver] = true;
});
}
}
},
child: AnimatedContainer(
duration: Duration(milliseconds: 300),
height: isNotExpandedSolverWidgets[solver] ? 20 : 55,
padding: EdgeInsets.only(top: 5, bottom: 5, left: 5, right: 5),
decoration: BoxDecoration(
color: defaultProfileColor.withOpacity(0.2),
borderRadius: BorderRadius.circular(10),
),
child: solversStatus[solver] != 'Done' ?
Text(
solversStatus[solver],
style: primaryColor600Style.copyWith(
fontSize: fontSize9,
),
).tr() : isNotExpandedSolverWidgets[solver] ?
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
solversStatus[solver],
style: primaryColor600Style.copyWith(
fontSize: fontSize10,
),
).tr(),
Icon(
Icons.arrow_drop_down,
size: fontSize15,
),
],
) : ClipRRect(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Row(
children: [
Text(
solversStatus[solver],
style: primaryColor600Style
.copyWith(
fontSize: fontSize9,
),
).tr(),
Icon(
Icons.arrow_drop_down,
size: fontSize18,
),
],
),
GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext
context) =>
ReusableConfirmationDialog(
titleText: 'changeWorkStatus'.tr(),
contentText: 'rejectWorkStatus'.tr(),
confirmButtonText: 'yes'.tr(),
onConfirm: () async {
await Database.changeWorkStatus(
ticketId: widget.ticketId,
ticketData: ticketData,
targetId: solver as String,
oldWorkStatus: 'done',
workStatus: 'todo');
Navigator.pop(context);
setState(() {
isNotExpandedSolverWidgets[solver] = true;
needToLoadTicket = true;
});
}));
},
child: Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: warningColor,
borderRadius:
BorderRadius.circular(5),
),
child: Text(
'disagree',
style: primaryColor600Style
.copyWith(
fontSize: fontSize9,
color: Colors.white,
),
).tr(),
),
)
]),
),
),
),
if(solversStatus[solver] != null && (povStatus != 'pic' && povStatus != 'pic-client'))
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: formBackgroundColor,
borderRadius: BorderRadius.all(
Radius.circular(10))),
child: Text(
solversStatus[solver],
style: weight600Style.copyWith(
color: primaryColor,
fontSize: 9,
),
),
),
],
),
);
use Text overflow
Text(
'You have pushed the button this many times:dfjhejh dskfjkawejfkjadshfkljhaskdfhekjnkjvnkjasdklfjjekjlkj',
maxLines: 1,
overflow: TextOverflow.ellipsis,
)
or You can use https://pub.dev/packages/marquee package, it will scroll your text infinitly. make sure to wrap this marquee widget in a sizedbox with height and width defined.

Text overflow flutter

I have the next widget, which is rendered with overflow. I have tried to solve, but i don't know. Can anyone help me? The aim is to do a custom card inside listview.
I have tried to wrap with expanded buth then, the error is referenced with constraints.
import 'package:flutter/material.dart';
import '../../shared/AppTheme.dart';
class ComandaScreen extends StatefulWidget {
const ComandaScreen({Key? key}) : super(key: key);
#override
State<ComandaScreen> createState() => _ComandaScreenState();
}
class _ComandaScreenState extends State<ComandaScreen> {
bool expanded = false;
int unidades = 0;
final List<Map<String, dynamic>> _items = List.generate(
10, (index) => {'id': index, 'Nombre': 'Nuggets $index',
'isExpanded': false, "unidades": 8});
#override
Widget build(BuildContext context) {
final ButtonStyle flatButtonStyle = TextButton.styleFrom(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
);
return Scaffold(
appBar: AppBar(
title: const Text('Comanda'),
backgroundColor: AppTheme.backgroundColor,
foregroundColor: AppTheme.primaryTextColor,
elevation: 0,
),
body: SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
// expandedHeaderPadding: const EdgeInsets.all(10),
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: const Duration(milliseconds: 200),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
// backgroundColor: item['isExpanded'] == true ? Colors.cyan[100] : Colors.white,
headerBuilder: (context, isExpanded) {
return Container(
margin: const EdgeInsets.all(10),
child: Row(children: [
const CircleAvatar(
child: Text(
'1',
textAlign: TextAlign.center,
)),
const SizedBox(
width: 10,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Nuggets',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w600),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Text(
'Unidades: ${7}',
style: TextStyle(color: Colors.black),
),
Text(
'Pendientes: 400',
style: TextStyle(color: Colors.black),
),
],
),
const SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Precio: 10 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
Text(
'Total: 70 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
],
),
],
),
],
),
),
]),
);
},
body: ButtonBar(
alignment: MainAxisAlignment.spaceAround,
buttonHeight: 52.0,
buttonMinWidth: 90.0,
children: <Widget>[
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] += 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.add,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Más'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] -= 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.remove,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Menos'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.edit_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Editar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.delete_outline_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Eliminar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.card_giftcard_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Invitar'),
],
),
)
],
),
isExpanded: item['isExpanded'],
),
)
.toList(),
// Card_lineaComanda(flatButtonStyle),
),
),
);
}
}
I 've edited the code to show all screen widget.
Image of result of code before:
For desktop applications, you can prevent the resize with breakpoint, so the error won't happen. In the pubsec.yaml file, add the following dependency.
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
And in your main method before runapp add this code with min-width and min-height below which the app won't resize.
const double desktopMinWidth = 800.0;
const double desktopMinHeight = 600.0;
if (Platform.isMacOS || Platform.isWindows) {
setWindowMinSize(const Size(desktopMinWidth, desktopMinHeight));
setWindowMaxSize(Size.infinite);
}
Note: Once done restart your app.
For mobile, it is entirely a different case. You might need to restructure the design

type 'some model' is not a subtype of type 'same model' But it is

When I get data from the server and change that to a model Called SetupIdeaModel I get this error.
type 'SetupIdeaModel' is not a subtype of type 'SetupIdeaModel' where
SetupIdeaModel is from package:onion/models/idea.dart
package:onion/models/Idea.dart:1
SetupIdeaModel is from package:onion/models/Idea.dart
package:onion/models/Idea.dart:1
I say the SetubIdeaModel is not a subtype of type 'SetupIdeaModel' But it is the same file and same model. Why I get this error.
I get data with this method.
Future getRequestDetails(String token, String requestId) async {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/request/$requestId",
token: token,
);
try {
List data = [
User().fromMap(response.data['data']['userId']),
SetupIdeaModel().fromJson(response.data['data']['ideaId']),
RequestModel().formJson(response.data['data']),
];
return data;
} catch (e, st) {
print("Error $e");
print("Stacktrace $st");
return "Something went wrong!";
}
}
the APIRequest() is a global method that I created for my requests. Ans also I'm using Dio packages for my requests.
The SetupIdeaModel
class SetupIdeaModel {
String id;
String userId;
String typeIdea = "Implemented Idea";
String category; //Or Industry
String experienceYear;
String experienceMonth;
String ideaHeadline;
String ideaText;
Map timeline = {
"timelineType": "date",
"details": null,
};
fromJson(json) {
return SetupIdeaModel(
typeIdea: json['ideaType'],
category: json['industry'],
ideaHeadline: json['headline'],
ideaText: json['idea'],
);
}
SetupIdeaModel({
this.uploadVideo,
this.location,
this.estimatedPeople,
this.whitePaper,
this.id,
this.userId,
this.typeIdea,
this.category,
this.experienceYear,
this.experienceMonth,
this.ideaHeadline,
this.ideaText,
this.timeline,
});
List documents = [];
Map uploadVideo;
String location;
String estimatedPeople;
Map whitePaper;
bool needServiceProvider = false;
bool needInvestor = true;
Map toSendMap() {
return {
"ideaType": typeIdea,
"industry": category,
"industryExperienceInMonth":
"${int.parse(experienceYear) * 12 + int.parse(experienceMonth)}",
"headline": ideaHeadline,
"idea": ideaText,
"timeline": timeline,
"uploadDocuments": documents,
"uploadVideo": uploadVideo,
"targetAudience": "$location",
"uploadPaper": whitePaper,
"estimatedPeople": estimatedPeople,
"needServiceProvider": "$needServiceProvider",
"needInvestor": "$needInvestor",
};
}
}
Using models with is FutureBuilder
FutureBuilder(
future: getData,
builder: (context, snapshot) {
if (snapshot.hasData) {
User _user = snapshot.data[0];
SetupIdeaModel _idea = snapshot.data[1];
RequestModel _request = snapshot.data[2];
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"${_idea.typeIdea}",
style: TextStyle(
color: deepBlue,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: Icon(Icons.info_outline,
color: middlePurple, size: 20),
onPressed: () {},
),
],
),
Card(
elevation: 4,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
child: Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"${_request.postedOn}",
style: TextStyle(color: Colors.black),
),
],
),
SizedBox(height: 10),
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(width: 0.5, color: deepGrey),
),
child: Column(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text("Industry",
style: TextStyle(color: deepGrey)),
Text(
"${_idea.category}",
style: TextStyle(color: Colors.black),
),
],
),
Divider(),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text("Idea Headline",
style: TextStyle(color: deepGrey)),
Text(
"${_idea.ideaHeadline}",
style: TextStyle(color: Colors.black),
),
],
),
Divider(),
SizedBox(height: 5),
Align(
alignment: Alignment.centerLeft,
child: RichText(
text: TextSpan(
text: 'Idea: ',
style: TextStyle(color: Colors.black),
children: <TextSpan>[
TextSpan(
style: TextStyle(
color: deepGrey,
fontWeight: FontWeight.normal),
text: "${_idea.ideaText}",
),
],
),
),
),
],
),
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
CircleAvatar(
backgroundImage: NetworkImage(
"${_user.profile ?? 'https://i.pravatar.cc/300'}"),
),
SizedBox(width: 5),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text("${_user.name}",
style: TextStyle(
fontWeight: FontWeight.bold)),
Text("${_user.industry}",
style:
TextStyle(color: deepGrey)),
Row(children: [
Text("Rated: ",
style:
TextStyle(color: deepGrey)),
MyFiveRating(rateVal: _user.rate),
])
],
),
]),
Row(children: [
InkWell(
child: Icon(Icons.more_vert,
color: deepGrey),
onTap: () {},
),
])
],
),
Divider(),
Row(children: [
Text("Interested in: "),
Icon(Icons.radio_button_checked,
color: middlePurple),
Text("${_request.investAs.type}"),
]),
Divider(),
RichText(
text: TextSpan(
text: 'Message: ',
style: TextStyle(color: Colors.black),
children: <TextSpan>[
TextSpan(
style: TextStyle(
color: deepGrey,
fontWeight: FontWeight.normal,
),
text:
"This is my message to you. Yes you, Who are reading this text.I'm with you how are you I'm fine thanks. Everything is goin well and what about you bro."),
],
),
),
],
),
)
]),
),
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GlowCheckbox(
color: Theme.of(context).primaryColor,
value: checkboxSelected,
enable: true,
onChange: (bool value) {
setState(() {
checkboxSelected = !checkboxSelected;
});
},
),
SizedBox(
width: 10,
),
Expanded(
// child: Text(
// "By Cheacking the box you agree to out terms and services",
// ),
child: RichText(
text: TextSpan(
text: 'Agree to ',
style: TextStyle(color: Colors.black),
children: <TextSpan>[
TextSpan(
text: 'Term and Condition',
style: TextStyle(
color: middlePurple,
decoration:
TextDecoration.underline),
recognizer: TapGestureRecognizer()
..onTap = () {
showDialog(
context: context,
builder: (context) {
return TandCDialog();
},
);
},
),
TextSpan(
text:
' and contract while Requesting this Franchise!'),
],
),
),
)
],
),
SizedBox(height: 5),
SizedBox(
width: double.infinity,
child: RaisedButton(
child: Text(
"Accept Add On Project",
style: TextStyle(
fontSize: 18,
color: Colors.white,
),
),
color: middlePurple,
onPressed: () {
acceptAddOnProject(true, _scaffoldKey);
},
),
),
SizedBox(
width: double.infinity,
child: OutlineButton(
child: Text(
"Declient",
style: TextStyle(
fontSize: 18,
),
),
onPressed: () {
acceptAddOnProject(false, _scaffoldKey);
},
),
),
],
),
),
],
),
),
);
} else if (snapshot.hasError) {
print("error ${snapshot.error}");
return Center(
child: Text(
"Something went wrong, While getting data from the server."));
} else {
return Center(child: SingleChildScrollView());
}
},
),
Flutter doesn't recognize the two paths as the same since they differ in upper vs lower case. Fix your imports so that they reference the same file.

Flutter return widgets in for loop

My code below is working, but instead of returning multiple widgets based on the length of the list, it stops in the first round and after a lot of research and googling I understand that it stops because I'm returning a widget. So basically the for loop stops when it hits the "return".
And if I don't add the "return" before the widget it return's nothing or it gives error saying that the "widget expecting a return type but nothing returning". So no "I think" I know th issue but I can't find the solution.
#override
Widget build(BuildContext context) {
for (var allAttributes in widget.allAttributes) {
//print(allAttributes.name);
bool attributeCheck;
if(widget.attributes.length > 0){
for(var attributes in widget.attributes){
if(allAttributes.id == attributes.attributeId){
return Row(
children: <Widget>[
new Container(
alignment: Alignment(-1.0, -1.0),
child: Padding(
padding: const EdgeInsets.only(bottom: 10.0, right: 10.0),
child: Text(
allAttributes.name + ':',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w600),
),
)),
DropdownButton<Attributes>(
hint: Text("Select item"),
value: selectedUser,
onChanged: (Attributes Value) {
setState(() {
selectedUser = Value;
});
},
items: widget.attributes.map((Attributes attributes) {
return DropdownMenuItem<Attributes>(
value: attributes,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
attributes.value,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
],
);
}
}
}
}
return Text('Nothing');
}
I did try with the map but it didn't work too, Here's the code for the map:
#override
Widget build(BuildContext context) {
widget.allAttributes.map((AllAttributes allAttributes) {
//print(allAttributes.name);
widget.attributes.map((Attributes attributes){
return Row(
children: <Widget>[
new Container(
alignment: Alignment(-1.0, -1.0),
child: Padding(
padding: const EdgeInsets.only(bottom: 10.0, right: 10.0),
child: Text(
allAttributes.name + ':',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w600),
),
)),
DropdownButton<Attributes>(
hint: Text("Select item"),
value: selectedUser,
onChanged: (Attributes Value) {
setState(() {
selectedUser = Value;
});
},
items: widget.attributes.map((Attributes attributes) {
return DropdownMenuItem<Attributes>(
value: attributes,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
attributes.value,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
],
);
}).toList();
}).toList();
return Text('Nothing');
}
I think Map method of list could be best solution for this type of situation.
It is really hard to change such big code without edit, so i showed how you can do in your case.
List<int> _data = [1, 2, 3, 4, 5, 6];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: _data.map((e) {
return Text(e.toString());
}).toList(),
)),
);
}
I still tried my best to change code. i hope following code work without any error.
Moreover, you was making list two time by wrapping list with list(for loop with for loop) so removed it.
//print(allAttributes.name);
return Column(
children:
widget.attributes.length>0? widget.attributes.map((Attributes attributes){
return Row(
children: <Widget>[
new Container(
alignment: Alignment(-1.0, -1.0),
child: Padding(
padding: const EdgeInsets.only(bottom: 10.0, right: 10.0),
child: Text(
allAttributes.name + ':',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w600),
),
)),
DropdownButton<Attributes>(
hint: Text("Select item"),
value: selectedUser,
onChanged: (Attributes Value) {
setState(() {
selectedUser = Value;
});
},
items: widget.attributes.map((Attributes attributes) {
return DropdownMenuItem<Attributes>(
value: attributes,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
attributes.value,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
],
);
}).toList(): [Text('Nothing')]);