Change color with flutter variable - flutter

there are two colors that need to be changed from the colors used in my project. These colors will change according to the theme and the theme data will be taken from the API. The problem now is that I manually give the theme to the test variable instead of the api, but the value I give to the int does not change afterwards. Whatever I give to the int at the beginning, it stays.
constant.dart:
import 'package:flutter/material.dart';
int koyuMor = 0xff410657;
int acikMor = 0xff5B336A;
int lacivert = 0xff0D1665;
int mavi = 0xff009DA4;
int koyuYesil = 0xff055511;
int acikYesil = 0xff8DA637;
int koyuTuruncu = 0xffC83232;
int acikTuruncu = 0xffDB7439;
var theme = 'ocean - theme';
int _color1 = 0;
int _color2 = 0;
void main() {
if (theme == 'thinker-theme') {
_color1 = koyuMor;
_color2 = acikMor;
}
if (theme == 'ocean-theme') {
_color1 = lacivert;
_color2 = mavi;
}
if (theme == 'forest-theme') {
_color1 = koyuYesil;
_color2 = acikYesil;
}
if (theme == 'sand-theme') {
_color1 = koyuTuruncu;
_color2 = acikYesil;
}
}
class Constant {
/// [Colors]
static Color color1 = Color(_color1);
static final Color color2 = Color(_color2);
static const Color koyuMor = Color(0x00410657);
static const Color acikMor = Color(0xff5B336A);
static const Color mavi = Color(0xff009DA4);
static const Color lacivert = Color(0xff0D1665);
static const Color koyuYesil = Color(0xff055511);
static const Color acikYesil = Color(0xff8DA637);
static const Color koyuTuruncu = Color(0xffC83232);
static const Color acikTuruncu = Color(0xffDB7439);
}
I also tried with ThemeData, it didn't seem possible to change it later.
the code i use in other pages:
color: Constant.color2,
edit: sample widget
appBar: AppBar(
backgroundColor: Constant.color1,
title: Text('Anasayfa'),
actions: [
IconButton(
icon: const Icon(Icons.notifications_none),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
Notifications()));
},
),
IconButton(
icon: const Icon(Icons.chat),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) =>
Messages()));
},
)
],
),
and
body: Column(
children: <Widget>[
// ignore: prefer_const_constructors
Container(
color: Constant.color2,
child: Column(

Related

how to save selected color using sharedpreference and set saved color as theme

i am stuck in this problem. I am new in Flutter. Help me plz. my problem is when i select color it is saved but when i want to display selected and saved color in theme. it goes wrong. Thank you in advance.
static const lightGreenVal = 0xff55efc4;
static const lightBlueVal = 0xff74b9ff;
static const lightRedVal = 0xffff7675;
List colors = [lightGreenVal, lightBlueVal, lightRedVal];
Color primaryColour = const Color(0xff55efc4);
Color getColorIndex(int index) {
switch (index) {
case 1:
return const Color(0xff55efc4);
break;
case 2:
return const Color(0xff74b9ff);
break;
case 3:
return const Color(0xffff7675);
break;
}
return const Color(0xff55efc4);
}
There are function of SharedPreference :
Future getColor() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
int index = preferences.getInt('color') ?? 1;
primaryColour = getColorIndex(index);
print("Color take from saved instant");
setState(() {});
}
Future setColor(int index) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.setInt("color", index);
}
#override
void initState() {
// TODO: implement initState
super.initState();
getColor();
}
It is selection of color and save in sharedpreference
Row(
children: [
Expanded(
child: SizedBox(
height: 200,
child: ListView.builder(
shrinkWrap: true,
itemCount: colors.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
if (colors[index] == lightGreenVal) {
primaryColour = const Color(lightGreenVal);
setColor(1);
setState(() {});
Get.back();
} else if (colors[index] == lightBlueVal) {
primaryColour = const Color(lightBlueVal);
setColor(2);
setState(() {});
Get.back();
} else {
primaryColour = const Color(lightRedVal);
setColor(3);
setState(() {});
Get.back();
}
},
child: Container(
height: 50,
width: 50,
color: Color(colors[index]),
),
);
},
),
),
),
],
)
here i want set as Theme that color i selected
GetMaterialApp(
debugShowCheckedModeBanner: false,
title: appName,
theme: ThemeData(
brightness: Brightness.light,
fontFamily: gilroyRegular,
useMaterial3: true,
colorScheme: ColorScheme.fromSwatch(backgroundColor: primaryColour),
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const ConnectionCheckpage(),
);

Field '_areas' should be initialized because its type 'List<Area>' doesn't allow null

Flutter shows error Non-nullable instance field '_areas' must be initialized.
Maybe this is because of not defining null in lists areas what when defining null Like List? _areas;
it shows an error on the index
Error: Field '_areas' should be initialized because its type 'List' doesn't allow null.
Error Line: List _areas;
Here is my code Please Help me out
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_State createState() => new _State();
}
class Area {
int index;
String name;
Color color;
Area({this.index: -1, this.name: 'Area', this.color: Colors.lightBlueAccent});
}
class _State extends State<MyApp> {
int _location = 0;
List<Area> _areas;
#override
void initState() {
//_areas = new List<Area>();
List _areas = [];
for(int i = 0; i<16; i++){
_areas.add(new Area(index: i, name: 'Area ${i}'));
}
var rng = new Random();
_location = rng.nextInt(_areas.length);
}
Widget _generate(int index){
return new GridTile(
child: new Container(
padding: new EdgeInsets.all(5.0),
child: new RaisedButton(
onPressed: () => _onPressed,
color: _areas[index].color,
child: new Text(_areas[index].name, textAlign: TextAlign.center,),
),
)
);
}
void _onPressed(int index){
setState((){
if(index == _location) {
_areas[index].color = Colors.green;
//You won
} else {
_areas[index].color = Colors.red;
}
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Grid'),
backgroundColor: Colors.deepPurpleAccent,
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new GridView.count(
crossAxisCount: 4,
children: new List<Widget>.generate(16, _generate),
)
)
),
);
}
}
I change it From ( List _areas; to List? _areas; ) but it again shows error
Remove the List declaration inside your initState method, and that should fix it.
But remember to add the nullable operator to the class property:
List<Area>? _areas;
In general, though, it is better to not use nullable lists. Instead, you can initiate the property with an empty list and just add values to it later.
List<Area> _areas = [];
#override
void initState() {
for(int i = 0; i < 16; i++) {
_areas.add(Area(index: i, name: 'Area ${i}'));
}
_location = Random().nextInt(_areas.length);
}
A more elegant way of building a list is like this:
List<Area> = List<Area>.generate(
16,
(int i) => Area(index: i, name: 'Area $i'),
);
BTW, you don't need the new keyword in Dart (Flutter).
Hello I think the problem that you declare 2 _areas you have to delete List word before the _areas inside iniState method
Please do refer this:
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_State createState() => _State();
}
class Area {
int index;
String name;
Color color;
Area(
{this.index = -1,
this.name = 'Area',
this.color = Colors.lightBlueAccent});
}
class _State extends State<MyApp> {
int _location = 0;
List<Area> _areas = [];
#override
void initState() {
//_areas = new List<Area>();
//List _areas = [];
for (int i = 0; i < 16; i++) {
print("function called");
_areas.add(Area(index: i, name: 'Area ${i}'));
print(_areas.length);
}
var rng = Random();
_location = rng.nextInt(_areas.length);
super.initState();
}
Widget _generate(int index) {
return GridTile(
child: Container(
padding: EdgeInsets.all(5.0),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: () => _onPressed(index),
child: Text(
_areas[index].name,
textAlign: TextAlign.center,
),
),
));
}
void _onPressed(int index) {
setState(() {
if (index == _location) {
_areas[index].color = Colors.green;
//You won
} else {
_areas[index].color = Colors.red;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Grid'),
backgroundColor: Colors.deepPurpleAccent,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_areas.length.toString());
},
),
body: Container(
padding: const EdgeInsets.all(32.0),
child: Center(
child: GridView.count(
crossAxisCount: 4,
children: List<Widget>.generate(16, _generate),
),
),
),
);
}
}
Please use late like this way late List<Area> _areas

Flutter Using Sqlite to display images?

In my app there is an alert dialog witch displays the rating based on some conditions, the rating is with stars image, i have a function with the conditions witch displays the rating, on another screen, i need those rating for that level that the user plays the same image that displays on the alert dialog based on the conditions to display on the other screen. for example if the user gets as rating 3 stars, than he goes to the other screen he will see the same rating there.
db_helper.dart
class Picture {
late final int? id;
late final String title;
late final Uint8List picture;
Picture(this.id, this.title, this.picture);
Picture.fromMap(Map map, this.id, this.title, this.picture) {
id = map[id];
title = map[title];
picture = map[picture];
}
Map<String, dynamic> toMap() => {
"id": id,
"title": title,
"picture" : picture,
};
}
class DatabaseHelper {
static final _databasename = "rating.db";
static final _databaseversion = 1;
static final table = "my_table";
static final columnID = 'id';
static final columnName = "ratingWithStars";
static final DatabaseHelper _databaseHelper = DatabaseHelper._();
DatabaseHelper._();
late Database db;
factory DatabaseHelper() {
return _databaseHelper;
}
Future<Database> get databse async {
if (db != null) return db;
// krijon database nese nuk ka
db = await _initDatabase();
return db;
}
_initDatabase() async {
Directory documentdirecoty = await getApplicationDocumentsDirectory();
String path = join(documentdirecoty.path, _databasename);
return await openDatabase(path,
version: _databaseversion, onCreate: _onCreate);
}
// funksion qe krijon database nese nuk ekziston
Future _onCreate(Database db, int version) async {
// sql code
await db.execute("CREATE TABLE Picture(id INTEGER PRIMARY KEY, title TEXT, picture BLOB )");
}
void savePicture(Picture picture) async {
var dbClient = await db;
await dbClient.insert("Picture", picture.toMap());
}
Future<List<Picture>> getPictures() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM Picture');
List<Picture> pictures = [];
for (int i = 0; i < list.length; i++) {
pictures.add(new Picture(list[i]["id"], list[i]["text"], list[i]["picture"]));
}
return pictures;
}
}
renditdjalet_button.dart
this is the class witch contains the function to display the rating on the alert dialog
class RenditFjaletButton extends StatefulWidget {
RenditFjaletButton(
{required this.QuizList,
required this.AllQuizLists,
required this.CurrentIndex,
Key? key})
: super(key: key);
late List AllQuizLists;
late List QuizList;
late int CurrentIndex;
#override
State<RenditFjaletButton> createState() => _RenditFjaletButtonState();
}
class _RenditFjaletButtonState extends State<RenditFjaletButton> {
late DatabaseHandler handler;
late Future<List<QuizInfo>?> futureData;
List<QuizDescription> selectReportList = [];
List<String> selectedWords = [];
List<QuizDescription> quizList = [];
int _selectedChipsIndex = 0;
String starsRating = '';
late Timer timer;
int startTimer = 65;
String starsOnTimer = '';
late QuizInfo question;
void initState() {
super.initState();
futureData = fetchData1();
startTheTimer();
this.handler = DatabaseHandler();
}
onPressed: () async {
await showDialog(
barrierDismissible: false,
context: context,
builder: (_) => AlertDialog(
backgroundColor: Color(0xFF50CFFD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(35.0),
),
),
content: Builder(
builder: (context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
String joinedWords =
selectedWords.join(" ").toString();
String setRatingInAlert(int timerForAlert) { //function for rating
double halfTimeForAlert = timerForAlert / 2;
if (joinedWords ==
data[widget.CurrentIndex].sentence &&
startTimer > halfTimeForAlert) {
starsRating = 'assets/threestars_small.png';
} else if (joinedWords ==
data[widget.CurrentIndex].sentence &&
startTimer <= 1) {
starsRating = 'assets/onestar_small.png';
} else if (joinedWords == question.sentence &&
startTimer < halfTimeForAlert) {
starsRating = 'assets/twostars_small.png';
} else {
starsRating = 'assets/zerostars_small.png';
}
return starsRating;
}
where i need to show the rating same as the one in the alert
renditfjalet_screen.dart
body: FutureBuilder<List<QuizInfo>?>(
future: futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<QuizInfo>? data = snapshot.data;
data?.sort((a, b) => a.level.compareTo(b.level));
return Stack(
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/background.PNG',
),
fit: BoxFit.cover),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GridView.count(
crossAxisCount: 4,
children: List.generate(
data!.length,
(index) {
return InkWell(
overlayColor:
MaterialStateProperty.all(Colors.green),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RenditFjaletButton(
QuizList: data[index].word,
AllQuizLists: data,
CurrentIndex: index,
),
),
);
},
child: Card(
elevation: 3.0,
margin: EdgeInsets.all(7.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
child: Column(
children: <Widget>[
Align(
alignment: Alignment.center,
child: Container(
child: Text(
'${data[index].level}',
style: GoogleFonts.fredokaOne(
textStyle: TextStyle(
fontSize: 30.0.sp,
color: Color(0xFF50CFFD),
),
),
)),
),
Container(
alignment: Alignment.center,
height: 30,
width: 65,
child: Image(
image: AssetImage('assets/threestars_small.png'), // here is where i want to show the rating, for now i just hardcoded it
),
),
],
),
),
);
},
),
),
),
),
],
You can convert an image to BASE64 and store image as a string in your database . Click there for more info

Statefull widget not changing data, how to fix that?

I have a text field which get its part of data from a function(getCurrentAssetsData), which gets data from a database(sqlite).
title: Text(this.coins[position].coin.toString() + " Temp Data " + getCurrentAssetsData(this.coins[position]).toString()),
But it showing null instead of the data.
The data is coming correctly as I am able to print statements.
My code:
class CoinList extends StatefulWidget {
#override
_CoinListState createState() => _CoinListState();
}
class _CoinListState extends State<CoinList> {
DbHelper helper = DbHelper();
List<Coin> coins;
int count=0;
#override
Widget build(BuildContext context) {
if(coins==null){
coins = List<Coin>();
getData();
}
return Scaffold(
body: coinListItems(),
floatingActionButton: FloatingActionButton(
onPressed: (){
navigateToDetail(Coin(0,''));
},
tooltip: "Add new Todo",
child: new Icon(Icons.add),
),
);
}
ListView coinListItems(){
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context,int position){
return GestureDetector(
child: SwipeDetector(
child:Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.red,
child: Text(this.coins[position].id.toString()),
),
title: Text(this.coins[position].coin.toString() + " Temp Data " + getCurrentAssetsData(this.coins[position]).toString()), //title
subtitle: Text(this.coins[position].description),
onTap: (){
//TODO:Open Coin specific orders
navigateToOrders(this.coins[position]);
},
),
),
onSwipeRight: () {
print("Swipe Right");//TODO:Delete coin code
},
),
onDoubleTap: (){
debugPrint("Tapped on "+this.coins[position].id.toString());
navigateToDetail(this.coins[position]);
},
);
},
);
}
void getData(){
final dbFuture = helper.initializeDb();
dbFuture.then((result){
final coinFuture = helper.getCoin();
coinFuture.then(
(result){
List<Coin> coins = List<Coin>();
count = result.length;
for(int i=0;i<count;i++){
coins.add(Coin.fromObject(result[i]));
debugPrint(coins[i].marketValue.toString());//title
}
setState(() {
this.coins = coins;
count = count;
});
debugPrint("Items "+count.toString());
}
);
});
}
String getCurrentAssetsData(coin){
final dbFuture = helper.initializeDb();
dbFuture.then((result){
//final coin = helper.retrieveCoin(coin_name);
final coinOrderFuture = helper.getCoinOrder(coin);
double totalCost = 0;
double totalCount = 0;
double totalCommission=0;
coinOrderFuture.then(
(result){
List<CoinOrder> coinOrders = List<CoinOrder>();
int count = result.length;
for(int i=0;i<count;i++){
coinOrders.add(CoinOrder.fromObject(result[i]));
totalCost += coinOrders[i].count * coinOrders[i].buyValue;
totalCount += coinOrders[i].count;
totalCommission+= coinOrders[i].commission;
}
//averagePrice = totalCost/totalCount;
//totalCommission = totalCommission;
//totalCost = totalCost;
String sData = "Avg: ${totalCost/totalCount} Investment: ${totalCost}";
debugPrint(sData);
return sData;
}
);
});
}
void navigateToDetail(Coin coin) async{
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context)=>CoinDetail(coin)),);
if(result==true){
getData();
}
}
void navigateToOrders(Coin coin) async{
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context)=>CoinOrderList(coin)),);
/*if(result==true){
getOrderData();
}*/
}
}
And the output:
You can see I can display the output of data in the console.
But not in the text widget.
As it is stateful widget, I thought it would reflect the data.
And that too, I am setting/calling the function while creating the text field itself.

How to change the color of one button among several buttons in Flutter?

I am new to Dart and the Flutter framework. Currently, I have a GridView populated with 25 buttons. Each button, by default, has an orange background color. However, I want to give an option to the user to long press on any button and a PopUpMenu shows up, giving them the option to pick between choosing a different color for the button. Here are the two things I have tried:
Set a global variable that changes the color. However, when I change its state, it changes the color of ALL the buttons (I only want the color of the button selected to get changed).
Pass a local variable through the instantiation of the button, and pass that variable along to the PopUpMenu. However, this does not change anything about the buttons.
How do I go about solving this problem? I am including snippets of code below to help you out. Note that this code refers to how #2 was implemented.
The 25-Button Instantiation:
// Random number generator
var _randGen = new Random();
//List of maze cards
List<Widget> mazeCards = new List();
// Generate cards until it has 25 cards within the list
while(mazeCards.length != 25)
{
// Get the index
var _currIndex = _randGen.nextInt(words.length);
// Add the card to the list
var _cardColor = Colors.orange;
mazeCards.add(createCard(words[_currIndex], _cardColor));
}
The createCard Method:
Widget createCard(String someString, Color _cardColor)
{
return GestureDetector(
onTapDown: _storePosition,
child: Container(
padding: EdgeInsets.all(8.0),
child:
_createButton(someString, _cardColor)
),
);
}
The createButton Method:
Widget _createButton(String someString, Color _cardColor)
{
Widget newButton = MaterialButton(
padding: EdgeInsets.all(50.0),
color: _cardColor,
onPressed: () => _printButtonText(someString),
onLongPress: () {
cardOptionsMenu(_cardColor);
},
textTheme: ButtonTextTheme.primary,
//_someColor(),
child: Text(someString)
);
return newButton;
}
The cardOptionsMenu Method:
void cardOptionsMenu(Color _cardColor)
{
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
showMenu(
context: context,
...
)
.then<void>((CardOptionEnum cardOption) {
if (cardOption == null) return;
else{
switch (cardOption)
{
case CardOptionEnum.makeBlackCard:
setState(() {
_cardColor = Colors.black;
});
break;
case CardOptionEnum.makeBlueCard:
setState(() {
_cardColor = Colors.blue;
});
break;
case CardOptionEnum.makeRedCard:
setState(() {
_cardColor = Colors.red;
});
break;
case CardOptionEnum.makeYellowCard:
setState(() {
_cardColor = Colors.yellow;
});
break;
case CardOptionEnum.changeWord:
break;
}
}
});
}
List<int> items = [];
List<Color> colors = [];
#override
void initState() {
super.initState();
items = List.generate(25, (ind) => ind).toList();
colors = List.generate(25, (ind) => Colors.orange).toList();
}
#override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: items.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (con, ind) {
return InkWell(
child: Card(child: Text('${items[ind]}',
style:TextStyle(color:Colors.white),
textAlign:TextAlign.center), color: colors[ind]),
onTap: () {
changeColor(ind);
});
});
}
void changeColor(index) {
showDialog(
context: context,
builder: (con) {
return AlertDialog(
title: Text('Choose a color !'),
content: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(
title: Text('Blue'),
onTap: () {
Navigator.of(con).pop();
changeState(index, Colors.blue);
}),
ListTile(
title: Text('Red'),
onTap: () {
Navigator.of(con).pop();
changeState(index, Colors.red);
}),
ListTile(
title: Text('Green'),
onTap: () {
Navigator.of(con).pop();
changeState(index, Colors.green);
})
]),
);
});
}
void changeState(index, color) {
setState(() {
colors[index] = color;
});
}