Add more counter rows in flutter - flutter

I wrote this code that represents a row counter and I need to know how to add more rows for more actions/activities like the below picture.
If possible don't change the code too much since I need to show and explain this to my classmate.
class CounterApplication extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: '¡Contador de Propósitos!',
home: CounterScreenState(),
);
}
}
class CounterScreenState extends StatefulWidget {
#override
CounterScreen createState() => CounterScreen();
}
class CounterScreen extends State<CounterScreenState>{
// Contador_1
int _count1 = 0;
void _incrementCount1() {
setState(() {
_count1++;
});
}
void _decrementCount1() {
if(_count1 < 1) {
return;
}
setState(() {
_count1--;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('¡Contador de Propósitos!'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount1,
),
Text("Caminatas:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount1,
)
],
),
),
);
}
}
The example that I need]:

check out this one
class CounterApplication extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: '¡Contador de Propósitos!',
home: CounterScreenState(),
);
}
}
class CounterScreenState extends StatefulWidget {
#override
CounterScreen createState() => CounterScreen();
}
class CounterScreen extends State<CounterScreenState> {
final int counterCount = 5;
final List<int> _counters = [];
void _incrementCount(int index) {
setState(() {
_counters[index]++;
});
}
void _decrementCount(int index) {
if (_counters[index] < 1) {
return;
}
setState(() {
_counters[index]--;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('¡Contador de Propósitos!'),
),
body: Center(
child: Column(
children: [
const SizedBox(height: 10),
for (int i = 0; i < counterCount; i++)
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: const Icon(Icons.remove),
onPressed: () => _decrementCount(i),
),
Text("Caminatas: ${_counters[i]}"),
FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => _incrementCount(i),
)
],
),
],
),
),
);
}
}

Wrap the Row with Column widget and add more Rows to display other elements
class CounterApplication extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: '¡Contador de Propósitos!',
home: CounterScreenState(),
);
}
}
class CounterScreenState extends StatefulWidget {
#override
CounterScreen createState() => CounterScreen();
}
class CounterScreen extends State<CounterScreenState>{
// Contador_1
int _count1 = 0;
// Libros_1
int _count2 = 0;
void _incrementCount1() {
setState(() {
_count1++;
});
}
void _decrementCount1() {
if(_count1 < 1) {
return;
}
setState(() {
_count1--;
});
}
void _incrementCount2() {
setState(() {
_count2++;
});
}
void _decrementCount2() {
if(_count2 < 1) {
return;
}
setState(() {
_count2--;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('¡Contador de Propósitos!'),
),
body: Center(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount1,
),
Text("Caminatas:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount1,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount2,
),
Text("Libros:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount2,
)
],
),
],
),
),
);
}
}

import 'package:flutter/material.dart';
void main() {
runApp(CounterApplication());
}
class CounterApplication extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: '¡Contador de Propósitos!',
home: CounterScreenState(),
);
}
}
class CounterScreenState extends StatefulWidget {
#override
CounterScreen createState() => CounterScreen();
}
class CounterScreen extends State<CounterScreenState>{
/// change data as per requirment
List<Counter> counterData= [
Counter('Data 1',0),
Counter('Data 2',0),
Counter('Data 3',0),
Counter('Data 4',0),
Counter('Data 5',0),
Counter('Data 6',0),
];
/// for increment and decrement
/// first get current counter using index then change as per need
void _incrementCount1(int index) {
setState(() {
Counter currentCounter = counterData[index];
currentCounter.count++;
});
}
void _decrementCount1(int index) {
Counter currentCounter = counterData[index];
if(currentCounter.count < 1) {
return;
}
setState(() {
currentCounter.count--;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('¡Contador de Propósitos!'),
),
body: Center(
/// here we use listview.builder()
// to make widgets as per data in list
child: ListView.builder(
itemCount: counterData.length,
itemBuilder: (_,index) => Padding(
// gave padding to give space
padding:const EdgeInsets.symmetric(vertical: 10.0),
child:Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child:const Icon(Icons.remove),
/// made change as index is needed
onPressed:(){ _decrementCount1(index);},
),
Text(counterData[index].name),
Text("${counterData[index].count}"),
FloatingActionButton(
child:const Icon(Icons.add),
onPressed: (){ _incrementCount1(index);},
)
],
),
),
)
),
);
}
}
class Counter{
String name;
int count;
Counter(this.name,this.count);
}

return Scaffold(
appBar: AppBar(
title: const Text('¡Contador de Propósitos!'),
),
body: Container (
child: ListView(
padding: EdgeInsets.all(20),
children: <Widget> [
mainAxisAlignment: MainAxisAlignment.spaceAround,
Center (
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount1,
),
Text("Caminatas:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount1,
),
],
),
Center (
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount1,
),
Text("Caminatas:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount1,
),
],
),
Center (
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: _decrementCount1,
),
Text("Caminatas:"),
Text("${_count1}"),
FloatingActionButton(
child:Icon(Icons.add),
onPressed: _incrementCount1,
),
],
),
),
],
),
);

Related

setState((){}); is not updating Android Emulator

I have a question about updating Android Emulator after pressing on an icon using setState()
this is my code:
import 'package:flutter/material.dart';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: 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 = 1;
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
setState(() {
leftDiceNumber = 5;
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
print('Right button got pressed.');
},
child: Image.asset('images/dice2.png'),
),
),
],
),
);
}
}
and I tried even multiple choices that I found in Stackoverflow , but nothing it's working...
this.setState(() {
leftDiceNumber = 5;
});
WidgetsBinding.instance.addPostFrameCallback((_) => setState(...));
insted of just setState() and didn't work
I want to change the value of leftDiceNumber = 5 when I click on the picture
the initialised value for leftDiceNumber is 1
Put the variable outside the build method.leftDiceNumber, else it will reset on every build.
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNumber = 1; //here
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
setState(() {
leftDiceNumber = 5;
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
print('Right button got pressed.');
},
child: Image.asset('images/dice2.png'),
),
),
],
),
);
}
}

How can i call a class from a Floating Button onpressed

I've been trying to use a floating action button in order to execute a class but I've been trying everything and failing. Here's my code:
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
centerTitle: true,
title: Text('Dices'),
backgroundColor: Colors.teal,
),
body: DicePage(),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add), onPressed: () {}),
),
),
);
}
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNum = 1;
int rightDiceNum = 1;
void diceRandomizer() {
setState(() {
leftDiceNum = Random().nextInt(6) + 1;
rightDiceNum = Random().nextInt(6) + 1;
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$leftDiceNum.png'),
),
),
Expanded(
child: FlatButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$rightDiceNum.png'),
),
),
],
),
);
}
}
now the code is a simple dice app where if i press on the images the function DiceRandomizer activates and it randomly gives a number from 1..6. then the image gets presented. But i wanna do just that with the floating action button.
As far as I know it's because the class is undefined, and try fix your code
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(home: DicePage()),
);
}
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNum = 1;
int rightDiceNum = 1;
diceRandomizer() {
setState(() {
leftDiceNum = Random().nextInt(6) + 1;
rightDiceNum = Random().nextInt(6) + 1;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
centerTitle: true,
title: Text('Dices'),
backgroundColor: Colors.teal),
body: Center(
child: Row(
children: <Widget>[
Expanded(
child: TextButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$leftDiceNum.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$rightDiceNum.png'),
),
),
],
),
),
floatingActionButton: Row(
children: [
FloatingActionButton(
onPressed: () {diceRandomizer();},
),
FloatingActionButton(
onPressed: (){diceRandomizer();},
)
],
),
);
}
}
Note
I make 2 FloatingActionButton
FlatButton isdeprecated and must migrate to TextButton
Try that and see the result, if error you can comment and i will help you.

In Flutter I want to be able to display the text I wrote last time and add text to it

in flutter,I'm currently working on a feature to edit lists.
I want to be able to display the last text I wrote and add text to it.
But I get an error like the one below.
I don't know how to do this anymore, so I would appreciate any advice on how to write it.
I'm sorry, but I don't understand English, and there are a few places where it's written in Japanese. answers don't have to be in Japanese.
This is my first question.
enter code here
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() {
// 最初に表示するWidget
runApp(Myenter code hereApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
// 右上に表示される"debug"ラベルを消す
debugShowCheckedModeBanner: false,
// アプリ名
title: 'My Todo App',
theme: ThemeData(
// テーマカラー
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
// リスト一覧画面を表示
home: TodoListPage(),
);
}
}
// リスト一覧画面用Widget
class TodoListPage extends StatefulWidget {
#override
_TodoListPageState createState() => _TodoListPageState();
}
class _TodoListPageState extends State<TodoListPage> {
// Todoリストのデータ
List<String> todoList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
// AppBarを表示し、タイトルも設定
appBar: AppBar(
title: Text('リスト一覧'),
),
// データを元にListViewを作成
body: ListView.builder(
itemCount: todoList.length,
itemBuilder: (context, index) {
return CupertinoContextMenu(
child: Card(
child: ListTile(
title: Text(todoList[index]),
),
),
actions: <Widget>[
CupertinoContextMenuAction(
child: const Text('Delete'),
//押されたら...
onPressed: () {
setState(() {});
//listの一つを削除
todoList.removeAt(index);
//そして、popで前の画面に戻る
Navigator.pop(context);
},
),
CupertinoContextMenuAction(
child: const Text('To edit'),
onPressed: () async {
var morenewText = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => TodoAddPage(todoList[index]),
),
);
setState(() {
todoList[index] = morenewText;
});
},
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// "push"で新規画面に遷移
// リスト追加画面から渡される値を受け取る
var newListText = await Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
// 遷移先の画面としてリスト追加画面を指定
return TodoAddPage(null);
}),
);
if (newListText != null) {
// キャンセルした場合は newListText が null となるので注意
setState(() {
// リスト追加
todoList.add(newListText);
});
}
},
child: Icon(Icons.add),
),
);
}
}
class TodoAddPage extends StatefulWidget {
dynamic oldnama;
TodoAddPage(this.oldnama);
#override
_TodoAddPageState createState() => _TodoAddPageState();
}
class _TodoAddPageState extends State<TodoAddPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('リスト追加'),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 入力されたテキストを表示
Text(widget.oldnama, style: TextStyle(color: Colors.blue)),
const SizedBox(height: 8),
// テキスト入力
TextField(
// 入力されたテキストの値を受け取る(valueが入力されたテキスト)
onChanged: (String value) {
// データが変更したことを知らせる(画面を更新する)
setState(() {
// データを変更
widget.oldnama = value;
});
},
),
const SizedBox(height: 8),
Container(
// 横幅いっぱいに広げる
width: double.infinity,
// リスト追加ボタン
child: ElevatedButton(
onPressed: () {
// "pop"で前の画面に戻る
// "pop"の引数から前の画面にデータを渡す
Navigator.of(context).pop(widget.oldnama);
},
child: Text('Add list', style: TextStyle(color: Colors.white)),
),
),
const SizedBox(height: 8),
Container(
// 横幅いっぱいに広げる
width: double.infinity,
// キャンセルボタン
child: TextButton(
// ボタンをクリックした時の処理
onPressed: () {
// "pop"で前の画面に戻る
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
),
],
),
),
);
}
}
You cant directly modify the widget entry variables
TextField(
// 入力されたテキストの値を受け取る(valueが入力されたテキスト)
onChanged: (String value) {
// データが変更したことを知らせる(画面を更新する)
setState(() {
// データを変更
widget.oldnama = value;
});
},
),
create another variable in state class like
var textValue = user.name;
use textFormField
TextFormField(
initValue: textValue,
onChanged: (value){
setState( () {
textValue = value;
});
},
)
or something like this, the important thing is that you cant do widget.oldnama = value
You can copy paste run full code below
Reason: null value cause Text widget has excepiton, you can change from
Text(widget.oldnama, style: TextStyle(color: Colors.blue)),
to
widget.oldnama == null
? Text("empty")
: Text("${widget.oldnama}",
style: TextStyle(color: Colors.blue)),
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() {
// 最初に表示するWidget
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
// 右上に表示される"debug"ラベルを消す
debugShowCheckedModeBanner: false,
// アプリ名
title: 'My Todo App',
theme: ThemeData(
// テーマカラー
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
// リスト一覧画面を表示
home: TodoListPage(),
);
}
}
// リスト一覧画面用Widget
class TodoListPage extends StatefulWidget {
#override
_TodoListPageState createState() => _TodoListPageState();
}
class _TodoListPageState extends State<TodoListPage> {
// Todoリストのデータ
List<String> todoList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
// AppBarを表示し、タイトルも設定
appBar: AppBar(
title: Text('リスト一覧'),
),
// データを元にListViewを作成
body: ListView.builder(
itemCount: todoList.length,
itemBuilder: (context, index) {
return CupertinoContextMenu(
child: Card(
child: ListTile(
title: Text(todoList[index]),
),
),
actions: <Widget>[
CupertinoContextMenuAction(
child: const Text('Delete'),
//押されたら...
onPressed: () {
setState(() {});
//listの一つを削除
todoList.removeAt(index);
//そして、popで前の画面に戻る
Navigator.pop(context);
},
),
CupertinoContextMenuAction(
child: const Text('To edit'),
onPressed: () async {
var morenewText = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => TodoAddPage(todoList[index]),
),
);
setState(() {
todoList[index] = morenewText;
});
},
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// "push"で新規画面に遷移
// リスト追加画面から渡される値を受け取る
var newListText = await Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
// 遷移先の画面としてリスト追加画面を指定
return TodoAddPage(null);
}),
);
if (newListText != null) {
// キャンセルした場合は newListText が null となるので注意
setState(() {
// リスト追加
todoList.add(newListText);
});
}
},
child: Icon(Icons.add),
),
);
}
}
class TodoAddPage extends StatefulWidget {
dynamic oldnama;
TodoAddPage(this.oldnama);
#override
_TodoAddPageState createState() => _TodoAddPageState();
}
class _TodoAddPageState extends State<TodoAddPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('リスト追加'),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 入力されたテキストを表示
widget.oldnama == null
? Text("empty")
: Text("${widget.oldnama}",
style: TextStyle(color: Colors.blue)),
const SizedBox(height: 8),
// テキスト入力
TextField(
// 入力されたテキストの値を受け取る(valueが入力されたテキスト)
onChanged: (String value) {
// データが変更したことを知らせる(画面を更新する)
setState(() {
// データを変更
widget.oldnama = value;
});
},
),
const SizedBox(height: 8),
Container(
// 横幅いっぱいに広げる
width: double.infinity,
// リスト追加ボタン
child: ElevatedButton(
onPressed: () {
// "pop"で前の画面に戻る
// "pop"の引数から前の画面にデータを渡す
Navigator.of(context).pop(widget.oldnama);
},
child: Text('Add list', style: TextStyle(color: Colors.white)),
),
),
const SizedBox(height: 8),
Container(
// 横幅いっぱいに広げる
width: double.infinity,
// キャンセルボタン
child: TextButton(
// ボタンをクリックした時の処理
onPressed: () {
// "pop"で前の画面に戻る
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
),
],
),
),
);
}
}

Can someone check my Dart code and tell me where I'm making mistake in returning data from my screen as a ListView

I am stuck here for the past 20 days in returning data in my app from the other screen. I'm new to programming and need help. I've been searching through all the internet to find an answer related to my query but nothing is helping though. I ask my fellow SO guys to please help.
You can look at the entire code which I've made open here.
My code:
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
final newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {
return ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index){
return Container(
child: Text('item: $newList'),
);
},
);
});
},
)
],
),
);
}
}
The screen where Navigator.pop() is used:
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text(nameOfSite[index]),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}
Here is the SecondPage and FavoriteList that I made
import 'package:flutter/material.dart';
import 'package:aioapp2/lists.dart';
Set<int> favorites = {};
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: <Widget>[
_getFavoriteList(),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: FloatingActionButton(
child: Icon(
Icons.edit,
color: Colors.blue,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditFavorites(),
),
).then((updatedFavorites) {
if (updatedFavorites != null)
setState(() {
favorites = updatedFavorites;
});
});
},
),
),
)
],
);
}
Widget _getFavoriteList() {
if (favorites?.isNotEmpty == true)
return _FavoriteList();
else
return _EmptyFavoriteList();
}
}
class _EmptyFavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Add Your Favorite Sites Here!❤',
style: TextStyle(color: Colors.white),
),
Icon(
Icons.favorite,
size: 150,
color: Colors.blue[100],
),
],
),
),
),
),
],
);
}
}
class _FavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: favorites.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[favorites.elementAt(index)]),
);
},
);
}
}
//Its FavoriteList Page. I changed the name
class EditFavorites extends StatefulWidget {
#override
_EditFavoritesState createState() => _EditFavoritesState();
}
class _EditFavoritesState extends State<EditFavorites> {
final _editableFavorites = <int>{};
#override
void initState() {
_editableFavorites.addAll(favorites);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red,
actions: <Widget>[
IconButton(
icon: Icon(Icons.done),
onPressed: () {
Navigator.pop<Set>(context, _editableFavorites);
},
)
],
),
//backgroundColor: Colors.indigo,
body: SafeArea(
child: ListView.builder(
itemCount: nameOfSite.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[index]),
trailing: IconButton(
icon: _editableFavorites.contains(index)
? Icon(
Icons.favorite,
color: Colors.red,
)
: Icon(
Icons.favorite_border,
color: Colors.grey,
),
onPressed: () {
setState(() {
if (_editableFavorites.contains(index))
_editableFavorites.remove(index);
else
_editableFavorites.add(index);
});
},
),
);
},
),
),
);
}
}
Just replace secondtab.dart with this code.
You can copy paste run full code below
You have to move out return ListView to the same layer with FloatingActionButton
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SecondPage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
Set newList = {};
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index) {
return Container(
child: Text('item: ${newList.elementAt(index)}'),
);
},
),
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {});
},
)
],
),
);
}
}
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
//Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text('nameOfSite[index]'),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}

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'),
),
),
],
),
);
}
}