How can I get context from dart file - flutter

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 ...

Related

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

how to display random image on a container in 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];

Flutter, pasing parameters on StatefulWidget

Can someone tell me what is happening in this program?
body: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new StuffInTiles(listOfTiles[index]);
},
itemCount: listOfTiles.length,
),
),
);
}
}
class StuffInTiles extends StatefulWidget{
final MyTile myTile;
const StuffInTiles(this.myTile);
#override
StuffInTilesState createState() => StuffInTilesState();
}
class StuffInTilesState extends State<StuffInTiles> {
#override
Widget build(BuildContext context) {
return Container(child:
//Text(widget.myTile.title),);
_buildTiles(widget.myTile));
}
Widget _buildTiles(MyTile t) {
I want to understand how passing parameters works,why i have
const StuffInTiles(this.myTile);
in this program, what this code is doing?
in my class StuffInTilesState extends State<StuffInTiles> i don't have any constructor, so how this code is working? why my parameters just happen to be there? before i was learning C++, so this is like a magic to me
If you learned C++ you are probably familiar with initializer list, which Dart has as well. In C++ you could do something:
MyClass {
MyClass(MyTitle title) : this.myTitle = title;
final MyTitle myTitle;
}
Which is also valid in Dart. However, Dart allows you to shorthand the call, by automatically assigning the reference to the new class property, without using any intermediate variable.
MyClass(this.myTitle);
Which is basically the same but ensures that any given property won't be null unless you explicitly pass null.
There are other type of constructors available on Dart, such as private constructors, factory constructors and named constructors. You may want to check the official documentation to learn more about it.
By default, when you create classes in Dart, there is just a default constructor implemented.
For example, if you have a class named AwesomeWidget. It will have a default constructor AwesomeWidget() that lets you create an instance of this widget.
So you could use a default constructor in code like so:
//Example 1
return AwesomeWidget();
//Example 2
AwesomeWidget myWidget = AwesomeWidget();
//Example 3
//...
Row(
children: [
Text("Example Code!"),
AwesomeWidget(),
Text("Example Footer Code!"),
],
),
//...
Now if you want to pass some values or some data to your Widget classes then you use the code you have posted above in your question.
The question is: Why would we want to send data to our widgets?
Answer: The biggest use case is when we make our list items as separate widgets. For example, in my food app, I have to show my user's order history in a ListView, so for the UI of each individual list item, I will just make a reusable Widget called OrderHistoryListItem.
In that OrderHistoryListItem, you want to show the date and time of the object. And the order id, and how much the user paid in that order or any other details, so to display this, we send this data to our Reusable Widget List Item, which displays it. Simple as that.
And that is one of the reasons why we pass values to Widgets. As a programmer, you can make use of this handy feature for more complex scenarios, be creative!

Flutter constants File with Provider package

I'm having trouble figuring out the best way to set up some constants (mainly strings). Currently I'm using a constants.dart file that just has the const variables defined in there and import it whenever it's needed. No class or anything, just a blank dart file. This works, however, I recently implemented localization using the Flutter Intl plugin in Android Studio. I got everything to work and can do something like this S.of(context).settings and it gets the translation from the correct file. My problem comes with some constant list of strings I have in my constants.dart file. I use them in many places for option selects. They look like this:
const playType = [
'RP/Story Focused',
'Battle/Combat Focused',
'Puzzles and Challenges',
'Exploration/Travel',
];
const length = [
'One Shot',
'2-5 Sessions',
'5-10 Sessions',
'On-going Campaign',
];
I cant change the the strings to the Intl reference because there is not context to be passed. Not sure how to set up a class that is loaded but not sure how to set that up and use the Provider package to serve it up.
EDIT:
heres the Constants file. Calling this with the provider is fine. The issue comes when I need to use the localization on the strings in the lists
import 'package:scryer/generated/l10n.dart';
class Constants {
Constants._();
static final instance = Constants._();
static List<String> playType = [
S.of(context).rpstoryFocused,//need a reference to a context
'Battle/Combat Focused',
'Puzzles and Challenges',
'Exploration/Travel',
];
static const length = [
'One Shot',
'2-5 Sessions',
'5-10 Sessions',
'On-going Campaign',
];
}
Heres how I call the constants on the actual page. Its a button that on press goes to a new screen that is either a multiselect checkbox list or single select radiobutton list. I pass the constants as an argument for the list
MaterialPageRoute(builder: (context) {
return MultiSelectScreen(
args: MultiSelectArguments(
label: S.of(context).selectPreferredPlayStyle,
options: playType, //this is the constants list reference
selections:
profile.playType,
),
);
})
The easy solution is to not use a constant and just create the lists in these spots, only used like twice i think, but better practice is to pull it out since its being used multiple times
you can try.
class Constants {
final BuildContext context;
Constants(#required this.context);
// static final instance = Constants._(); // to make class a singleton
static const playType = [
'RP/Story Focused',
'Battle/Combat Focused',
'Puzzles and Challenges',
'Exploration/Travel',
];
static const length = [
'One Shot',
'2-5 Sessions',
'5-10 Sessions',
'On-going Campaign',
];
}
Then, at the root of your project you should provide this class like;
void main() {
/** WidgetsFlutterBinding.ensureInitialized() is required in Flutter v1.9.4+ before using any plugins if the code is executed before runApp. */
WidgetsFlutterBinding.ensureInitialized();
runApp( Provider(
create: (context) => Constants(context),
child: MyApp(),
),
);
}
You will be able to access these constants in any BuildContext anywhere down the widget tree as follows;
final Contants constants = Provider<Constants>.of(context);
you get the length constant like; constants.length

how can i save a TextField input value and provide it to another screen in flutter?

im completely new to flutter and im facing some issues rn , i have a textfield which i input in some string , then i save the input through the TextEditingController , i next want to display the input in another screen , but what's happening in my case that everytime i change screens the TextEdditingcontroller.text value gets reset ,
full code at : https://github.com/0x-xsh/studentchat/tree/master/lib
issue at https://github.com/0x-xsh/studentchat/blob/master/lib/NewProblem.dart in LINE 142 , it prints the input value in the console but sends a blank string to the new screen. so it returns an error when https://github.com/0x-xsh/studentchat/blob/master/lib/ProblemList.dart LINE 19 executes.
i tried to do a setState on Line 142 but same issue.
I would add a List<Problem> parameter to our ProblemList class.
We can then pass in this list when navigating to our ProblemList page and access it with the following:
class ProblemList extends StatefulWidget {
final List<Problem> pList;
const ProblemList({this.pList});
#override
ProblemListState createState() => ProblemListState();
}
class ProblemListState extends State<ProblemList> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("My Problems"),
leading: Icon(Icons.list),
),
body: Text(widget.pList[0].desc), //<-------- This is where you access the list
),
);
}
}
Line 142 becomes:
onPressed: () {
Problem problem = new Problem(problemDescription.text, problemDetails.text);
problems.add(problem);
print(problems[0].desc);
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
ProblemList(pList: problems))); //<----- Passing the list to the class
},
You can't access the state of other page like you do in ProblemList.dart...
You'll need to pass the list as an argument to the ProblemList.
Try to declare a List<Problem> problems; inside the ProblemList class, add this variable to class constructor and send the list on NewProblem.dart, line 147.
Also, you code is a mess... The files have a name and the classes have another name.. Very confusing...
Always try to use the correct naming convention to your files and classes. This will help you and whoever is trying to help you :)
https://dart.dev/guides/language/effective-dart/style
When you have a better understanding of Flutter, I recommend you to learn about state management with Flutter.. There's a lot of ways. Take a look at some options and pick the one that better corresponds to your project needs...