Build function returned null - flutter

I have an app which generates a new Card wrapped in a GestureDetector when the FAB of Scaffold is pressed. the app was working fine but i wanted to implement a delete card functionality and when i added that, the app doesnt recognize the return statements in the build function. I feel like im missing something obvious but since i am new to flutter i am struggling to find what went wrong.
Whole code:
class _Starting_screenState extends State<Starting_screen> {
int _count = 1;
#override
Widget build(BuildContext context) {
{
List<Widget> cardList = new List.generate(
_count, (int i) => new createCard());
SystemChrome.setEnabledSystemUIOverlays([]);
_deleteNoDo(int id, int index) async {
debugPrint("Deleted Item!");
setState(() {
cardList.removeAt(index);
});
void addItems() async {
setState(() {
cardList.insert(0, new GestureDetector(
onTap: () async {
await Navigator.push(context, MaterialPageRoute(
builder: (context) =>
TodoList(), // this just navigates to another screen ; not important in this question
)
);
},
child: Card(
child: ListTile(
title: Text("project 1"),
trailing: new Listener(
key: new Key(UniqueKey().toString()),
child: new Icon(Icons.remove_circle,
color: Colors.redAccent,),
onPointerDown: (pointerEvent) => _deleteNoDo(id, index),
),
subtitle: whitefontstylemont(text: "project 1",
size: 20,)) //this is just a custom TextStyle
),
));
});
}
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () async {
setState(() {
_count += 1;
});
},
heroTag: "btn2",
child: Icon(Icons.add, color: Color(whitecolor),),
backgroundColor: Color(redcolor),),
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
pinned: true,
flexibleSpace: FlexibleSpaceBar(
),
actions: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 20, right: 10),
child: whitefontstyle(
text: "Remaining tasks for today - ${cardList
.length}", size: 20,),
),
),
],
),
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2
),
delegate: new SliverChildBuilderDelegate((context,
index) {
return cardList[index];
},
childCount: cardList.length
)
),
]
)
);
}
}
}
}
delete function:
_deleteNoDo(int id, int index) async {
debugPrint("Deleted Item!");
setState(() {
cardList.removeAt(index);
});
function which adds a card :
void addItems() async {
setState(() {
cardList.insert(0, new GestureDetector(
onTap: () async {
await Navigator.push(context, MaterialPageRoute(
builder: (context) =>
TodoList(), // this just navigates to another screen ; not important in this question
)
);
},
child: Card(
child: ListTile(
title: Text("project 1"),
trailing: new Listener(
key: new Key(UniqueKey().toString()),
child: new Icon(Icons.remove_circle,
color: Colors.redAccent,),
onPointerDown: (pointerEvent) => _deleteNoDo(id, index),
),
subtitle: whitefontstylemont(text: "project 1", size: 20,)) //this is just a custom TextStyle
),
));
});
}
code where cards are displayed in a list
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2
),
delegate: new SliverChildBuilderDelegate((context, index) {
return cardList[index]; // this is where the cards are displayed in a list
},
childCount: cardList.length
)
)

Related

Flutter Alert Dialog doesn't work/displaying

So I am facing this problem that my alert Dialog isn't displaying. I had tried every possible solution and searching here and there but nothing works. When I click on the edit button from the pop up menu nothing is displayed everything remains the same.
Calling alert Dialog
trailing: PopupMenuButton(
icon: Icon(Icons.more_vert),
itemBuilder: (context)=>[
PopupMenuItem(
value:1,
onTap: (){
//debugPrint('popup');
Navigator.pop(context);
_showMyDialog();
},
child: ListTile(
leading: Icon(Icons.edit),
title: Text('Edit'),
)),
PopupMenuItem(
value:1,
// onTap: (){
// Navigator.pop(context);
// showDialogBox();
// },
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Delete'),
)),
]),
Alert Dialog Code
Future<void> showDialogBox(String title)async{
editController.text=title;
debugPrint('dialog');
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
debugPrint('alert');
return AlertDialog(
title: Text('Update'),
content: Container(
child: TextFormField(
controller: editController,
),
),
actions: [
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Update')),
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Cancel')),
],
);
}
);
}
Complete Class Code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:firebase_tutorial/utils/routes/routes_names.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_database/firebase_database.dart';
import '../../utils/utils.dart';
class PostScreen extends StatefulWidget {
const PostScreen({Key? key}) : super(key: key);
#override
State<PostScreen> createState() => _PostScreenState();
}
class _PostScreenState extends State<PostScreen> {
final ref=FirebaseDatabase.instance.ref('Post');
FirebaseAuth _auth=FirebaseAuth.instance;
final searchController=TextEditingController();
final editController=TextEditingController();
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: ()async{
SystemNavigator.pop();
return true;
},
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Post Screen'),
actions: [
GestureDetector(
onTap: (){
_auth.signOut().then((value){
Navigator.pushNamed(context, RoutesNames.loginScreen);
}).onError((error, stackTrace){
Utils().toastMessage(error.toString());
});
},
child: Icon(Icons.logout_outlined)),
SizedBox(width: 10,),
],
),
floatingActionButton: FloatingActionButton(
onPressed:(){
Navigator.pushNamed(context, RoutesNames.newPost);
},
child: Icon(Icons.add),),
body: Column(
children: [
// Expanded(
// child:FirebaseAnimatedList(
// query: ref,
// itemBuilder: (context,snapshot,animation,index){
// return ListTile(
// title: Text(snapshot.child('post').value.toString()),
// );
// }
// ),
// ),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextFormField(
onChanged: (String value){
setState(() {
});
},
controller: searchController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: "Search",
),
),
),
Expanded(child: StreamBuilder(
stream: ref.onValue,
builder: (context,AsyncSnapshot<DatabaseEvent> snapshot){
if(!snapshot.hasData){
return CircularProgressIndicator();
}
else{
return ListView.builder(
itemCount: snapshot.data!.snapshot.children.length,
itemBuilder: (context,index){
Map<dynamic,dynamic> map=snapshot.data!.snapshot.value as dynamic;
List<dynamic> list=[];
list.clear();
list=map.values.toList();
final title=list[index]['post'].toString();
if(searchController.text.isEmpty){
return ListTile(
title: Text(list[index]['post']),
subtitle: Text(list[index]['id'].toString()),
trailing: PopupMenuButton(
icon: Icon(Icons.more_vert),
itemBuilder: (context)=>[
PopupMenuItem(
value:1,
onTap: (){
//debugPrint('popup');
Navigator.pop(context);
_showMyDialog();
},
child: ListTile(
leading: Icon(Icons.edit),
title: Text('Edit'),
)),
PopupMenuItem(
value:1,
// onTap: (){
// Navigator.pop(context);
// showDialogBox();
// },
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Delete'),
)),
]),
);
}
else if(title.toLowerCase().contains(searchController.text.toLowerCase())){
return ListTile(
title: Text(list[index]['post']),
subtitle: Text(list[index]['id'].toString()),
);
}
else{
return Container();
}
});
}
}))
],
),
),
);
}
Future<void> showDialogBox(String title)async{
editController.text=title;
debugPrint('dialog');
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
debugPrint('alert');
return AlertDialog(
title: Text('Update'),
content: Container(
child: TextFormField(
controller: editController,
),
),
actions: [
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Update')),
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Cancel')),
],
);
}
);
}
}
try adding a delay before calling showDialog like this:
await Future.delayed(const Duration(milliseconds: 10));
Your dialog isnt displayed because when you select a menu item the pop() method is automatically called to close the popup menu; so if you open a dialog immediately, the dialog will get automatically popped.
hope this fixes your issue

I cannot send data to home screen using Flutter/Dart

I did a todo list, I want to send data home screen but I cannot.
I want to get data from page 2 with to do list app and create object on page 1 and add it to the list, but I can't send it with constructor.
class IlkEkran extends StatefulWidget {
String? works;
toDolist("Limon ", DateTime.now())
];
toDolist selectedIndex = toDolist.testerobject();
String? works;
_IlkEkranState({String? works}) { error is here
this.works = works;
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(children: [
Flexible(
child: ListView.builder(
itemCount: listem.length,
itemBuilder: (context, index) {
return Card(
margin: EdgeInsets.all(5),
elevation: 20,
child: ListTile(
title: Text(listem[index].yapilacaklar),
subtitle: Text(listem[index].tarih.toString()),
leading: CircleAvatar(child: Icon(Icons.shopping_basket)),
trailing: Wrap(
spacing: 5,
children: [
IconButton(
onPressed: () {
selectedIndex = listem[index];
setState(() {
listem.remove(selectedIndex);
});
},
icon: Icon(Icons.delete)),
IconButton(
onPressed: () {
setState(() {
toDolist newWork =
toDolist(works!, DateTime.now());
listem.add(newWork);
});
},
icon: Icon(Icons.notification_important)),
],
),
),
);
}),
),
]),
);
}
}

RangeError (index) Flutter

I am getting an error and red screen while trying to click a button. RangeError (index): Invalid value: Valid value range is empty: 0. I do not know how to fix this error because nothing is flagged until I run my emulator. I have attached my
If I need to add some code please let me know I am more than willing to. Thank you!
home_page.dart
import 'package:flutter/material.dart';
import 'package:timestudy_test/pages/study_page.dart';
import 'package:timestudy_test/pages/timer_page.dart';
import 'package:timestudy_test/viewmodels/study_viewmodel.dart';
class HomePage extends StatefulWidget {
#override
State createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
TextEditingController textController = new TextEditingController();
late String filter;
#override
void initState() {
textController.addListener(() {
setState(() {
filter = textController.text;
});
});
super.initState();
}
#override
void dispose() {
textController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text('TimeStudyApp'),
),
body: Material(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 8.0, left: 16.0, right: 16.0),
child: TextField(
style: TextStyle(fontSize: 18.0),
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: () {
textController.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
hintText: "Search...",
),
controller: textController,
)),
Expanded(
child: StudyViewModel.studies.length > 0
? ListView.builder(
itemCount: StudyViewModel.studies.length,
itemBuilder: (BuildContext context, int index) {
if (filter == null || filter == "") {
return buildRow(context, index);
} else {
if (StudyViewModel.studies[index].name
.toLowerCase()
.contains(filter.toLowerCase())) {
return buildRow(context, index);
} else {
return Container();
}
}
},
)
: Center(
child: Text('No studies found!'),
),
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
int? nullableInterger;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: 'Add a study',
selected: nullableInterger ?? 0,
)));
},
),
);
}
Widget buildRow(BuildContext context, int index) {
return ExpansionTile(
title: Text(StudyViewModel.studies[index].name, style: TextStyle(fontSize: 18.0)),
children: <Widget>[
ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: StudyViewModel.studies[index].tasks.length,
itemBuilder: (context, int taskIndex) {
return ListTile(
title: Text(StudyViewModel.studies[index].tasks[taskIndex].name),
contentPadding: EdgeInsets.symmetric(horizontal: 32.0),
subtitle: Text(
StudyViewModel.studies[index].tasks[taskIndex].elapsedTime),
trailing: IconButton(
icon: Icon(
Icons.timer
),
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TimerPage(
task: StudyViewModel
.studies[index].tasks[taskIndex])));
},
),
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(
Icons.edit
),
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: StudyViewModel.studies[index].name,
selected: index)));
},
),
IconButton(
icon: Icon(
Icons.delete
),
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Do you wish to delete this study?'),
actions: <Widget>[
FlatButton(
child: Text('Accept'),
onPressed: () async {
StudyViewModel.studies.removeAt(index);
await StudyViewModel.saveFile();
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
},
),
],
),
],
);
}
}
study_page.dart
import 'package:flutter/material.dart';
import 'package:timestudy_test/models/study.dart';
import 'package:timestudy_test/models/task.dart';
import 'package:timestudy_test/viewmodels/study_viewmodel.dart';
class StudyPage extends StatefulWidget {
final String title;
final int selected;
StudyPage({required this.title, required this.selected});
#override
State createState() => StudyPageState();
}
class StudyPageState extends State<StudyPage> {
late Study study;
late TextField nameField;
TextEditingController nameController = new TextEditingController();
late TextField taskNameField;
TextEditingController taskNameController = new TextEditingController();
#override
void initState() {
nameField = new TextField(
controller: nameController,
decoration: InputDecoration(
labelText: 'Study name'),
);
taskNameField = new TextField(
controller: taskNameController,
decoration:
InputDecoration(labelText: 'Task name'),
);
if(widget.selected != null) {
study = StudyViewModel.studies[widget.selected];
nameController.text = study.name;
} else {
study = new Study(
name: "",
tasks: <Task>[]
);
}
super.initState();
}
#override
void dispose() {
nameController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text(widget.title),
),
body: Material(
child: Padding(padding: EdgeInsets.all(16.0), child: Column(
children: <Widget>[
Padding(padding: EdgeInsets.only(bottom: 8.0), child: nameField),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Tasks:', style: TextStyle(fontSize: 18.0),),
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add a task'),
content: taskNameField,
actions: <Widget>[
FlatButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Accept'),
onPressed: () {
if(taskNameController.text == ""){
errorDialog(context, 'Please enter a task name!');
} else {
setState(() {
study.tasks.add(new Task(
name: taskNameController.text,
elapsedTime:
StudyViewModel.milliToElapsedString(
0)));
taskNameController.clear();
});
Navigator.of(context).pop();
}
},
),
],
);
});
},
)
],
),
Expanded(
child: ListView.builder(
itemCount: study.tasks.length,
itemBuilder: (context, int index) {
return ListTile(
title: Text(study.tasks[index].name),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
study.tasks.removeAt(index);
});
},
),
);
},
),
), Spacer(),
Center(
child: RaisedButton(
color: Theme.of(context).accentColor,
child: Text('Save'),
onPressed: () async {
if (nameController.text == "") {
errorDialog(context, 'Please enter a study name!');
} else {
if (study.tasks.length < 1) {
errorDialog(context, 'Please add at least one task!');
} else {
study.name = nameController.text;
if (widget.selected != null) {
StudyViewModel.studies[widget.selected] = study;
await StudyViewModel.saveFile();
Navigator.of(context).pop();
} else {
if (StudyViewModel.checkName(nameController.text)) {
errorDialog(context, 'Study name already taken!');
} else {
StudyViewModel.studies.add(study);
await StudyViewModel.saveFile();
Navigator.of(context).pop();
}
}
}
}
},
))
],
),
)));
}
void errorDialog(BuildContext context, String message) async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
}
);
}
}
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
int? nullableInterger;
// the issue is here you need to assign value
// the nullableInterger is use here as nothing.. declare it on state level and
// assign it when your listview builder done so the value of nullable integer is
// changed and passing value as argument will not be 0 and this error will not appear again
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: 'Add a study',
selected: nullableInterger ?? 0,
)));
},
),

ValueListenableBuilder<String> widget cannot be marked as needing to build. setState() or markNeedsBuild() called during build. File_manager flutter

I am using the file_manager package. When I try to run the example code given, I get the below error. I'm not familiar with ValueNotifier and ValueListenableBuilder so I can't figure out, what seems to be the issue here.
The following assertion was thrown while dispatching notifications for ValueNotifier<String>:
setState() or markNeedsBuild() called during build.
This ValueListenableBuilder<String> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
Below is the code. I have not added a single line of my own code. It is package example code
import 'dart:io';
import 'package:file_manager/file_manager.dart';
import 'package:flutter/material.dart';
class HomeView extends StatelessWidget {
final FileManagerController controller = FileManagerController();
HomeView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// Creates a widget that registers a callback to veto attempts by the user to dismiss the enclosing
// or controllers the system's back button
return WillPopScope(
onWillPop: () async {
if (await controller.isRootDirectory()) {
return true;
} else {
controller.goToParentDirectory();
return false;
}
},
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
onPressed: () => createFolder(context),
icon: const Icon(Icons.create_new_folder_outlined),
),
IconButton(
onPressed: () => sort(context),
icon: const Icon(Icons.sort_rounded),
),
IconButton(
onPressed: () => selectStorage(context),
icon: const Icon(Icons.sd_storage_rounded),
)
],
title: ValueListenableBuilder<String>(
valueListenable: controller.titleNotifier,
builder: (context, title, _) => Text(title),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () async {
await controller.goToParentDirectory();
},
),
),
body: Container(
margin: const EdgeInsets.all(10),
child: FileManager(
controller: controller,
builder: (context, snapshot) {
final List<FileSystemEntity> entities = snapshot;
return ListView.builder(
itemCount: entities.length,
itemBuilder: (context, index) {
FileSystemEntity entity = entities[index];
return Card(
child: ListTile(
leading: FileManager.isFile(entity)
? const Icon(Icons.feed_outlined)
: const Icon(Icons.folder),
title: Text(FileManager.basename(entity)),
subtitle: subtitle(entity),
onTap: () async {
if (FileManager.isDirectory(entity)) {
// open the folder
controller.openDirectory(entity);
// delete a folder
// await entity.delete(recursive: true);
// rename a folder
// await entity.rename("newPath");
// Check weather folder exists
// entity.exists();
// get date of file
// DateTime date = (await entity.stat()).modified;
} else {
// delete a file
// await entity.delete();
// rename a file
// await entity.rename("newPath");
// Check weather file exists
// entity.exists();
// get date of file
// DateTime date = (await entity.stat()).modified;
// get the size of the file
// int size = (await entity.stat()).size;
}
},
),
);
},
);
},
),
)),
);
}
Widget subtitle(FileSystemEntity entity) {
return FutureBuilder<FileStat>(
future: entity.stat(),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (entity is File) {
int size = snapshot.data!.size;
return Text(
"${FileManager.formatBytes(size)}",
);
}
return Text(
"${snapshot.data!.modified}",
);
} else {
return const Text("");
}
},
);
}
selectStorage(BuildContext context) {
showDialog(
context: context,
builder: (context) => Dialog(
child: FutureBuilder<List<Directory>>(
future: FileManager.getStorageList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final List<FileSystemEntity> storageList = snapshot.data!;
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: storageList
.map((e) => ListTile(
title: Text(
"${FileManager.basename(e)}",
),
onTap: () {
controller.openDirectory(e);
Navigator.pop(context);
},
))
.toList()),
);
}
return const Dialog(
child: CircularProgressIndicator(),
);
},
),
),
);
}
sort(BuildContext context) async {
showDialog(
context: context,
builder: (context) => Dialog(
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: const Text("Name"),
onTap: () {
controller.sortedBy = SortBy.name;
Navigator.pop(context);
}),
ListTile(
title: const Text("Size"),
onTap: () {
controller.sortedBy = SortBy.size;
Navigator.pop(context);
}),
ListTile(
title: const Text("Date"),
onTap: () {
controller.sortedBy = SortBy.date;
Navigator.pop(context);
}),
ListTile(
title: const Text("type"),
onTap: () {
controller.sortedBy = SortBy.type;
Navigator.pop(context);
}),
],
),
),
),
);
}
createFolder(BuildContext context) async {
showDialog(
context: context,
builder: (context) {
TextEditingController folderName = TextEditingController();
return Dialog(
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: TextField(
controller: folderName,
),
),
ElevatedButton(
onPressed: () async {
try {
// Create Folder
await FileManager.createFolder(
controller.getCurrentPath, folderName.text);
// Open Created Folder
controller.setCurrentPath =
controller.getCurrentPath + "/" + folderName.text;
} catch (e) {}
Navigator.pop(context);
},
child: const Text('Create Folder'),
)
],
),
),
);
},
);
}
}

Flutter Provider/Consumer UI not Updating with Data Change

I am new to Flutter and working on developing my first application. I an having trouble updating my UI based on data changes. I followed this tutorial: https://www.filledstacks.com/post/flutter-architecture-my-provider-implementation-guide/ (and added extra features with https://www.filledstacks.com/post/flutter-provider-architecture-sharing-data-across-your-models/), which walks through a MVVM setup using the GetIt library.
I have successfully passed the data through the viewmodels and services, but I can't get my UI to update. Essentially, I want a user to be able to tap the movie on their watchlist and remove it. This works in a data sense, but my Watchlist UI isn't updating when I pop back to it. My entire project is available at https://github.com/n0ahth0mas/movie_night, but the core files to this problem are listed here:
locator.dart
...
...
GetIt locator = GetIt.instance;
void setupLocator() {
locator.registerLazySingleton(() => AuthenticationService());
locator.registerLazySingleton(() => WatchlistService());
locator.registerLazySingleton(() => Api());
locator.registerLazySingleton(() => LoginModel());
locator.registerFactory(() => HomeModel());
locator.registerFactory(() => RemoveButtonModel());
locator.registerFactory(() => WatchlistModel());
}
watchlist_service.dart
...
...
class WatchlistService {
Api _api = locator<Api>();
List<Movie> _watchlist = [];
List<Movie> get watchlist => _watchlist;
Future getUserWatchlist(User user) async {
for (String id in user.watchlistId) {
_watchlist.add(await _api.getMovie(id));
}
}
bool inList(Movie movie) {
return _watchlist.contains(movie);
}
void editList(Movie movie, bool remove) {
if (remove) {
_watchlist.remove(movie);
print("removed " + movie.title + " from list in watchlist service");
} else {
_watchlist.add(movie);
print("added " + movie.title + " to list in watchlist service");
}
}
}
watchlist_model.dart
...
...
class WatchlistModel extends BaseModel {
WatchlistService _watchlistService = locator<WatchlistService>();
List<Movie> get watchlist => _watchlistService.watchlist;
Future getWatchlist(User user) async {
setState(ViewState.Busy);
await _watchlistService.getUserWatchlist(user);
setState(ViewState.Idle);
}
}
watchlist_view.dart
...
...
class WatchlistView extends StatelessWidget {
Widget _createMovieCard(Movie movie, BuildContext context) {
return CupertinoButton(
onPressed: () => _getInfo(movie, context),
child: Image.network(movie.getPoster(185)),
);
}
_getInfo(Movie movie, BuildContext context) {
Navigator.pushNamed(
context,
"details",
arguments: movie,
);
}
#override
Widget build(BuildContext context) {
return BaseView<WatchlistModel>(
onModelReady: (model) => model.getWatchlist(Provider.of<User>(context)),
builder: (context, model, child) => Scaffold(
body: model.state == ViewState.Idle
? CustomScrollView(
primary: false,
slivers: <Widget>[
CupertinoSliverNavigationBar(
largeTitle: Text("My Watchlist"),
trailing: Material(
color: Colors.transparent,
child: IconButton(
icon: Icon(CupertinoIcons.add_circled_solid),
onPressed: () =>
Navigator.pushNamed(context, 'search'))),
),
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio:
MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 1.7)),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return _createMovieCard(
model.watchlist[index], context);
}, childCount: model.watchlist.length),
),
],
)
: Center(child: CircularProgressIndicator())));
}
}
removebtn_model.dart
...
...
class RemoveButtonModel extends BaseModel {
WatchlistService _watchlistService = locator<WatchlistService>();
//bool watchlistStatus()
void removeMovie(Movie movie) {
print("removed " + movie.title + " from list in remove button model");
_watchlistService.editList(movie, true);
notifyListeners();
}
void addMovie(Movie movie) {
print("added " + movie.title + " to list in remove button model");
_watchlistService.editList(movie, false);
notifyListeners();
}
}
details_view.dart
...
...
class DetailsView extends StatelessWidget {
_makeStars(double voteAverage) {
double trueRating = voteAverage / 2;
print(trueRating);
return GFRating(
color: Colors.yellowAccent[700],
value: trueRating,
size: GFSize.SMALL,
allowHalfRating: true,
);
}
_backdrop(String link) {
if (link != null) {
return Image.network("http://image.tmdb.org/t/p/w780/$link");
} else
return Image.asset("assets/images/transparent.png");
}
#override
Widget build(BuildContext context) {
Movie movie = ModalRoute.of(context).settings.arguments;
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
CupertinoSliverNavigationBar(
largeTitle: Text(movie.title),
trailing:
Material(color: Colors.transparent, child: RemoveButton(movie)),
),
SliverToBoxAdapter(
child: Column(
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 20)),
Center(child: Image.network(movie.getPoster(342))),
Center(
child: Container(
padding: EdgeInsets.all(10),
child: Center(
child: Text(movie.title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 40, fontWeight: FontWeight.w800))),
)),
Container(
padding: EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_makeStars(movie.voteAverage),
Text("platform",
style: Theme.of(context).textTheme.headline5),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(20, 0, 10, 50),
child: Text(movie.overview),
),
_backdrop(movie.backdropPath)
],
))
],
),
);
}
}
remove_btn.dart
...
...
class RemoveButton extends StatelessWidget {
final Movie movie;
RemoveButton(this.movie);
_showDialog(String id, bool inWatchlist, BuildContext context,
RemoveButtonModel model) {
if (inWatchlist) {
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text("Remove from your watchlist?"),
actions: <Widget>[
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: Text("Cancel"),
),
CupertinoDialogAction(
textStyle: TextStyle(color: Colors.red),
onPressed: () => _deletelist(id, context, model),
child: Text("Remove"),
)
]));
} else {
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text("Add to your watchlist?"),
actions: <Widget>[
CupertinoDialogAction(
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: Text("Cancel"),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _addList(id, context, model),
child: Text("Add"),
)
]));
}
}
_deletelist(String id, BuildContext context, RemoveButtonModel model) {
model.removeMovie(movie);
Provider.of<User>(context).deleteFromWatchlist(id);
//Navigator.pushNamed(context, 'watchlist');
Navigator.popUntil(context, ModalRoute.withName('watchlist'));
}
_addList(String id, BuildContext context, RemoveButtonModel model) {
model.addMovie(movie);
Provider.of<User>(context).addToWatchList(id);
Navigator.popUntil(context, ModalRoute.withName('watchlist'));
}
Widget _rightBtn(Movie movie, BuildContext context, RemoveButtonModel model) {
if (Provider.of<User>(context).inWatchlist(movie)) {
return IconButton(
icon: Icon(Icons.remove_circle),
color: Colors.blue,
onPressed: () =>
_showDialog(movie.id.toString(), true, context, model));
} else {
return IconButton(
icon: Icon(Icons.add_circle),
color: Colors.blue,
onPressed: () =>
_showDialog(movie.id.toString(), false, context, model));
}
}
#override
Widget build(BuildContext context) {
return BaseView<RemoveButtonModel>(
builder: (context, model, child) => _rightBtn(movie, context, model),
);
}
}
Thanks for your help! I've been stuck on this for the past 3 days and cannot figure out what I'm doing wrong.