Setting a background in flutter from a list - list

I would like to have a page called Theme with grid images, and when I click on an image, to select that image as my background to home page.
This is a list I have:
List<Theme2> themeitems = [
Theme2(
background: 'assets/images/theme/deskWhite.png',
selected: false,
),
Theme2(
background: 'assets/images/theme/greenDrop.png',
selected: false,
),
Theme2(
background: 'assets/images/theme/leaf.png',
selected: false,
),
],
This is a home page where I would like to set a background image:
child: Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/theme/sand.png'),
////// image: AssetImage(themeitems[idx].background.selected), // I know this is not correct
fit: BoxFit.cover,
),
),
child: Column(.........
So, how could I set background image from one of these list items?
I tried using themeitems[index].selected = !themeitems[index].selected; but I am not sure how to use it correctly. If there is a problem like this on the net, please send me a link.
Thank you for your time.

Based on your code, I think it's easier to rename your images into something more sequentially, for example: image1.png, image2.png, image3.png,...
You can store it in a list, but I think you don't need to do that, as long as you've added your images in your assets folder.
And then, to select the image, inside your code:
int index = 0; //this variable is to store your selected index
child: Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/theme/image$index.png'), //So if the index = 0, so image).png will appear. And, so on.
fit: BoxFit.cover,
),
),
child: Column( //YOUR CODE

Related

How to add a change of color hover on ReorderableListView icons in flutter?

I have this ReorderableListView in my app, and I would like that when I hover my mouse on the check-circle icons on the left, they change color,
Right now when I hover my mouse over it, nothing happens, they are not even clickable
Here is the part of the ReorderableListView code where I define icons and text of each item :
children: listeTaches.map((e) => ListTile(
key: UniqueKey(),
//leading: Icon(Icons.task),
leading: Icon(BeoticIcons.disc),
title: Text(e),
//trailing: Icon(Icons.more_vert),
trailing: Icon(BeoticIcons.circle_check)
)).toList(),
Thanks for your help !
Try below code hope its helpful to you:
I think is same as like our Icon Widget for eg.
Icon(Icons.add,color:Colors.red),
Just try your Icon like below
Icon(BeoticIcons.circle_check,color:Colors.red),
You need to handle the event and launch the desired code when it happens. For this, you will need a StatefulWidget and control the event that triggers it (https://flutter.dev/docs/development/ui/advanced/gestures).
Greetings
You could use Mouse Region to handle the hover interaction with your icon. If you wrap your icon widget with a mouse region then you just change the color in the onHover event. Something like this :
children: listeTaches.map((e) => ListTile(
key: UniqueKey(),
//leading: Icon(Icons.task),
leading: MouseRegion(
onHover: _updateIcon,
child:Icon(BeoticIcons.disc, color:my_color)),
title: Text(e),
//trailing: Icon(Icons.more_vert),
trailing: Icon(BeoticIcons.circle_check)
)).toList(),
Then in the _updateIcon you could change a variable that the icon would use as the color
final my_color = Colors.grey; //declare before with the default color of your icon
_updateIcon(){
setState(() {
my_color = Colors.red;
});
}
Hope i could help :)

Flutter chat app with django channels backend keeps reloading

I am using flutter chat app and using Django Rest Framework + channels as the backend. In the chat page, I am using the following code to display messages -
Scaffold(
backgroundColor: backColor,
appBar: AppBar(),
body:
GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor,
),
),
);
}else{
var mymessages = jsonDecode(snapshot.data);
if(mymessages['command']=='messages'){
// setState(() {
messages = ChatMessagesList.fromJson(mymessages["messages"]).messages;
// });
}else{
ChatMessage msg = ChatMessage.fromJson(mymessages["message"]);
if(!messages.contains(msg))
// setState(() {
messages.add(msg);
// });
}
return Column(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
color: backColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
),
),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
),
child:
ListView.builder(
reverse: true,
padding: EdgeInsets.only(top: 15.0),
itemCount: messages.length,
itemBuilder: ( context, index) {
final ChatMessage message = messages[index];
final bool isMe = message.sender.username == linUser.username;
return _buildMessage(message, isMe);
},
),
),
),
),
_buildMessageComposer(),
],
);
}
}
)
,
),
)
Here channel is IOWebSocketChannel that connect to django websocket url, and it is closed in dispose(). messages is a List<ChatMessage> declared outside build. Depending on what is sent via channel.sink either list of ChatMessage is received or just a single, latest ChatMessage sent by users.
Problem is, as long as the list of messages has a message, the chat page as well as all the previous pages in the stack start reloading/refreshing continuously, the displayed page itself stays at the chat page, but in the terminal, the print statements from earlier pages like Home Page and ChatRooms page keep showing up repeatedly, non stop, without any error. I have tried a few methods like using rest api to load the past messages, but the moment there is a new message on channel.stream, the reload/refresh starts. It only stops when I navigate back to previous page i.e. the ChatRooms page. I tried using stream controller but that went nowhere.
I also checked some examples that use firebase, and realized that their stream receives the entire list of messages everytime. What I am trying to do is fetch the list of past messages once at the beginning, save it inside messages, and then keep adding to the list as and when messages are sent/received. The same will be reflected in the page.

How do I display name (without extension) of files from assets folders in flutter

I have some music files in my assets folder and I want to automatically display them in a list, without having to write a line for every single music in the folder.
I think something like ListView.builder might work, but I'm pretty new in all this and not quite sure how to execute this properly.
Since it's impossible to get the names of your music files from the /assets folder within a Flutter project, I think you can try these ways:
Have a json file listing all the metadata of the files (name, artist, path in /assets, etc) and work with that file (get the name, get the path of the file, etc).
Store your music online and get them through APIs
Copy all the music from your /assets into a phone's directory, then handle the files from that directory from now on (For example: Call this method to get the names of the files). Check out this answer.
If what you want to display is like the image you describe, and if the name is not important (like ringtones), then you can simply do this (assuming you name the files by numbers from 1-10):
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: SampleScreen(),
));
}
class SampleScreen extends StatefulWidget {
#override
_SampleScreenState createState() => _SampleScreenState();
}
class _SampleScreenState extends State<SampleScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) => _buildMusicItem(index)),
);
}
Widget _buildMusicItem(int index) {
return Container(
height: 40,
margin: EdgeInsets.all(5),
padding: EdgeInsets.only(left: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.red, width: 2)),
alignment: Alignment.centerLeft,
child: Text('Music ${index + 1}'),
);
}
}
Result:

Adding API code in a basic Google Bar Chart

I have a basic google chart:-
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic'],
['2006', 1600652, 4604684, 940478],
['2007', 1968113, 4013653, 1037079],
['2008', 1901067, 6792087, 1037327]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"}}
);
}
​
I want to be able to specify the border color and width etc.
Can you tell me how to use the API commands:-
backgroundColor.stroke,
backgroundColor.strokeWidth,
i.e How do I add these API calls.
Thanks
You can send the settings for both the stroke color and strokeWidth with the rest of you options, similar to how you've specified the title for the hAxis:
backgroundColor: {
stroke: '#000',
strokeWidth: '2'
}
That would give the chart a black 2pixel border, demo on jsfiddle.

How to set Google Charts legend width in JavaScript?

I am generating this Google Line Chart using the Google JS API. As you can see, the labels are very narrow. How do I make it so that the whole label text is visible?
Here are some samples based on the google code playground line charts. Adjusting the chartArea width option gives more space for labels:
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10},
chartArea: {width: '50%'}}
);
If it's an option, you could also position the labels beneath the chart, which gives considerably more space:
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10},
legend: 'bottom'}
);
Expanding the chartArea option to a width of 100% solved the problem for me. Contrary to the documentation, the chartArea does include the legend. I used a PieChart but the same option is available for the LineChart.
var options = {'title':title,'width':w,'height':h,'chartArea':{left:0,top:10,width:"100%"}};
var chart = new google.visualization.PieChart(document.getElementById(chartDiv));
chart.draw(data,options);
Reference.
None of the previous answers worked well for me. Setting width to less than 100% centers the plot area and leaves too much unused space on the left. Setting it to 100% is not a solution either.
What worked well - see live working fiddle - is setting the right value to accommodate the legend, then adjusting the left value eventually, for the Y axis title and labels. The plot area width will adjust automatically between these two fixed margins:
var options = {
...
legend: { position: 'right' },
chartArea: {
right: 130, // set this to adjust the legend width
left: 60, // set this eventually, to adjust the left margin
},
...
};
There is an option in legend.textStyle we can customize legend text styles inside google charts
var options = {
legend: { textStyle: { fontSize: 78 //size of the legend
} }
}
You need to make the chart wider or your labels shorter.