Selection of Item in DropdownButton causes Flutter to throw error - dart

I am currently trying to retrieve data (tags) from a REST API and use the data to populate a dropdown menu which I can successfully do but upon selection of the item, I get the following error which according to this would mean that the "selected value is not member of the values list":
items == null || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.
This occurs after the dropdown menu shows my selected item. However, this is error should not be occurring as I've done the necessary logging to check that the data is indeed assigned to the list in question. Could anyone help me resolve this issue? I have isolated it to down to it originating in the setState() method in onChanged of DropdownButton but can't seem to understand why that should be causing an issue. Any help would be deeply appreciated!
My code is as follows:
class _TodosByTagsHomePageState extends State<TodosByTagsHomePage> {
Tag selectedTag;
final Logger log = new Logger('TodosByTags');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: ListView(
children: <Widget>[
FutureBuilder<List<Tag>> (
future: fetchTags(),
builder: (context, snapshot) {
if (snapshot.hasData) {
log.info("Tags are present");
_tagsList = snapshot.data;
return DropdownButton<Tag>(
value: selectedTag,
items: _tagsList.map((value) {
return new DropdownMenuItem<Tag>(
value: value,
child: Text(value.tagName),
);
}).toList(),
hint: Text("Select tag"),
onChanged: (Tag chosenTag) {
setState(() {
log.info("In set state");
selectedTag = chosenTag;
Scaffold.of(context).showSnackBar(new SnackBar(content: Text(selectedTag.tagName)));
});
},
) ;
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container(width: 0.0, height: 0.0);
}),
])
);
}
// Async method to retrieve data from REST API
Future<List<Tag>> fetchTags() async {
final response =
await http.get(REST_API_URL);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
var result = compute(parseData, response.body);
return result;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
static List<Tag> parseData(String response) {
final parsed = json.decode(response);
return (parsed["data"] as List).map<Tag>((json) =>
new Tag.fromJson(json)).toList();
}
List<Tag> _tagsList = new List<Tag>();
}
// Model for Tag
class Tag {
final String tagName;
final String id;
final int v;
Tag({this.id, this.tagName, this.v});
factory Tag.fromJson(Map<String, dynamic> json) {
return new Tag(
id: json['_id'],
tagName: json['tagName'],
v: json['__v'],
);
}
}

update your code like this
I think issues that when calling setState in FutureBuilder that call fetchTags() move fetchTags() to initState() for once call
class _TodosByTagsHomePageState extends State<TodosByTagsHomePage> {
Tag selectedTag;
Future<List<Tag>> _tags;
#override
void initState() {
_tags = fetchTags();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: ListView(children: <Widget>[
FutureBuilder<List<Tag>>(
future: _tags,
builder: (context, snapshot) {
if (snapshot.hasData) {
return DropdownButton<Tag>(
value: selectedTag,
items: snapshot.data.map((value) {
print(value);
return DropdownMenuItem<Tag>(
value: value,
child: Text(value.tagName),
);
}).toList(),
hint: Text("Select tag"),
onChanged: (Tag chosenTag) {
setState(() {
selectedTag = chosenTag;
});
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container(width: 0.0, height: 0.0);
}),
]));
}

Related

How to assign <List<Data>> to list variable?

How to display one by one data using this DB function?
Future<List<Data>> display() async {
//final Database db = await database;
var db = await db1;
final List<Map<String, dynamic>> maps = await db.query('syncTable');
return List.generate(maps.length, (i) {
return Data(
syn_TableName: maps[i]['syn_TableName'],
syn_ChangeSequence: maps[i]['syn_ChangeSequence'],
);
});
}
You can use the FutureBuilder to consume your display() method. Then inside the FutureBuilder you can use AsyncSnapshot.data to get your List of Dataelements.
In the next step you use can call List.map() to map your Data to widgets. In this example I use the ListTile to display:
snapshot.data.map((data) {
return ListTile(
title: Text(data.syn_TableName),
subtitle: Text(data.syn_ChangeSequence),
);
}).toList(),
Here a minimal working example which you can try out:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder<List<Data>>(
initialData: [],
future: display(),
builder: (context, snapshot) {
return ListView(
children: snapshot.data.map((data) {
return ListTile(
title: Text(data.syn_TableName),
subtitle: Text(data.syn_ChangeSequence),
);
}).toList(),
);
}),
),
);
}
Future<List<Data>> display() async {
return List.generate(15, (i) {
return Data(
syn_TableName: 'syn_TableName $i',
syn_ChangeSequence: 'syn_ChangeSequence $i',
);
});
}
}
class Data {
final String syn_TableName;
final String syn_ChangeSequence;
Data({this.syn_ChangeSequence, this.syn_TableName});
}

Bloc cannot return data in the dialog

I am developing a simple todo app using flutter with BloC pattern.
It has a ui to display TodoDetails.
When a user click a button, it show a new SimpleDialog.
I want to show some Tag list in the SimpleDialog like:
class AddEditTodoPage extends StatefulWidget {
final TodoRepository todoRepository;
final TagRepository tagRepository;
final Todo todo;
final SaveTodoBloc bloc;
AddEditTodoPage({this.todoRepository, this.tagRepository, this.todo})
: bloc = SaveTodoBloc(
todoRepository: todoRepository,
tagRepository: tagRepository,
todo: todo);
#override
State<StatefulWidget> createState() => _AddEditTodoPageState(todo: todo);
}
class _AddEditTodoPageState extends State<AddEditTodoPage> {
final Todo todo;
_AddEditTodoPageState({this.todo});
#override
Widget build(BuildContext context) {
return Center(
child: StreamBuilder<Tag>(
stream: widget.bloc.tag,
builder: (context, snapshot) {
final tag = snapshot.data;
return OutlineButton(
onPressed: () async {
final selectedTag = await showDialog<TagSelection>(
context: context,
builder: (context) => _showTagSelectDialog(context),
);
},
);
}},
);
}
_showTagSelectDialog(BuildContext context) => SimpleDialog(
title: Text("Select a Tag or create a new one"),
children: <Widget>[
StreamBuilder<List<Tag>>(
stream: widget.bloc.tags,
builder: (context, snapshot) {
final tagList = snapshot.data;
if (tagList == null || tagList.isEmpty) {
// This is always 'null'!!!
return SizedBox();
} else {
return ListView(
children: tagList.map(_buildTagName).toList(),
);
}
}),
],
);
Widget _buildTagName(Tag tag) => Text(tag.name);
}
So my bloc is getting the TagList like:
class SaveTodoBloc {
final TodoRepository todoRepository;
final TagRepository tagRepository;
final Todo todo;
SaveTodoBloc({this.todoRepository, this.tagRepository, this.todo}) {
if (tagRepository != null) {
_getTags();
}
}
final _getTagsSubject = PublishSubject<List<Tag>>();
Stream<List<Tag>> get tags => _getTagsSubject.stream;
Future<Null> _getTags() async {
await tagRepository.getAll().then((list) {
_getTagsSubject.add(list);
print("[SaveTodoBloc][JOS] _getTags - $list"); // It resturns correct list of Tags.
});
}
}
When I check the log, the bloc logic returns correct list of Tags.
But when I show the Dialog, it doesn't have list of tags.
The list is null.

Flutter: My list view is not updated when I modify an item

I am developing a 'todo' flutter app using BloC Architecture pattern.
My 'Home' ui displays todo list, and user can click the item's button to change the status from "todo" to "complete".
When an item is completed, it should display with another color distinct from other todos not completed.
But when I click the "complete" button, the list view is not updated.
Below is my UI code:
class HomePage extends StatelessWidget {
final TodoRepository _todoRepository;
final HomeBloc bloc;
HomePage(this._todoRepository) : this.bloc = HomeBloc(_todoRepository);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<List<Task>>(
stream: bloc.todos,
builder: (context, snapshot) {
return ListView(
children: snapshot.data.map(_buildItem).toList(),
);
}),
),
);
}
Widget _buildItem(Todo todo) {
if (todo.complete) {
return completed(todo);
} else {
return inCompleted(todo);
}
}
Widget inCompleted(Todo todo) {
return MaterialButton(
textColor: Colors.white,
color: Colors.green,
child: Text("Complete"),
onPressed: () {
bloc.done.add(todo);
}
);
}
Widget completed(Todo todo) {
return MaterialButton(
textColor: Colors.white,
color: Colors.red,
child: Text("Cancel"),
onPressed: () {
bloc.done.add(todo);
}
);
}
}
And here is my BloC class:
class HomeBloc {
final _getTodosSubject = PublishSubject<List<Todo>>();
final _doneTodoSubject = PublishSubject<Todo>();
final _cancelTodoSubject = PublishSubject<Todo>();
final TodoRepository _todoRepository;
var _todos = <Todo>[];
Stream<List<Todo>> get todos => _getTodosSubject.stream;
Sink<Todo> get done => _doneTodoSubject.sink;
Sink<Todo> get cancel => _doneTodoSubject.sink;
HomeBloc(this._todoRepository) {
_getTodos().then((_) {
_getTodosSubject.add(_todos);
});
_doneTodoSubject.listen(_doneTodo);
_cancelTodoSubject.listen(_cancelTodo);
}
Future<Null> _getTodos() async {
await _todoRepository.getAll().then((list) {
_todos = list;
});
}
void _doneTodo(Todo todo) {
todo.complete = true;
_update(todo);
}
void _cancelTodo(Todo todo) async {
todo.complete = false;
_update(todo);
}
void _update(Todo todo) async {
await _todoRepository.save(todo);
_getTodos();
}
}
It's because you don't "refresh" your list after calling getTodos() here's the modification:
HomeBloc(this._todoRepository) {
_getTodos() //Remove the adding part it's done in the function
_doneTodoSubject.listen(_doneTodo);
_cancelTodoSubject.listen(_cancelTodo);
}
Future<Null> _getTodos() async {
await _todoRepository.getAll().then((list) {
_todos = list;
_getTodosSubject.add(list); //You can actually remove the buffer _todos object
});
}
As I mention in the comment you can remove the _todos buffer but I don't want to refract to much you code.
With these few adjustents it's should work.
Hope it's help !!

Get the value of the Future<Map<String,String>> in FutureBuilder

I have a Future method like below:
Future<Map<String,String>> readFavorites() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
names = prefs.getKeys();
for (var key in names) {
debugPrint("key is " + key);
debugPrint("value is " + prefs.get(key));
pairs.putIfAbsent(key, () => prefs.get(key));
}
return pairs;
}
I want to get the snapshot length plus the map's values in the futurebuilder below:
Widget build(BuildContext ctxt) {
return Container(
child: FutureBuilder(
future: readFavorites(),
builder: (context, AsyncSnapshot<Map<String,String>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
//replace this with a loading icon
child: new CircularProgressIndicator());
} else {
return ListView.builder(
itemExtent: 90,
itemCount: snapshot.data.length, <== How to get the map length?
itemBuilder: (BuildContext context, int index) {
return SingleDish(
dish_name: snapshot.data[index],
dish_picture: snapshot.data[index]., <== How to get the value from the map?
);
});
}
},
),
);
}
I tried the following but I got a null exception: snapshot.data[snapshot.data[index]]. Will appreciate any help.
UPDATE
What is interesting is that when I printed the key I got the following:
lib_cached_image_data_last_clean
Future<Map<String, String>> readFavorites() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
names = prefs.getKeys();
//This returned the correct value because I hardcoded the key
print("hardcoded key is " + prefs.getString("Cutlet"));
for (var key in names) {
//This fellow here returned lib_cached_image_data_last_clean
print("key is" + key);
pairs.putIfAbsent(key, () => prefs.get(key));
// print("key is " + pairs.length.toString());
}
return pairs;
}
So, I know for a fact that readFavorites() returns values. But am not sure why the key is not what I added in the SharedPreferences.
Take a look at this code it is auto explained and you can adapt this code to your needs.
Widget build(BuildContext ctxt) {
return Container(
child: FutureBuilder(
future: readFavorites(),
builder: (context, AsyncSnapshot<Map<String,String>> snapshot) {
switch( snapshot.connectionState){
case ConnectionState.none:
return Text("there is no connection");
case ConnectionState.active:
case ConnectionState.waiting:
return Center( child: new CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.data != null){
Map<String,String> myMap = Map.from( snapshot.data ); // transform your snapshot data in map
var keysList = myMap.keys.toList(); // getting all keys of your map into a list
return ListView.builder(
itemExtent: 90,
itemCount: myMap.length, // getting map length you can use keyList.length too
itemBuilder: (BuildContext context, int index) {
return SingleDish(
dish_name: keysList[index], // key
dish_picture: myMap[ keysList[index] ], // getting your map values from current key
);
}
);
}
// here your snapshot data is null so SharedPreferences has no data...
return Text("No data was loaded from SharedPreferences");
}//end switch
},
),
);
}

Usage of FutureBuilder with setState

How to use the FutureBuilder with setState properly? For example, when i create a stateful widget its starting to load data (FutureBuilder) and then i should update the list with new data, so i use setState, but its starting to loop for infinity (because i rebuild the widget again), any solutions?
class FeedListState extends State<FeedList> {
Future<Null> updateList() async {
await widget.feeds.update();
setState(() {
widget.items = widget.feeds.getList();
});
//widget.items = widget.feeds.getList();
}
#override
Widget build(BuildContext context) {
return new FutureBuilder<Null>(
future: updateList(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics:
const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: widget.items.length,
itemBuilder: (context, index) {
return FeedListItem(widget.items[index]);
},
),
onRefresh: updateList,
),
);
}
},
);
}
}
Indeed, it will loop into infinity because whenever build is called, updateList is also called and returns a brand new future.
You have to keep your build pure. It should just read and combine variables and properties, but never cause any side effects!
Another note: All fields of your StatefulWidget subclass must be final (widget.items = ... is bad). The state that changes must be stored in the State object.
In this case you can store the result (the data for the list) in the future itself, there is no need for a separate field. It's even dangerous to call setState from a future, because the future might complete after the disposal of the state, and it will throw an error.
Here is some update code that takes into account all of these things:
class FeedListState extends State<FeedList> {
// no idea how you named your data class...
Future<List<ItemData>> _listFuture;
#override
void initState() {
super.initState();
// initial load
_listFuture = updateAndGetList();
}
void refreshList() {
// reload
setState(() {
_listFuture = updateAndGetList();
});
}
Future<List<ItemData>> updateAndGetList() async {
await widget.feeds.update();
// return the list here
return widget.feeds.getList();
}
#override
Widget build(BuildContext context) {
return new FutureBuilder<List<ItemData>>(
future: _listFuture,
builder: (BuildContext context, AsyncSnapshot<List<ItemData>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return new Center(
child: new CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
final items = snapshot.data ?? <ItemData>[]; // handle the case that data is null
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: items.length,
itemBuilder: (context, index) {
return FeedListItem(items[index]);
},
),
onRefresh: refreshList,
),
);
}
},
);
}
}
Use can SchedulerBinding for using setState() inside Future Builders or Stream Builder,
SchedulerBinding.instance
.addPostFrameCallback((_) => setState(() {
isServiceError = false;
isDataFetched = true;
}));
Screenshot (Null Safe):
Code:
You don't need setState while using FutureBuilder.
class MyPage extends StatefulWidget {
#override
State<MyPage> createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
// Declare a variable.
late final Future<int> _future;
#override
void initState() {
super.initState();
_future = _calculate(); // Assign your Future to it.
}
// This is your actual Future.
Future<int> _calculate() => Future.delayed(Duration(seconds: 3), () => 42);
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<int>(
future: _future, // Use your variable here (not the actual Future)
builder: (_, snapshot) {
if (snapshot.hasData) return Text('Value = ${snapshot.data!}');
return Text('Loading...');
},
),
);
}
}

Resources