Provider not updating when doing, Navigator.pop(context) in flutter - flutter

Here I am using provider package for state management.
I have a SpeedDial widget in the floatingActionButton. And whenever I add something in the list mainGoalList by using speedDial and do Navigator.pop(context); it does go back to the page but does not update the list.
SpeedDial
SpeedDialChild(
child: Icon(Icons.book),
backgroundColor: Colors.blue,
label: 'Add Notes',
labelStyle: TextStyle(
fontSize: 18.0,
color: Colors.black,
),
onTap: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context)
.viewInsets
.bottom),
child: AddNotes(),
),
));
}),
AddNote
Center(
child: FlatButton(
onPressed: () {
if (_actcontroller.text == null) {
print("Cannot add null topic");
} else {
addingTheNotes();
Navigator.pop(context);
}
},
child: Text("Add"),
color: Colors.blue,
),
)
Adding the notes
addingTheNotes() {
theDataProvider.ourAllnotes.add(
TodaysNoteClass(
note: _actcontroller.text,
dateTime: theDataProvider.notesChoosenDate,
status: false,
),
);
theDataProvider.showingTheTodaysList();
}
Here is the change notifier
List<TodaysNoteClass> _ourAllnotes = [];
List<TodaysNoteClass> get ourAllnotes => _ourAllnotes;
set ourAllnotes(List<TodaysNoteClass> val) {
_ourAllnotes = val;
notifyListeners();
}
Consumer class, this is where I am showing the notes
class HomePage extends StatefulWidget {
static const String id = 'homePage';
final String todaysDate =
DateFormat('d MMMM').format(DateTime.now()).toLowerCase();
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var theDataProvider;
Widget build(BuildContext context) {
theDataProvider = Provider.of<TheData>(context, listen: false);
return Consumer<TheData>(
builder: (context, value, child) => SingleChildScrollView(
child: Container(
child: Column(
children: [
Container(
height: 120,
child: TodaysNote(),
),
],
),
),
),
);
}
}
And this is the TodaysNote class
class TodaysNote extends StatefulWidget {
TodaysNote({Key key}) : super(key: key);
bool boxChecked = false;
#override
_TodaysNoteState createState() => _TodaysNoteState();
}
class _TodaysNoteState extends State<TodaysNote> {
var theDataProvider;
Widget build(BuildContext context) {
theDataProvider = Provider.of<TheData>(context, listen: false);
return Consumer<TheData>(
builder: (context, value, child) => Container(
child: theDataProvider.showingTheTodaysList(),
),
);
}
}
But now when I go to another screen and then come to the previous screen. I see the updated list.
I have wrapped the main file with provider, wrapped the files with consumer but did not work.
What might be the reason behind this?

try using this:
Navigator.push( context, MaterialPageRoute( builder: (context) => SecondPage()), ).then((value) => setState(() {}));

Related

Delete Specific ListTile from ListView.builder with longPress

In ListView.builder I'm adding a new ListTile with the button Pressed.
Now when I press on ListTile I want to delete that widget.
I have tried to do that by wrapping the widget with InkWell but when I try to delete it deletes from the last ListTile.
How to delete that specific ListTile when I longPressed on that.
Below here is the code
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
/*InkWell(
child: widgets[index],
onLongPress: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Delete?'),
actions: [
IconButton(
onPressed: () {
widgets.removeAt(index);
setState(() {
Navigator.pop(context);
});
},
icon: Icon(Icons.check))
],
));
},
);*/
class _HomeState extends State<Home> {
#override
List<Widget> widgets = [];
int inde = 0;
List<List> blogList = [];
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Note'),
centerTitle: true,
),
body: Column(children: [
Expanded(
child: ListView.builder(
itemCount: widgets.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: widgets[index],
onLongPress: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Delete?'),
actions: [
IconButton(
onPressed: () {
widgets.removeAt(index);
setState(() {
Navigator.pop(context);
});
},
icon: Icon(Icons.check))
],
));
},
);
},
),
),
FloatingActionButton(
onPressed: () {
setState(() {
widgets.add(Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(width: 2),
color: Color.fromARGB(255, 76, 178, 204),
),
child: ListTile(
leading: Icon(Icons.circle),
title: TextField(),
)),
));
});
},
child: Icon(Icons.add),
),
]));
}
}
Actually your code works, it deletes the ListTile which you use long press on.
The problem is that you do not assign different controllers to the TextField widgets. So if you enter some text into them, and call setState when deleting one, the values in the TextFields will be wrong, and it looks like the last one is deleted.
So you need to add the following logic to your code:
Create another list like widgets for the controllers.
When adding a new item, create a new controller and assign it to the TextField.
When deleting an item, dispose the controller and remove it from the controllers' list.
Don't forget to dispose all remaining controllers when the widget is disposed.
Here is a sample code, check for the comments where I added to your code. You can run it on DartPad.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Home(),
),
),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Widget> widgets = [];
// this is the list for the controllers
List<TextEditingController> controllers = [];
int inde = 0;
List<List> blogList = [];
// you need to add this in order to dispose
// the controllers when the widget is disposed
#override
void dispose() {
for (var controller in controllers) {
controller.dispose();
}
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Note'),
centerTitle: true,
),
body: Column(children: [
Expanded(
child: ListView.builder(
itemCount: widgets.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: widgets[index],
onLongPress: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete?'),
actions: [
IconButton(
onPressed: () {
setState(() {
widgets.removeAt(index);
// dispose the controller
controllers[index].dispose();
// remove the controller from list
controllers.removeAt(index);
});
Navigator.pop(context);
},
icon: const Icon(Icons.check))
],
));
},
);
},
),
),
FloatingActionButton(
onPressed: () {
setState(() {
// create a new controller and add it to the list
final newController = TextEditingController();
controllers.add(newController);
widgets.add(Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(width: 2),
color: const Color.fromARGB(255, 76, 178, 204),
),
child: ListTile(
leading: const Icon(Icons.circle),
// assign the controller to the field
title: TextField(controller: newController),
)),
));
});
},
child: const Icon(Icons.add),
),
]));
}
}
I suggest that following the convention, begin all private members of your state class with an underscore, so rename controllers to _controllers etc.

Flutter State Management with Bloc/Cubit

for many of you this is an obvious / stupid question, but I've come to a point where I don't have a clue anymore. I have real difficulties understanding State Management with Bloc / Cubit.
Expectation: I have a page with a ListView (recipe_list) of all recipes and an 'add' button. Whenever I click on a ListItem or the 'add' button I go to the next page (recipe_detail). On this page I can create a new recipe (if clicked the 'add' button before), update or delete the existing recipe (if clicked on ListItem before). When I click the 'save' or 'delete' button the Navigator pops and I go back to the previous page (recipe_list). I used Cubit to manage the state of the recipe list. My expectation is that the ListView updates automatically after I clicked 'save' or 'delete'. But I have to refresh the App to display the changes.
main.dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Recipe Demo',
home: BlocProvider<RecipeCubit>(
create: (context) => RecipeCubit(RecipeRepository())..getAllRecipes(),
child: const RecipeList(),
)
);
}
}
recipe_list.dart
class RecipeList extends StatefulWidget {
const RecipeList({Key? key}) : super(key: key);
#override
_RecipeListState createState() => _RecipeListState();
}
class _RecipeListState extends State<RecipeList> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 24.0
),
color: const Color(0xFFF6F6F6),
child: Stack(
children: [
Column(
children: [
Container(
margin: const EdgeInsets.only(
top: 32.0,
bottom: 32.0
),
child: const Center(
child: Text('Recipes'),
),
),
Expanded(
child: BlocBuilder<RecipeCubit, RecipeState>(
builder: (context, state) {
if (state is RecipeLoading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is RecipeError) {
return const Center(
child: Icon(Icons.close),
);
} else if (state is RecipeLoaded) {
final recipes = state.recipes;
return ListView.builder(
itemCount: recipes.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return BlocProvider<RecipeCubit>(
create: (context) => RecipeCubit(RecipeRepository()),
child: RecipeDetail(recipe: recipes[index]),
);
}
));
},
child: RecipeCardWidget(
title: recipes[index].title,
description: recipes[index].description,
),
);
},
);
} else {
return const Text('Loading recipes error');
}
}
),
),
],
),
Positioned(
bottom: 24.0,
right: 0.0,
child: FloatingActionButton(
heroTag: 'addBtn',
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return BlocProvider<RecipeCubit>(
create: (context) => RecipeCubit(RecipeRepository()),
child: const RecipeDetail(recipe: null),
);
}
));
},
child: const Icon(Icons.add_rounded),
backgroundColor: Colors.teal,
),
)
],
),
),
),
);
}
}
recipe_detail.dart
class RecipeDetail extends StatefulWidget {
final Recipe? recipe;
const RecipeDetail({Key? key, required this.recipe}) : super(key: key);
#override
_RecipeDetailState createState() => _RecipeDetailState();
}
class _RecipeDetailState extends State<RecipeDetail> {
final RecipeRepository recipeRepository = RecipeRepository();
final int _recipeId = 0;
late String _recipeTitle = '';
late String _recipeDescription = '';
final recipeTitleController = TextEditingController();
final recipeDescriptionController = TextEditingController();
late FocusNode _titleFocus;
late FocusNode _descriptionFocus;
bool _buttonVisible = false;
#override
void initState() {
if (widget.recipe != null) {
_recipeTitle = widget.recipe!.title;
_recipeDescription = widget.recipe!.description;
_buttonVisible = true;
}
_titleFocus = FocusNode();
_descriptionFocus = FocusNode();
super.initState();
}
#override
void dispose() {
recipeTitleController.dispose();
recipeDescriptionController.dispose();
_titleFocus.dispose();
_descriptionFocus.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 24.0
),
color: const Color(0xFFF6F6F6),
child: Stack(
children: [
Column(
children: [
Align(
alignment: Alignment.topLeft,
child: InkWell(
child: IconButton(
highlightColor: Colors.transparent,
color: Colors.black54,
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(Icons.arrow_back_ios_new_rounded),
),
),
),
TextField(
focusNode: _titleFocus,
controller: recipeTitleController..text = _recipeTitle,
decoration: const InputDecoration(
hintText: 'Enter recipe title',
border: InputBorder.none
),
style: const TextStyle(
fontSize: 26.0,
fontWeight: FontWeight.bold
),
onSubmitted: (value) => _descriptionFocus.requestFocus(),
),
TextField(
focusNode: _descriptionFocus,
controller: recipeDescriptionController..text = _recipeDescription,
decoration: const InputDecoration(
hintText: 'Enter recipe description',
border: InputBorder.none
),
),
],
),
Positioned(
bottom: 24.0,
left: 0.0,
child: FloatingActionButton(
heroTag: 'saveBtn',
onPressed: () {
if (widget.recipe == null) {
Recipe _newRecipe = Recipe(
_recipeId,
recipeTitleController.text,
recipeDescriptionController.text
);
context.read<RecipeCubit>().createRecipe(_newRecipe);
//recipeRepository.createRecipe(_newRecipe);
Navigator.pop(context);
} else {
Recipe _newRecipe = Recipe(
widget.recipe!.id,
recipeTitleController.text,
recipeDescriptionController.text
);
context.read<RecipeCubit>().updateRecipe(_newRecipe);
//recipeRepository.updateRecipe(_newRecipe);
Navigator.pop(context);
}
},
child: const Icon(Icons.save_outlined),
backgroundColor: Colors.amberAccent,
),
),
Positioned(
bottom: 24.0,
right: 0.0,
child: Visibility(
visible: _buttonVisible,
child: FloatingActionButton(
heroTag: 'deleteBtn',
onPressed: () {
context.read<RecipeCubit>().deleteRecipe(widget.recipe!.id!);
//recipeRepository.deleteRecipe(widget.recipe!.id!);
Navigator.pop(context);
},
child: const Icon(Icons.delete_outline_rounded),
backgroundColor: Colors.redAccent,
),
),
),
],
),
),
),
);
}
}
recipe_state.dart
part of 'recipe_cubit.dart';
abstract class RecipeState extends Equatable {
const RecipeState();
}
class RecipeInitial extends RecipeState {
#override
List<Object> get props => [];
}
class RecipeLoading extends RecipeState {
#override
List<Object> get props => [];
}
class RecipeLoaded extends RecipeState {
final List<Recipe> recipes;
const RecipeLoaded(this.recipes);
#override
List<Object> get props => [recipes];
}
class RecipeError extends RecipeState {
final String message;
const RecipeError(this.message);
#override
List<Object> get props => [message];
}
recipe_cubit.dart
part 'recipe_state.dart';
class RecipeCubit extends Cubit<RecipeState> {
final RecipeRepository recipeRepository;
RecipeCubit(this.recipeRepository) : super(RecipeInitial()) {
getAllRecipes();
}
void getAllRecipes() async {
try {
emit(RecipeLoading());
final recipes = await recipeRepository.getAllRecipes();
emit(RecipeLoaded(recipes));
} catch (e) {
emit(const RecipeError('Error'));
}
}
void createRecipe(Recipe recipe) async {
await recipeRepository.createRecipe(recipe);
final newRecipes = await recipeRepository.getAllRecipes();
emit(RecipeLoaded(newRecipes));
}
void updateRecipe(Recipe recipe) async {
await recipeRepository.updateRecipe(recipe);
final newRecipes = await recipeRepository.getAllRecipes();
emit(RecipeLoaded(newRecipes));
}
void deleteRecipe(int id) async {
await recipeRepository.deleteRecipe(id);
final newRecipes = await recipeRepository.getAllRecipes();
emit(RecipeLoaded(newRecipes));
}
}
It looks like you're creating another BlocProvider when you're navigating to RecipeDetail page. When you're pushing new MaterialPageRoute, this new page gets additionally wrapped in new RecipeCubit. Then, when you're calling context.read<RecipeCubit>(), you're referencing that provider (as this is closest BlocProvider in the widget tree). Your RecipeList can't react to those changes because it's BlocBuilder is looking for a BlocProvider declared above it in the widget tree (the one in MyApp).
Besides that, newly created provider gets removed from the widget tree anyway when you're closing RecipeDetail page as it is declared in the MaterialPageRoute which has just been pushed off the screen.
Try to remove the additional BlocProvider (the one in RecipeList, in OnTap function of RecipeCardWidget):
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return BlocProvider<RecipeCubit>( // remove this BlocProvider
create: (context) => RecipeCubit(RecipeRepository()),
child: RecipeDetail(recipe: recipes[index]),
);
}
));
},

How can I solve Flutter navigation BuilderContext subtype error?

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_auths/pages/searchservice.dart';
import 'package:flutter_auths/pages/tasks.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var queryResultSet = [];
var tempSearchStore = [];
initiateSearch(value) {
if (value.length == 0) {
setState(() {
queryResultSet = [];
tempSearchStore = [];
});
}
var capitalizedValue =
value.substring(0, 1).toUpperCase() + value.substring(1);
if (queryResultSet.length == 0 && value.length == 1) {
SearchService().searchByName(value).then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
queryResultSet.add(docs.documents[i].data);
}
});
} else {
tempSearchStore = [];
queryResultSet.forEach((element) {
if (element['Username'].startsWith(capitalizedValue)) {
setState(() {
tempSearchStore.add(element);
});
}
});
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('Firestore search'),
),
body: ListView(children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (val) {
initiateSearch(val);
},
decoration: InputDecoration(
prefixIcon: IconButton(
color: Colors.black,
icon: Icon(Icons.arrow_back),
iconSize: 20.0,
onPressed: () {
Navigator.of(context).pop();
},
),
contentPadding: EdgeInsets.only(left: 25.0),
hintText: 'Search by name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0))),
),
),
SizedBox(height: 10.0),
GridView.count(
padding: EdgeInsets.only(left: 10.0, right: 10.0),
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
primary: false,
shrinkWrap: true,
children: tempSearchStore.map((element) {
return buildResultCard(element);
}).toList())
]));
}
}
Widget buildResultCard(data) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
elevation: 2.0,
child: Container(
child: Column(
children: <Widget> [ Text(data['Username'],
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
RaisedButton(
onPressed: () {
Navigator.push(
data,
MaterialPageRoute(builder: (data) => ProfilePage()),
);
},
child: const Text('asd', style: TextStyle(fontSize: 12)),
),
]
)
)
);
}
Here I search for a user from database then it shows me the results in cards, I added a button and by clicking on it I want to navigate the page to another page but the following error occures.
this is the error and the app
So I want to click on specific user’s button and redirect the page to that user’s profile. How can I do that?
You are getting this error because instead of passing buildContext you are passing data.
So your error gets removed if you change you code from this
Navigator.push(
data,
MaterialPageRoute(builder: (data) => ProfilePage()),
);
to
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(username: data['Username']))
);
This is how you should pass the data to the Profile Page.
Also
Widget buildResultCard(data)
be changed to
Widget buildResultCard(context, data)
and
buildResultCard(element);
to
buildResultCard(context, element);
First, you need to Navigate to that page with data like
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(profileData: data))
);
then you need to receive that data
class ProfilePage extends StatefulWidget {
var profileData;
ProfilePage({this.profileData});
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(widget.profileData['username']),
),
);
}
}
You can pass and receive data in another way
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(),settings: RouteSettings(arguments: data))
);
then
class ProfilePage extends StatefulWidget {
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
var profileData;
#override
Widget build(BuildContext context) {
profileData=ModalRoute.of(context).settings.arguments;
return Scaffold(
body: Center(
child: Text(profileData['username']),
),
);
}
}

PushNamed issue: Type 'FillData' (a Statefulwidget) is not a subtype of type 'List<Object>'

I'm new in Flutter. I'm trying to push a List from NewData to FillData screen with pushNamed. But it said:
The following _TypeError was thrown while handling a gesture:
type 'FillData' is not a subtype of type 'List'
If i remove the comment in '/FillData', i receive null data instead. What should i do?
This is my code:
SettingNavigator
class SettingNavigator extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => Home(),
'/NewData': (context) => NewData(),
// '/FillData': (context) => FillData(), (in comment)
}
onGenerateRoute: (setting) {
if (setting.name == '/FillData') {
final ChartGroupData chartName = setting.arguments;
final List<ChartGroupData> groupNames = setting.arguments;
return MaterialPageRoute(builder: (context) {
return FillData(
chartName: chartName,
gName: groupNames,
);
});
}
return null;
},
);
}
}
NewData
import 'package:flutter/material.dart';
class NewData extends StatefulWidget {
List<ChartGroupData> groupNames;
NewData({Key key, #required this.groupNames}) : super(key: key);
#override
NewDataStage createState() => NewDataStage();
}
class NewDataStage extends State<NewData> {
TextEditingController _nameCtrl = new TextEditingController();
var textFields = <Widget>[];
var groupTECs = <TextEditingController>[];
#override
void initState() {
super.initState();
textFields.add(createCustomTextField());
}
Widget createCustomTextField() {
var groupCtrl = TextEditingController();
groupTECs.add(groupCtrl);
return Container(
padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
child: Row(
children: <Widget>[
Expanded(flex: 3, child: Text("Group ${textFields.length}")),
Container(
constraints: BoxConstraints.tightFor(width: 120, height: 60),
child: TextField(
controller: groupCtrl,
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("New Chart")),
),
body: Container(
alignment: AlignmentDirectional.center,
constraints: BoxConstraints.expand(),
child: Column(
children: <Widget>[
Text(
"Your chart name",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
TextField(
style: TextStyle(fontSize: 20),
controller: _nameCtrl,
),
Expanded(
flex: 3,
child: Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: textFields.length,
itemBuilder: (BuildContext context, int index) {
return textFields[index];
},
),
),
),
SizedBox(
height: 60,
width: 120,
child: RaisedButton(
onPressed: _onTapNext,
child: Text("NEXT"),
color: Colors.green,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _onTapCreate,
child: Icon(Icons.add, color: Colors.white),
shape: CircleBorder(),
),
),
);
}
void _onTapNext() {
/// Push Groups name to FillData
widget.groupNames = List<ChartGroupData>();
for (int i = 0; i < textFields.length; i++) {
var name = groupTECs[i].text;
widget.groupNames.add(ChartGroupData(name));
}
print(widget.groupNames.toString());
Navigator.pushNamed(context, '/FillData',
arguments: FillData(
gName: widget.groupNames,
chartName: ChartGroupData(_nameCtrl.text),
));
}
void _onTapCreate() {
setState(() {
textFields.add(createCustomTextField());
});
}
}
FillData
class FillData extends StatefulWidget {
final ChartGroupData chartName;
final List<ChartGroupData> gName;
FillData({Key key, #required this.chartName, #required this.gName})
: super(key: key);
#override
FillDataStage createState() => FillDataStage();
}
class FillDataStage extends State<FillData> {
void _showDialog() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Received Data"),
content: Text(widget.chartName.toString()),
);
},
);
}
void _onTapPrintReceivedData() {
print(widget.gName);
print(widget.chartName);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Fill your Data"),
),
),
body: Center(
child: RaisedButton(
onPressed: () {
_onTapPrintReceivedData();
_showDialog();
},
child: Text("Print Data"),
),
),
));
}
}
Class ChartGroupData
lass ChartGroupData {
final String groupNames;
ChartGroupData(this.groupNames);
#override
String toString() {
return 'Group: $groupNames';
}
}
You have 2 problems with your code:
1- you cant user routes with onGenerateRoute, because now the app doesn't know where to go, to the widget that you didn't pass anything to (inside routes) or to the widget inside the onGenerateRoute.
2- arguments is a general object that you can put whatever you want inside of it, and doing this:
final ChartGroupData chartName = setting.arguments; final
List groupNames = setting.arguments;
passes the same value to two different objects, I solved this by doing the following (it's not the best but will give you a rough idea of what you should do)
created a new object that contains the data to be passed:
class ObjectToPass {
final ChartGroupData chartName;
final List<ChartGroupData> groupNames;
ObjectToPass({this.chartName, this.groupNames});
}
changed FillData implementation:
class FillData extends StatefulWidget {
final ObjectToPass objectToPass;
FillData({Key key, #required this.objectToPass}) : super(key: key);
#override
FillDataStage createState() => FillDataStage();
}
...
void _showDialog() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Received Data"),
content: Text(widget.objectToPass.chartName.toString()),
);
},
);
}
void _onTapPrintReceivedData() {
print(widget.objectToPass.groupNames);
print(widget.objectToPass.chartName);
}
to navigate to FillData you would:
Navigator.pushNamed(
context,
'/FillData',
arguments: ObjectToPass(
chartName: ChartGroupData(_nameCtrl.text),
groupNames: groupNames,
),
);
finally this is how your MaterialApp should look like:
return MaterialApp(
initialRoute: '/NewData',
onGenerateRoute: (setting) {
if (setting.name == '/FillData') {
return MaterialPageRoute(builder: (context) {
return FillData(
objectToPass: setting.arguments,
);
});
} else if (setting.name == '/NewData') {
return MaterialPageRoute(builder: (_) => NewData());
}
return null;
},
);
you can pass a list instead of the object I created and get your objects from it by it's index.

Return the list of selected items, in the CheckBox, to the TabBar main screen Flutter

I have an app with two tabs. One for the "all items" list and second for the "favourite/saved items". The second tab has a FAB and text written "Add your favorite items here" inside the children of the Column widget. So when the FAB is clicked, Navigator.push() works and triggers a second screen for "selecting favorite items" by the use of CheckBox widget. I've made an empty list _saved (its actually a Set to avoid duplicates) to store the items that are to be selected. And in the 'select favorite items screen' there is also a FAB, which when clicked, Navigator.pop() works and SHOULD RETURN THE _saved LIST. And this is the only problem I'm facing. I'm just not able to implement it.
Also as I mentioned above some text is written in the "Saved Items" tab, I want to build something like
"If items selected, just show the items and not the (before mentioned) Text! If none selected anything, just return the Text."
You guys can check the entire code here.
The code where I'm facing issues:
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Add Your Favorite Sites Here!❤',
style: TextStyle(color: Colors.white),
),
Container(
child: Icon(Icons.favorite, size: 150, color: Colors.blue[100]),
),
SizedBox(height: 250),
FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
},
child: Icon(Icons.add),
foregroundColor: Colors.blue,
),
],
);
}
}
//The Favorite List Code:
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),
// backgroundColor: Colors.indigo,
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
// value: _saved.contains(context), // changed
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(context, _saved);
},
),
);
}
}
this is demo code, you can make your customize code using below code
class checkModel{
String nameOfSite;
bool isCheck;
checkModel(this.nameOfSite, this.isCheck);
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<checkModel> _list = new List();
#override
void initState() {
// TODO: implement initState
super.initState();
_list.add(checkModel("title1", false));
_list.add(checkModel("title2", false));
}
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
body: ListView.builder(
itemCount: _list.length,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
// value: _saved.contains(context), // changed
value: _list[index].isCheck,
onChanged: (val) {
print("object ${val}");
setState(() {
_list[index].isCheck = val;
});
},
title: Text(_list[index].nameOfSite),
);
},
),
);
}
}
Replace:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
With:
Navigator.push<Set>(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
).then((Set _saved){
print(_saved);
});
And see logs, you have the Set of saved items.