Alert box with multi select chip in flutter - flutter

I have a multiselect chip in my app , but when since the data in the AlertDialog depends dynamically, it will be 1 or 100, so I have added SingleChildScrollView over the alert Dialog to give scrolling if there are more entries , but when I added SingleChildScrollView my alert box goes to top of the screen like this, I want it to align in center,
If I removed the SingleChildScrollView then It will come like this which I wanted. but If there are lot of entries I cant select because It cant cover the entire data?
Is there any way where I can align it to center of screen with scroll enabled?
Thanks
showDialog(
context: context,
builder: (BuildContext context) {
return SingleChildScrollView(
child: AlertDialog(
title: Text("choose items"),
content: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
listSelectedItem = selectedList;
});
},
),
actions: <Widget>[
FlatButton(
child: Text("CANCEL"),
onPressed: () {
setState(() {
dropdownSelected = null;
listSelectedItem.clear();
});
Navigator.of(context).pop();
}),

In AlertDialog's content use Container and constraints, and in Container's child wrap SingleChildScrollView then wrap MultiSelectChip
code snippet
return AlertDialog(
title: Text("Report Video"),
content: Container(
constraints: BoxConstraints(
maxHeight: 100.0,
),
child: SingleChildScrollView(
child: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
selectedReportList = selectedList;
});
},
),
),
),
actions: <Widget>[
FlatButton(
child: Text("Report"),
onPressed: () => Navigator.of(context).pop(),
)
],
);
})
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> reportList = [
"Not relevant",
"Illegal",
"Spam",
"Offensive",
"Uncivil",
"a123",
"b234",
"c2314",
"aaaa",
"a",
"1Not relevant",
"2Illegal",
"3Spam",
"4Offensive",
"5Uncivil",
"6a123",
"7b234",
"8c2314",
"9aaaa",
"0a",
"Not relevant",
"Illegal",
"Spam",
"Offensive",
"Uncivil",
"a123",
"b234",
"c2314",
"aaaa",
"a",
"1Not relevant",
"2Illegal",
"3Spam",
"4Offensive",
"5Uncivil",
"6a123",
"7b234",
"8c2314",
"9aaaa",
"0a",
];
List<String> selectedReportList = List();
_showReportDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
//Here we will build the content of the dialog
return AlertDialog(
title: Text("Report Video"),
content: Container(
constraints: BoxConstraints(
maxHeight: 100.0,
),
child: SingleChildScrollView(
child: MultiSelectChip(
reportList,
onSelectionChanged: (selectedList) {
setState(() {
selectedReportList = selectedList;
});
},
),
),
),
actions: <Widget>[
FlatButton(
child: Text("Report"),
onPressed: () => Navigator.of(context).pop(),
)
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("Report"),
onPressed: () => _showReportDialog(),
),
Text(selectedReportList.join(" , ")),
],
),
),
);
}
}
class MultiSelectChip extends StatefulWidget {
final List<String> reportList;
final Function(List<String>) onSelectionChanged;
MultiSelectChip(this.reportList, {this.onSelectionChanged});
#override
_MultiSelectChipState createState() => _MultiSelectChipState();
}
class _MultiSelectChipState extends State<MultiSelectChip> {
// String selectedChoice = "";
List<String> selectedChoices = List();
_buildChoiceList() {
List<Widget> choices = List();
widget.reportList.forEach((item) {
choices.add(Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
selected: selectedChoices.contains(item),
onSelected: (selected) {
setState(() {
selectedChoices.contains(item)
? selectedChoices.remove(item)
: selectedChoices.add(item);
widget.onSelectionChanged(selectedChoices);
});
},
),
));
});
return choices;
}
#override
Widget build(BuildContext context) {
return Wrap(
children: _buildChoiceList(),
);
}
}

Related

Unable to navigate from GetX Dialog to another screen

I have follow dialog box. When I click 'Next' I want it to navigate to GamePage() screen. But unfortunately it doesn't work.
Following is the GamePage Widget
class GamePage extends StatelessWidget {
final homeCtrl = Get.find<HomeController>();
GamePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF8fb1ca),
body: SafeArea(
child: ListView(
children: [
Padding(
padding: EdgeInsets.all(3.0.wp),
child: Row(
children: [
IconButton(
onPressed: () {
Get.back();
},
icon: const Icon(Icons.arrow_back),
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0.wp),
child: Column(
children: [
SizedBox(
height: 2.0.wp,
),
Center(
child: Text(
'What ${homeCtrl.currentWord.first.wordtype} is this?',
style: TextStyle(
fontSize: 18.0.sp,
color: Colors.grey[800],
),
),
),
SizedBox(height: 10.0.wp),
WordsWidget(currentWord: homeCtrl.currentWord.first),
],
),
),
],
),
),
);
}
}
Following is the Word Widget being called from GamePage Widget
class WordsWidget extends StatelessWidget {
final currentWord;
WordsWidget({Key? key, this.currentWord}) : super(key: key);
final homeCtrl = Get.find<HomeController>();
#override
Widget build(BuildContext context) {
// var currentWord = homeCtrl.nextWord();
var shuffleword = [].obs;
shuffleword.addAll(homeCtrl.shuffleWord(currentWord.word));
TextToSpeech tts = TextToSpeech();
String language = 'en-US';
tts.setLanguage(language);
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
print('pressed here');
Get.defaultDialog(
title: 'Go to next page',
content: Container(
child: Column(
children: [
Text('You are about to move to another screen'),
ElevatedButton.icon(
onPressed: () {
Get.to(() => GamePage());
},
icon: Icon(
Icons.arrow_right,
),
label: Text('Go'))
],
),
));
},
child: Text('Open Dialog')),
],
);
}
}
Get.back() is working but not Get.to
Try
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return const GamePage();
},
),
);
},
child: Text("Next Word"),
)
Try this code -
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_memory/next_page.dart';
import 'package:image_picker/image_picker.dart';
void main() {
//check getMaterialApp is used
runApp(const GetMaterialApp(
title: 'Temp',
home: const MyApp(),
));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Image Picker'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
print('pressed here');
Get.defaultDialog(
title: 'Go to next page',
content: Container(
child: Column(
children: [
Text('You are about to move to another screen'),
ElevatedButton.icon(
onPressed: () {
Get.to(() => NextPage());
},
icon: Icon(
Icons.arrow_right,
),
label: Text('Go'))
],
),
));
},
child: Text('Open Dialog')),
),
);
}
}
and next page is -
import 'package:flutter/material.dart';
class NextPage extends StatefulWidget {
const NextPage({ Key? key }) : super(key: key);
#override
State<NextPage> createState() => _NextPageState();
}
class _NextPageState extends State<NextPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Next Page'),
),
body: Container(
child: Center(
child: Text("this is next page"),
),
),
);
}
}
And yes, you need to insure that you are using 'GetMaterialApp'.
If you want to use GetX navigation system, you should wrap your application in a GetMaterialApp instead of MaterialApp.
So in your main use this:
class GetxApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GetMaterialApp(
home: HomePage(),
);
}
}
Instead of this:
class NormalApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

AlertDialog with a CheckboxListTile in flutter

I'm having some problems when I use a CheckboxListTile inside a AlertDialog. The problem is that when I try to check, the box doesn't work correctly. This is my code:
import 'package:flutter/material.dart';
void main() {
runApp(PadelApp());
}
class PadelApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false, //esto es para quitar el cartelito de debug
title: 'Test',
theme: ThemeData( primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget{
//#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
var _formkey = GlobalKey<FormState>();
var _lstgrupos = ['Group 1', 'Group 2'];
List<String> _SelectedGroupsItems = [];
String _SelectedGroups = 'Groups';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Test')),
body: Form(
key: _formkey,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: ListTile(
title: Text(_SelectedGroups),
onTap: () => showDialog(
context: context,
barrierDismissible: true,
builder: (context) {
return AlertDialog(
title: Text("Choose a group"),
content: SingleChildScrollView(
child: Container(
width: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.min,
children: _lstgrupos.map((lst) => CheckboxListTile(
title: Text(lst),
value:_SelectedGroupsItems.contains(lst),
onChanged: (value) {
setState(() {
if (value!) {
if (!_SelectedGroupsItems.contains(lst)) {
_SelectedGroupsItems.add(lst);
}
} else {
if (_SelectedGroupsItems.contains(lst)) {
_SelectedGroupsItems.add(lst);
}
}
});
},
)).toList(),
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cerrar'),
onPressed: ()=> Navigator.of(context).pop(),
)
]
);
}
),
),
),
],
),
],
),
),
),
);
}
}
I have tried to modify in several ways but I realize that the problem is in "value" variable (in onChanged: (value)). This variable is always true or always false but doesn't change.
You need surround your AlertDialog with StatefullBuilder
Otherwise the setState does not rebuild the dialog
Like this :
StatefulBuilder(
builder: (context, setState) {
return AlertDialog(...)
})

Why is Navigator.pop failing to pass a parameter back?

I'm launching an alert dialog to confirm a user's action of saving or clearing a filter, and I want to return a boolean based on their selection. I'm trying to pass it through Navigator.pop() but keep getting this error:
The following _TypeError was thrown while handling a gesture:
type 'bool' is not a subtype of type 'AlertDialog' of 'result'
Anyone know why this is happening? Here is my code. The specific error is happening in the onPressed where I assign the result of showDialog to a var shouldClear.
import 'package:flutter/material.dart';
class FilterNavbar extends StatelessWidget {
final VoidCallback clearFilter;
const FilterNavbar({#required this.clearFilter});
#override
Widget build(BuildContext context) {
return Container(
height: 60,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * .3,
child: RaisedButton(
onPressed: () async {
var shouldClear = await showDialog<AlertDialog>(
context: context,
builder: (context) {
return generateDialog(context, attemptSave: false);
}
);
},
child: const Text("Clear"),
),
),
Container(
width: MediaQuery.of(context).size.width * .3,
child: RaisedButton(
onPressed: () async {
await showDialog<AlertDialog>(
context: context,
builder: (context) {
return generateDialog(context, attemptSave: true);
}
);
Navigator.pop(context, true);
},
child: const Text("Save"),
),
)
]
),
);
}
}
AlertDialog generateDialog(BuildContext context, {bool attemptSave}){
return AlertDialog(
title: Center(child: Text("${attemptSave ? "Save": "Clear"} filter?")),
actions: [
FlatButton(
onPressed: () {
if (attemptSave) {
Navigator.pop(context, false);
}
else {
Navigator.pop(context, true);
}
},
child: Text("${attemptSave ? "Save": "Clear"}")
)
],
);
}
You can copy paste run full code below
Please change AlertDialog to bool
From
await showDialog<AlertDialog>
to
await showDialog<bool>
working demo
full code
import 'package:flutter/material.dart';
class FilterNavbar extends StatelessWidget {
final VoidCallback clearFilter;
const FilterNavbar({#required this.clearFilter});
#override
Widget build(BuildContext context) {
return Container(
height: 60,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * .3,
child: RaisedButton(
onPressed: () async {
var shouldClear = await showDialog<bool>(
context: context,
builder: (context) {
return generateDialog(context, attemptSave: false);
});
},
child: const Text("Clear"),
),
),
Container(
width: MediaQuery.of(context).size.width * .3,
child: RaisedButton(
onPressed: () async {
await showDialog<bool>(
context: context,
builder: (context) {
return generateDialog(context, attemptSave: true);
});
Navigator.pop(context, true);
},
child: const Text("Save"),
),
)
]),
);
}
}
AlertDialog generateDialog(BuildContext context, {bool attemptSave}) {
return AlertDialog(
title: Center(child: Text("${attemptSave ? "Save" : "Clear"} filter?")),
actions: [
FlatButton(
onPressed: () {
if (attemptSave) {
Navigator.pop(context, false);
} else {
Navigator.pop(context, true);
}
},
child: Text("${attemptSave ? "Save" : "Clear"}"))
],
);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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>[
Expanded(
child: FilterNavbar(
clearFilter: () {},
)),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Collect user input data - flutter

I want to collect input data from the user and record it in a certain page. You will see what my program does (full code down below). But the code below, is having two problems.
first problem: The Data in the HistoryPage class is not getting stored correctly. For example when I press A then type 50, The HistoryPage will store it as 'Subtracted 50 on A (and the date)'. But when I enter a second input, such as 30 on B, the Page will show 'Subtracted 30 on A', 'Subtracted 30 on B'. Thus, the Value of A also changes.
Second problem:
count++;
print(count);
historyList.add(History(data: text.data, dateTime: DateTime.now()));
This part of the code is not working. I tried to make 'text' a global variable. But I cannot change the constructor in the class Tile with a global variable.
full code:
import 'package:flutter/material.dart';
import './globals.dart' as globals;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HistoryPage()),
);
},
child: Text(value.toString()),
),
FlatButton(
child: Center(child: Text("Spent")),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type()),
);
},
)
],
));
}
}
class Spent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Tile(
text: Text(
"A",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"B",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"C",
style: TextStyle(fontSize: 20.0),
),
),
]))));
}
}
class Tile extends StatelessWidget {
final Text text;
Tile({this.text});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type()),
);
},
child: text,
);
}
}
class Type extends StatefulWidget {
#override
TypeState createState() => TypeState();
}
class TypeState extends State<Type> {
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
keyboardType: TextInputType.number),
FlatButton(
child: Text("Subract"),
onPressed: () {
if (int.tryParse(_controller.text) == null) return;
globals.enteredValue = int.parse(_controller.text);
setState(() {
value -= globals.enteredValue;
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
count++;
print(count);
historyList.add(History(data: text.data, dateTime: DateTime.now()));
},
),
])),
));
}
}
int value = 0;
int count = 0;
List<History> historyList = [];
class History {
String data;
DateTime dateTime;
History({
this.data,
this.dateTime,
});
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}),
),
body: Container(
child: ListView.builder(
itemCount: historyList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
' Subtracted ${globals.enteredValue} on ${historyList[index].data} ${historyList[index].dateTime.toString()}'),
);
},
),
));
}
}
globals.dart
library numbers.globals;
int enteredValue = 0;
You can copy paste run full code below
Step 1: class History add enteredValue attribute
class History {
int enteredValue;
Step 2: historyList.add need enteredValue
historyList.add(History(
enteredValue: int.parse(_controller.text),
Step 3: class Type need final Text text;
class Type extends StatefulWidget {
final Text text;
Type({this.text});
Step 4: MaterialPageRoute(builder: (context) => Type(text: text)),
working demo
full code
import 'package:flutter/material.dart';
import './globals.dart' as globals;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HistoryPage()),
);
},
child: Text(value.toString()),
),
FlatButton(
child: Center(child: Text("Spent")),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Spent()),
);
},
)
],
));
}
}
class Spent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Tile(
text: Text(
"A",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"B",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"C",
style: TextStyle(fontSize: 20.0),
),
),
]))));
}
}
class Tile extends StatelessWidget {
final Text text;
Tile({this.text});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type(text: text)),
);
},
child: text,
);
}
}
class Type extends StatefulWidget {
final Text text;
Type({this.text});
#override
TypeState createState() => TypeState();
}
class TypeState extends State<Type> {
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
keyboardType: TextInputType.number),
FlatButton(
child: Text("Subract"),
onPressed: () {
if (int.tryParse(_controller.text) == null) return;
globals.enteredValue = int.parse(_controller.text);
setState(() {
value -= globals.enteredValue;
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
count++;
print(count);
historyList.add(History(
enteredValue: int.parse(_controller.text),
data: widget.text.data,
dateTime: DateTime.now()));
},
),
])),
));
}
}
int value = 0;
int count = 0;
List<History> historyList = [];
class History {
int enteredValue;
String data;
DateTime dateTime;
History({
this.enteredValue,
this.data,
this.dateTime,
});
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}),
),
body: Container(
child: ListView.builder(
itemCount: historyList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
' Subtracted ${historyList[index].enteredValue} on ${historyList[index].data} ${historyList[index].dateTime.toString()}'),
);
},
),
));
}
}

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