how to display random image on a container in flutter - flutter

I am new at flutter. and I want to add random picture in a container how to add random picture from assets()?
For example when user use my application and refresh the page the picture in the container will change automatically.

You shall make a list of all the asset files like this and so on...
List<String> assets=['assets/file1.png','assets/file2.png'];
in your build function call assets.shuffle(). This will reorder the assets file in random order and then make a variable imagepath as:-
String imagePath=assets[0];//now this will store a random image path ..
Whole code:-
class MyApp extends StatelessWidget {
List<String> assets=['assets/file1.png','assets/file2.png'];
String imagePath;
#override
Widget build(BuildContext context) {
assets.shuffle();//shuffle over here
imagePath=assets[0];//store random image over here
return Container(
child: Image.asset(imagePath),//show random image
);
}
}
You can also perform shuffle and other tasks in the initState of a statefull widget.

You have to implement something yourself. I would suggest adding possible images to a list
const List<String> randomImages = [
"assets/images/image1",
"assets/images/image2",
"assets/images/image3",
"assets/images/image4",
"assets/images/image5",
];
Then using darts random class, Find a random int to use as an index that is bounded by the length of the string
Random random = Random()
int randomIndex = random.nextInt(randomImages.length)
Image randomImage = randomImages[randomIndex];

Related

How to add new cards to gridview on tap of button flutter

I am trying to code something for my flutter app.
I have an empty gridview (5x6 configuration) on center top and 5 colored buttons (color containers) at the bottom (each with a different color), and a remove all button on the bottom right).
When I tap one of the 5 buttons, a container (or card) appears on the left in the gridview, having the same color of the button. When I press another button, another container appears, and so on (untill 30 containers appear - limit). I can make any mix of containers.
When I then press the remove all button, all containers in the grid view are removed.
I also have to use flutter riverpod for statemanagement and divide custom widgets in different files.
Can anyone tell me or code this for me?
Iā€™m a bit stuck atm.
Thank you in advance! šŸ™
MY CODE (lib folder of project)
enter link description here
I've created a flutter app that demonstrates a grid painter that you might be looking for (Gif)
In order to do this I have used the Bloc pattern using (flutter_bloc) library.
It helps to start by defining the initial state of the app which is a list of 30 transparent tiles(5x6)
part of 'painter_bloc.dart';
#immutable
abstract class PainterState extends Equatable {
final List<Tile> tiles;
const PainterState(this.tiles);
#override
List<Object?> get props => [tiles];
}
class PainterInitial extends PainterState {
PainterInitial() : super(List.generate(30, (index) => Tile.empty(index)));
}
Each Tile(defined model class) holds two properties
class Tile {
final int index;
final Color color;
Tile({
required this.index,
required this.color,
});
factory Tile.empty(int index) =>
Tile(index: index, color: Colors.transparent);
There is one event that is dispatched from the UI to the PainterBloc i.e. ColorTapped (An event that is trigged when one of the colored cards is tapped)
This event holds two pieces of information(card color, currentTileIndex)
part of 'painter_bloc.dart';
#immutable
abstract class PainterEvent {}
class ColorTapped extends PainterEvent {
final Color color;
final int currentTileIndex;
ColorTapped(this.color, this.currentTileIndex);
}
One the PainterBloc receives the ColorTapped event. It emits a PainterMarked state with a modified list of Tiles
class PainterBloc extends Bloc<PainterEvent, PainterState> {
PainterBloc() : super(PainterInitial()) {
on<ColorTapped>(_onColorTapped);
}
void _onColorTapped(ColorTapped event, emit) {
List<Tile> markedTiles = <Tile>[...state.tiles];
markedTiles[event.currentTileIndex] = state.tiles
.where((element) => element.index == event.currentTileIndex)
.first
.copyWith(color: event.color);
emit(PainterMarked(markedTiles));
}
This new state is used to rebuild the UI thereby coloring the tiles.
I have also used a CounterBloc to help keep track of the pointer/index of the grid tiles to color.
You can find the complete code here

reusable classes in flutter

I have a page like the following. This page has two buttons. One of them is sending the form to the relevant place. In my case to the instructor. But, this one is not important for now. The second button is the important one. Anyway, the second one is saving the form as a draft. So, I know I need to save the data that is entered, in SQLite. Then when he/she want to edit the form again I need to pull the data from SQLite then fill the relevant places. Here is the question. When I click to edit button. The page below will show up with the content that is filled before. However, for this task, it does not make sense to code again the screen below for the edit button. So I need to reuse the page below. How can I do it? Any idea. Is there any content that could be helpful? Please attach a link, video, etc. It doesn't matter. I just want to learn how to do it. I hope I could explain the situation. If any more information is required to understand the situation feel free to ask for it.
There are many ways to achieve what you need. But basically, you need to check whether there is saved data or not? If there is saved data then show it otherwise show an empty page. Simple example:
class MyPageData {
String firstField;
String secondField;
// ... fields with page info
}
class MyFormPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MyForPageState();
}
class _MyForPageState extends State<MyFormPage>{
MyPageData _savedData;
#override
void initState() {
super.initState();
_savedData = loadDataFromDb();
}
#override
Widget build(BuildContext context) {
String myFirstField = "";
String mySecondField = "";
// other fields
if (_savedData != null){
myFirstField = _savedData.firstField;
mySecondField = _savedData.secondField;
// other fields
}
// render page with fields values above
}
}
Here MyPageData is a model of all the data on your page. So it's easier to work with. Also, this data is saved to db and restored from db in the future.
MyFormPage is a stateful widget for your form page. There is a loadDataFromDb method that is used to load saved data. Then in the build method, we check whether there is saved data or not. If there is data we filled initial values for all fields on our page and use those fields as initial values for the widgets from which our page is constructed. So if there is no data saved then _savedData will be null and all widgets will have empty initial values.
If you put your page in a widget like this
class MyPage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
body: // your page here
)
}
}
you can open it in different locations.
_onButton1Click(BuildContext context){
// do something button 1 specific
final route = MaterialPageRoute(builder: (context) => MyPage());
Navigator.of(context).push(route);
}
_onButton2Click(BuildContext context){
// do something button 2 specific
final route = MaterialPageRoute(builder: (context) => MyPage());
Navigator.of(context).push(route);
}

I have a stored List data and how can I localize it in flutter?

I can translate the text inside the widget using AppLocalizations.of(context)!.translated and it work fine
However, when I want to localize a stored List<> data which will be used in listView Builder, I am not able to do so, since it need (context).
My question is how to localize a stored list data(outside widget) and pass to list view builder?
Thanks for your help.
I think you should do 2 things
In case if you have a list in another file, then it should be static like this:
class Presets {
static var presetData = [];
}
after you loaded up your list, you can do these steps:
First,
Create Widgets as children like this:
List<Widget> presetsLoadUp() {
List<Widget> children = <Widget>[];
for(i < yourList.length){
children.add(Text(yourList[i]));
}
return children;
}
You can create your own unique widget inside the children.add method.
Secondly,
Create the list:
...
child: ListView(
children: presetsLoadUp(),
),
If anyone has similar problem, please take it for reference.
I just build another widget to solve this.
What I do is :
build another widget,
then put the list data inside and
return ListViewBuilder.
Everything is same,
just put your list data inside another widget can solve the problem

Is there a way to display RaisedButtons in a ButtonBar lazily?

I have a set of buttons I want to display on a flutter app to represent the days of the week. I currently have a widget that builds 7 RaisedButtons to represent the various days of the week. Is there a way I can do this lazily instead of having to build all 7 RaisedButtons in flutter?
Note I am using the ButtonBar widget to display the set of buttons.
You can declare a list like following:
List<Widget> _optionList = List<Widget>();
and add as many and any kind of widget in the list, like following:
void setupHintButtonsUI() {
_optionList.clear();
for (var i = 0; i < 7; i++) {
_optionList.add(
FlatButton(),
);
}
}
You can make an empty list of strings and add days name in it and then iterate through it. Create a function using the for loop like
var i = "";
main() {
final List<String> days = <String>['Sunday', 'Monday', 'Tuesday','Wednesday','Thurday','Friday'];
days.sort();
// print(days);
for (i in days){
print(i);
}
}
and then you can loop through the code and create widgets

How can I get context from dart file

I have this dart file category_data.dart:
import 'package:flutter/material.dart';
final List categories = [
'Entertainment',
'Sports',
'Politics',
'Science',
'Technology',
'Travel'
];
/*
you can change your category here.
If you change, make sure you have changed in the admin panel.
Otherwise the app will show error.
*/
/*
if your change the defalut category, make sure your category item munber is equal to category colors item number.
Example: If you have 5 categories, then remove an color item in the category colors.
else if you have more than 6 categories, then you have to add color items in the category colors List down below.
*/
final List categoryColors = [
Colors.orange[200],
Colors.blue[200],
Colors.red[200],
Colors.pink[200],
Colors.purple[200],
Colors.blueGrey[400]
];
I want to add internationalization through intl plugin. For this I am using the follow code to get the locale translation of text:
AppLocalizations.of(context).categoryName
Then categories list would be the following:
import 'package:flutter/material.dart';
import 'package:news_app/generated/l10n.dart';
final List categories = [
AppLocalizations.of(context).entertainment,
AppLocalizations.of(context).sports,
AppLocalizations.of(context).politics,
AppLocalizations.of(context).science,
AppLocalizations.of(context).technology,
AppLocalizations.of(context).travel
];
But this code give me an error, because I don't have the context:
Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name
How could you get the context to use internationalization? I have only seen the context in the build method of the widgets.
You can define a method and pass the context to it.
List _getCategoryList(BuildContext context) {
return [
AppLocalizations.of(context).entertainment,
AppLocalizations.of(context).sports,
AppLocalizations.of(context).politics,
AppLocalizations.of(context).science,
AppLocalizations.of(context).technology,
AppLocalizations.of(context).travel
];
}
You can use it like:
final List categories = _getCategoryList(context); -- Use this inside your widget.
I had the same issue before, the way i resolved it is to create a GlobalKey:
static GlobalKey rootWidgetKey = GlobalKey();
Then attach it to your root widget:
...
home: YourRootWidget(
key: rootWidgetKey,
...
Then you can access the root context anywhere by referring to rootWidgetKey.currentContext.
add your list after the build method like the example
#override
Widget build(BuildContext context) {
final List categories = [
AppLocalizations.of(context).entertainment,
AppLocalizations.of(context).sports,
AppLocalizations.of(context).politics,
AppLocalizations.of(context).science,
AppLocalizations.of(context).technology,
AppLocalizations.of(context).travel
];
return ...