Flutter: Update text on screen when MaterialButton is clicked - flutter

I'm new to Flutter. I'm trying to build a basic dice app with a button. When the button is clicked, the displayed text gets updated with a random number.
import 'package:flutter/material.dart';
import 'dart:math';
int dice = 0;
void main() {
int dice = 0;
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
title: const Text('Quick Dice'),
backgroundColor: Colors.blueGrey,
),
body: Center(
child: MaterialButton(
onPressed: () {
rollDice();
},
child: new Text('$dice'),
),
),
),
),
);
}
void rollDice(){
dice = Random().nextInt(6) + 1;
print('In Roll Dice()');
print('$dice');
}
When the button is clicked, I can see that the function rollDice() is being called and the value of $dice is being updated but on the screen, the value never gets updated.
Is there something I'm missing? Should the child text element be refreshed somehow to to show the new value on button press?

Do like this ( StatefulWidget ) :
void main(){
runApp(MaterialApp(
home: UpdateScreen(),
));
}
class UpdateScreen extends StatefulWidget{
#override
UpdateScreenState createState() => UpdateScreenState();
}
class UpdateScreenState extends State<UpdateScreen>{
int dice = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
title: const Text('Quick Dice'),
backgroundColor: Colors.blueGrey,
),
body: Center(
child: MaterialButton(
onPressed: () {
rollDice();
},
child: new Text('$dice'),
),
),
);
}
void rollDice(){
setState(() {
dice = Random().nextInt(6) + 1;
print('In Roll Dice()');
print('$dice');
});
}
}

Try below code hope its helpful to you.
Refer Random here
and use dart.math library here
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(
home: DiceApp(),
));
}
class DiceApp extends StatefulWidget {
#override
DiceAppState createState() => DiceAppState();
}
var randomNo = new Random();
var dice = randomNo.nextInt(6) + 1;
class DiceAppState extends State<DiceApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Dice App'),
),
body: Center(
child: MaterialButton(
color: Colors.blue,
onPressed: () {
setState(() {
dice = randomNo.nextInt(6) + 1;
});
},
child: Text(
dice.toString(),
),
),
),
);
}
}
Your result screen-> |

For updating your data on screen you have to use state management like provider, Getx , block etc. Or you can use the setState method in your rollDice() function then the the widget will rebuild and your data will be updated. Something like this--
void rollDice(){
setState(() {
dice = Random().nextInt(6) + 1
});
print('In Roll Dice()');
print('$dice');
}

Related

Create button to reset the counter

I'm trying to learn flutter and my first 'APP' is a counter. The counter was working, but I would like to increment it and put a button to reset the count. Here's my code:
'''
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
theme: ThemeData(primarySwatch: Colors.purple), home: HomePage()));
}
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var count = 0;
void reset() {
count = 0;
setState(() {});
}
void increment() {
count++;
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Meu Primeiro APP!"),
),
body: Center(
child: Text(
"Contador\n$count",
textAlign: TextAlign.center,
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
increment();
},
),
);
}
}
'''
I've done searches on the internet and still haven't found the solution to this problem, which apparently is simple to solve.
First of all you need to create a new button with that functionality of resetting your counter variable. Wrap your center widget with a column and add a new button like this:
Column(
children: [
Center(
child: Text(
"Contador\n$count",
textAlign: TextAlign.center,
),
),
ElevatedButton(
child: const Text("Reset Counter"),
onPressed: () {
setState(() {
count = 0;
});
},
),
],
),
In order to see the counter updating on your screen you have to call the increment method inside of setState() so the framework schedules a rebuild!
void increment() {
setState(() {
count++;
});
}
I suggest you do some tutorials on the official flutter site to get started with the core fundamentals of flutter - happy coding! :)

how save theme or color of my flutter app

please any one help me when I close my app the theme reback to defult theme,how can I save the theme when I pick color from colorpicker library and I use hive library to save data,
if there are any another libraries to save data better than hive please tell me
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/src/block_picker.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter',
debugShowCheckedModeBanner: false,
//theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Box? box;
Color? z;
#override
void initState() {
super.initState();
openBox();
try {
getData();
} catch (e) {
print(e);
}
}
Future openBox() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('colorBox');
return;
}
void saveData(val) {
box!.put('color1', val);
}
void getData() {
setState(() {
z = Color(box!.get('color1'));
});
}
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
Color color = Colors.blue;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Counter"),
backgroundColor: z,
),
endDrawer: Drawer(
child: ListView(
children: [
ListTile(
title: Text("pick color"),
leading: Icon(Icons.color_lens),
onTap: () => showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text("select your color"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
BlockPicker(
onColorChanged: (Color value) {
saveData(value.value);
},
pickerColor: Colors.blue,
),
TextButton(
onPressed: () {
getData();
Navigator.pop(ctx);
},
child: Text("close"))
],
),
)),
),
],
),
),
body: Center(
child: Container(
width: double.infinity,
height: double.infinity,
child: TextButton(
onPressed: () {
incrementCounter();
},
child: Text(
'${counter}',),
),
),
),
);
}
}
I make code smaller as I can,and I remove all the style.
Hive should work for you,
alternatively you can use
Use the Shared Preference package and there you can store simple values as key pair values.Load that data in the init of the initial screen so that you can display the color as you need.
Step 1: Install flutter hive from https://pub.dev/packages/hive_flutter
Step 2: import 'package:hive_flutter/adapters.dart'; in your models
This class as of writing this answer contains two classes:
Color and TimeOfDay
Use hive. This is a benchmark blog that shows hive's performance capabilities: hive performance

Hi I'm new to dart and flutter I do not know why this isnt working, nothing happens when the button is pressed and I have no clue why

New to this so I have no clue whats wrong here. I need the code to add 1 to _count when the button is pressed but nothing happens when the button is pressed
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
int _count = 0;
void main() {
var app = MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
_count++;
return _count.toString();
},
),
appBar: AppBar(title: Text('Welcome')),
body: Center(
child: Text('You have pressed the button $_count times.'),
),
),
);
runApp(app);
}
To update state you need StatefulWiget to have a state with your count data, then call setState when you change your data:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _count = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState((){_count++;});
},
),
appBar: AppBar(title: Text('Welcome')),
body: Center(
child: Text('You have pressed the button $_count times.'),
),
),
);
}
}
You can fast check result copying this code to dartpad and pressing run.
It will be good start for you if you check this page, knowing what is state in flutter.

Flutter Randomizing - How to prevent from displaying the previous element shown

Upon clicking, my app shows either yes, no, or maybe. How do I set the subsequent result strictly different from the previous one? For example, the current result is 'no', how do I randomize and make sure that the next result would ONLY either be 'yes' or 'maybe'?
This is the code
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
),
);
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'Ask Me Anything',
style: TextStyle(fontFamily: 'Lobster', fontSize: 25),
),
),
body: picker(),
),
);
}
}
class picker extends StatefulWidget {
#override
_pickerState createState() => _pickerState();
}
class _pickerState extends State<picker> {
List yourList = ["Yes", "No", "Maybe"];
int randomIndex;
_pickerState() {
randomIndex = Random().nextInt(yourList.length);
}
#override
Widget build(BuildContext context) {
return Center(
child: TextButton(
onPressed: () {
setState(() {
randomIndex = Random().nextInt(yourList.length);
print("What's showing is '${yourList[randomIndex]}'");
});
},
child: Stack(
children: <Widget>[
Center(child: Image.asset('images/blu.png')),
Center(
child: Text(
yourList[randomIndex],
style: TextStyle(fontSize: 40, fontFamily: 'Lobster'),
),
),
],
),
),
);
}
}
You could just do a while loop which keeps trying for a new answer as long as the answer is equal to the current answer:
_pickerState() {
oldIndex = randomIndex;
randomIndex = Random().nextInt(yourList.length);
while (oldIndex == randomIndex){
randomIndex = Random().nextInt(yourList.length);
}
And then in your onPressed:
setState(() {
randomIndex = _pickerState();
print("What's showing is '${yourList[randomIndex]}'");
});

setState function not updating image under stateful widget

I was trying to build Dice Game in which if users click the image should be changed from the asset folder but the image is not changing but the value in the terminal is updating setState Method is not working properly maybe
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: Center(child: Text('Dicee')),
backgroundColor: Colors.red,
),
body: DicePage(),
),
),
);
}
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
#override
Widget build(BuildContext context) {
int leftDiceNumber = 5;
int rightDiceNumber = 2;
return Center(
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: (){
setState(() {
leftDiceNumber = Random().nextInt(6) + 1;
print('$leftDiceNumber');
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: FlatButton(
onPressed: (){
setState(() {
rightDiceNumber = Random().nextInt(6) + 1;
print('$rightDiceNumber');
});
},
child: Image.asset('images/dice$rightDiceNumber.png'),
),
),
],
),
);
}
}
it should show the updated images
You need to move your variables outside of the build method. They are being reset on each build.
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: Center(child: Text('Dicee')),
backgroundColor: Colors.red,
),
body: DicePage(),
),
),
);
}
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNumber = 5;
int rightDiceNumber = 2;
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: (){
setState(() {
leftDiceNumber = Random().nextInt(6) + 1;
print('$leftDiceNumber');
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: FlatButton(
onPressed: (){
setState(() {
rightDiceNumber = Random().nextInt(6) + 1;
print('$rightDiceNumber');
});
},
child: Image.asset('images/dice$rightDiceNumber.png'),
),
),
],
),
);
}
}