I am writing a flutter program where the user should select a value from a DropdownButtonFormField. once the selection is made, the choice should be displayed on the dropdown. I use a push route to get the data from a second screen in which the choice is utilized. My problem is after selecting the option, the page refreshes and therefore doesnt show the selected value on the dropdown.
Below is my code:
I create the Dropdownbuttonformfield in a file called shared.dart so I can call it in multiple files:
class UserDropdownList extends StatefulWidget {
#override
_UserDropdownListState createState() => _UserDropdownListState();
}
class _UserDropdownListState extends State<UserDropdownList> {
String currentUser;
#override
Widget build(BuildContext context) {
final user = Provider.of<List<User>>(context) ?? [];
return DropdownButtonFormField(
isExpanded: true,
decoration: textInputDecoration,
value: currentUser,
hint: Text(
'Incoming Officer',
),
onChanged: (val) {
setState(() => currentUser = val);
var route = MaterialPageRoute(
builder: (BuildContext context) =>
FinalForm(chosenUser: currentUser,)
);
Navigator.of(context).push(route);
},
// onChanged: (val) => setState(() => currentUser = val),
items: user.map((user){
return DropdownMenuItem(
value: user.userId,
child: Text(user.name)
);
}).toList(),
);
}
}
I then call the Custom button in my main page like so
class FinalForm extends StatefulWidget {
//code for importing selected user
final String chosenUser;
FinalForm({Key key, this.chosenUser}) : super (key: key);
#override
_FinalForm createState() => _FinalFormState();
}
class _FinalFormState extends State<FinalForm> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Final Form')
),
body: Form(
child: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
children: <Widget>[
SizedBox(height: 20.0),
Align(
child: Text(
'Select Incoming Officer',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.blueAccent,
),
)
),
SizedBox(height: 20.0),
StreamProvider<List<User>>.value(
value: DatabaseService().users,
child: UserDropdownList(),
),
SizedBox(height: 20.0),
Text("${widget.chosenUser}"),
],),
),
),
);
}
}
Is there a way to keep the selected value on the dropdown or prevent the screen from reloading?
If you are navigating away from the current page / view, it would make sense for the current dropdown selection to be lost. You can pass the current selection as an argument to the push function to redisplay on the new page. Hth
Related
I am implementing a sort by function which displays sort options through a modal bottom sheet, I am able to do it in my "Home Page" widget. Would like to check if I can extract these codes and sub it as a widget for better organization. I am unable to do as I am concerned with the return values from the radio value.
Appreciate any help given, thanks!!
Here is my code:
child: TextButton.icon( // Button to press sort
onPressed: (() {
showModalBottomSheet( // show modal
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10.0)),
context: context,
builder: (BuildContext build) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[ // radio values
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text(
"Case Earliest to Latest"),
onChanged: (val) {
print(
"Radio Tile pressed $val");
setSelectedRadioTile(val!);
print(selectedRadioTile);
Navigator.pop(context);
},
activeColor:
constants.secondaryBlueColour,
),
RadioListTile(
value: 2,
groupValue: selectedRadioTile,
title: Text(
"Case Latest to Earliest "),
onChanged: (val) {
print(
"Radio Tile pressed $val");
setSelectedRadioTile(val!);
print(selectedRadioTile);
Navigator.pop(context);
},
activeColor:
constants.secondaryBlueColour,
)
],
);
});
}),
icon: Icon(
Icons.sort,
size: 28,
color: constants.textGrayColour,
),
label: Text("Sort",
style: TextStyle(
color: constants.textGrayColour,
fontWeight: FontWeight.bold)))),***
Container(
margin: const EdgeInsets.only(top: 5),
width: MediaQuery.of(context).size.width * 0.5,
decoration: BoxDecoration(
border: Border(
left: BorderSide(
width: 2.0,
color:
constants.categoryButtonBackgroundColour),
bottom: BorderSide(
width: 2.0,
color:
constants.categoryButtonBackgroundColour),
)),
child: TextButton.icon(
onPressed: () {},
icon: Icon(Icons.filter_alt,
size: 28, color: constants.textGrayColour),
label: Text("Filter",
style: TextStyle(
color: constants.textGrayColour,
fontWeight: FontWeight.bold))),
),
],
),
I implemented a SortWidget() but am wondering how I can return the current radio value to my homepage and set the state in the homepage based on the radio value
showModalBottomSheet is a future method, you can use async method for this. and Navigator.pop(context, value); will give you the result. you can also used callback method, seems not needed for your case.
onPressed:()async {
final value = await showModalBottomSheet(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
context: context,
builder: (BuildContext build) {
return MyBottomSheetWidget(selectedRadioTile: selectedRadioTile);
},
);
print("$value");
}
class MyBottomSheetWidget extends StatelessWidget {
// make it statefulWidget if you want to update dialog ui
const MyBottomSheetWidget({
Key? key,
required this.selectedRadioTile,
}) : super(key: key);
final selectedRadioTile;
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// radio values
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("Case Earliest to Latest"),
onChanged: (val) {
print("Radio Tile pressed $val");
Navigator.pop(context, val);
},
),
RadioListTile(
value: 2,
groupValue: selectedRadioTile,
title: Text("Case Latest to Earliest "),
onChanged: (val) {
print("Radio Tile pressed $val");
// setSelectedRadioTile(val!);
print(selectedRadioTile);
Navigator.pop(context, val);
},
)
],
);
}
}
showModalBottomSheet is actually a function which can't converted to widget without having some other widget in place. What you can do is, create a function which hold code of this showModalBottomSheet and call that function on button click.
But if you want to create a separate widget then you can create the widget from the internal code of the showModalBottomSheet which starts with return Column.
You need to create a widget which can take two properties which are int variable named selected and a Function named setSelected. Then you can call that widget from inside the showModalBottomSheet and pass two props from your page. This selected will be set as selectedRadioTile & setSelected will be set as setSelectedRadioTile.
Example Code
class BottomFilter extends StatelessWidget {
const BottomFilter(
{Key? key,
required this.selected,
required this.setSelected})
: super(key: key);
final int selected;
final Function setSelected;
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// radio values
RadioListTile(
value: 1,
groupValue: selected,
title: Text("Case Earliest to Latest"),
onChanged: (val) {
print("Radio Tile pressed $val");
setSelected(val!);
print(selected);
Navigator.pop(context);
},
activeColor: Colors.amber,
),
RadioListTile(
value: 2,
groupValue: selected,
title: Text("Case Latest to Earliest "),
onChanged: (val) {
print("Radio Tile pressed $val");
setSelected(val!);
print(selected);
Navigator.pop(context);
},
activeColor: Colors.amber,
)
],
);
}
}
Call it like this
builder: (BuildContext build) {
return BottomFilter(selected: selectedRadioTile, setSelected: setSelectedRadioTile);
})
Dartpad link to test this code https://dartpad.dev/?id=9359bc416ae48b996085d6f98a977e27
I have been building this quiz app using flutter and I seem to have encountered an issue. The problem is that I have made a drawer in the App where I display all the topics and their respective quizzes, and for the user currently logged in, the leading widget inside the ListTile widget can take 2 icon values depending on whether the user has completed the quiz or not. For some reason, the Icon doesn't seem to update for the quizzes that are actually complete.
I have basically tried creating a list of all the quizzes that the user has completed and checking whether the list contains the quiz represented by each ListTile. For some reason, I can't seem to make it work.
here is the code for my 'drawer.dart' file :
class AppTopicDrawer extends StatelessWidget {
final List<Topic> topics;
const AppTopicDrawer({super.key, required this.topics});
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView.separated(
shrinkWrap: true,
itemBuilder: ((context, index) {
var topic = topics[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(10, 30, 10, 30),
child: Text(
topic.title,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
),
QuizList(topic: topic),
],
);
}),
separatorBuilder: ((context, index) {
return const Divider();
}),
itemCount: topics.length,
),
);
}
}
class QuizList extends StatelessWidget {
final Topic topic;
const QuizList({super.key, required this.topic});
#override
Widget build(BuildContext context) {
return Column(
children: topic.quizzes.map((e) {
return Card(
elevation: 4,
margin: const EdgeInsets.all(10.0),
child: InkWell(
onTap: (() {}),
child: Container(
padding: const EdgeInsets.fromLTRB(5, 10, 5, 10),
child: ListTile(
title: Text(e.title),
subtitle: Text(
e.description,
style: const TextStyle(fontSize: 12),
),
leading: QuizBadge(topic: topic, quizId: e.id),
)),
),
);
}).toList(),
);
}
}
class QuizBadge extends StatelessWidget {
const QuizBadge({super.key, required this.topic, required this.quizId});
final Topic topic;
final String quizId;
#override
Widget build(BuildContext context) {
Report report = Provider.of<Report>(context);
List completed = report.topics[topic.id] ?? [];
print(completed);
if (completed.contains(quizId)) {
return const Icon(FontAwesomeIcons.checkDouble, color: Colors.green);
} else {
return const Icon(FontAwesomeIcons.solidCircle, color: Colors.grey);
}
}
}
This is the current state of the drawer :
This is the app firestore where I try to access the 'reports' collection.
This is the stream provider I am using:
Any help regarding this issue will be appreciated. Thank You.
Assumption and what I want to achieve
I want to make it so that after inputting into the TextField of the TodoAddPage class, it will be displayed in the TodoListPage class like a "TODO list".
Problems and error messages that are occurring
It looks like the following image.
! image description
The corresponding source code.
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
// app name
title: 'My Todo App',
theme: ThemeData(
// theme color
primarySwatch: Colors.blue,
),
// display the list list screen
home: TodoListPage(),
);
}
}
// Widget for list list screen
class MyTodoApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Todo App',
// App name
theme: ThemeData(
// theme color
primarySwatch: Colors.blue,
),
// Display the list list screen
home:
TodoListPage()
);
}
}
// Widget for list list screen
class TodoListPage extends StatefulWidget {
#override
_TodoListPageState createState() => _TodoListPageState();
}
class _TodoListPageState extends State<TodoListPage> {
// Todo list data
List<String> todoList = [];
#override
Widget build(BuildContext context) {
double _width = MediaQuery.of(context).size.width;
double _height = MediaQuery.of(context).size.height;
return Scaffold(
// Display the AppBar and set the title
appBar: AppBar(
title: Text('List of Lists'),
),
body: Container(
height: _height,
width: _width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xffe4a972).withOpacity(0.6),
const Color(0xff9941d8).withOpacity(0.6), const Color(0xff9941d8).withOpacity(0.6),
],
begin: Alignment.topRight,
end: Alignment.bottomLeft,
),
),
child: ListView.builder(
itemCount: todoList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(todoList[index]),
),
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// "push" to transition to new screen
// receive the value passed from the add list screen
final newListText = await Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
// specify the list add screen as the destination screen
return TodoAddPage();
}),
);
if (newListText ! = null) () {
// note that newListText will be null if we cancel it
setState(() {
// add list
todoList.add(newListText);
});
};
},
child: Icon(Icons.add),
),
// Create a ListView based on the data
);
}
}
// Widget for list add screen
class TodoAddPage extends StatefulWidget {
#override
_TodoAddPageState createState() => _TodoAddPageState();
}
class _TodoAddPageState extends State<TodoAddPage> {
// Have the input text as data
String _text = '';
// Widget to display based on the data
#override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(
title: Text('Add list'),
),
body: Container(
// Add margins
padding: EdgeInsets.all(64),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// Display the input text
Text(_text, style: TextStyle(color: Colors.blue)),
const SizedBox(height: 8),
// Input text
TextField(
// receive the value of the input text (value is the input text)
onChanged: (String value) {
// notify that the data has changed (refresh the screen)
setState(() {
// change the data
_text = value;
});
},
),
const SizedBox(height: 8),
Container(
// expand to full width
width: double.infinity,
// add list button
child: ElevatedButton(
onPressed: () {
// "pop" to go back to the previous screen
// pass the data from the "pop" argument to the previous screen
Navigator.of(context).pop(_text);
},
child: Text('add list', style: TextStyle(color: Colors.white)),
),
),
const SizedBox(height: 8),
Container(
// expand to full width
width: double.infinity,
// cancel button
child: TextButton(
// what to do when the button is clicked
onPressed: () {
// "pop" to go back to the previous screen
Navigator.of(context).pop();
},
child: Text('cancel'),
),
),
],
),
)
);
}
}
```
### Things I've tried
I've enclosed the Widget in a SingleChildScrollView.
However, when I press the button, it goes blank.
So I created a DropdownButton in my app. The thing is that whenever I click the dropdown, the app crashes. I'm so confused because when I click other widgets like TextFormFields before clicking the DropdownButton it seems to work properly.
Error Message:
'package:flutter/src/material/dropdown.dart': Failed assertion: line 581 pos 12: 'menuHeight == menuBottom - menuTop': is not true.
Here's my DropdownButton:
import 'package:flutter/material.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(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DropDownTry(),
);
}
}
class DropDownTry extends StatefulWidget {
const DropDownTry({Key? key}) : super(key: key);
#override
_DropDownTryState createState() => _DropDownTryState();
}
class _DropDownTryState extends State<DropDownTry> {
String dropdownValue = 'Male';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
underline: SizedBox(),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: <String>['Male', 'Female']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
)),
),
);
}
}
Try below code hope its help to you try to remove const keyword for SizedBox Widget
Declare one String variable for default dropdown value
String? dropdownValue;
Your Dropdown Lists
List gender = [
'Male',
'Female',
'Other',
];
Your Dropdown Widget
DropdownButtonHideUnderline(
child: DropdownButton(
hint: Text(
'Select Gender',
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
textAlign: TextAlign.center,
),
value: dropdownValue,
onChanged: (String? genderNewValue) {
setState(
() {
dropdownValue = genderNewValue;
},
);
},
items: gender.map<DropdownMenuItem<String>>(
(value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(
fontSize: 15,
),
),
);
},
).toList(),
),
),
Your result screen:
I got same error. after struggling 2 days, I figured it out that the problem is about two factors. one is I used dropdown in showModalBottomSheet and second one is I didn't use appBar in scaffold where mydropdown located in. When i located my scaffold that contains my dropdown in, to another screen and add appBar. it worked perfectly.
Wrap your dropdown code in SingleChildScrollView.
ex.
return Scaffold(
body: SingleChildScrollView(
child:Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
underline: SizedBox(),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: <String>['Male', 'Female']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
)),
),
)
)
Mainly, don't make the DropDown very sticky to the top. It likes some space above.
Also, this happens due to the bad layout of the parent widgets.
Maybe u have made a column with a single child and this child is a stack and the crashed widget is inside the stack.
Try to make a clearer layout of the parent widgets.
also, put the main parent of the screen in a Material Widget.
The problem is caused because the framework can't calculate the heights beyond the menu.
I want to have a Settings screen where I can choose a color to be returned to the first screen.
I can't get the first screen to update when the Setting screen is closed.
I'm using the Provider as a change notifier. But I can't see how to trigger the update of the first screen. The third button creates an event which updates the screen, but can this be done automatically?
What am I missing...?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
Color bgColor = Colors.yellow[100];
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomeScreen());
}
}
class MyHomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: Consumer<ColorModel>(builder: (context, colorModel, child) {
return Scaffold(
appBar: AppBar(title: Text('Thanks for your help :)')),
body: Container(
constraints: BoxConstraints.expand(),
color: bgColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Change background color on this screen'),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Button1', style: TextStyle(color: Colors.white)),
onPressed: () {
var result = Navigator.push(
context, MaterialPageRoute(builder: (context) => Screen2()));
print('>>> Button1-onPressed completed, result=$result');
},
),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Choose a colour', style: TextStyle(color: Colors.white)),
onPressed: () {
asyncButton(context);
print('>>> Screen1 Button-onPressed completed');
},
),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Now try me', style: TextStyle(color: Colors.white)),
onPressed: () {
colorModel.notifyListeners();
},
),
],
),
),
);
}),
);
}
void asyncButton(BuildContext context) async {
var result = await Navigator.push(
context, MaterialPageRoute(builder: (context) => Screen2()));
print('>>> asyncButton completed: result = $result');
bgColor = result;
}
}
class ColorModel with ChangeNotifier {
void updateDisplay() {
notifyListeners();
}
}
class Screen2 extends StatelessWidget {
int _value;
List<String> names = ['Red', 'Green', 'Blue'];
List<Color> colors = [Colors.red[100], Colors.green[100], Colors.blue[100]];
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: Scaffold(
appBar: AppBar(
toolbarHeight: 80,
backgroundColor: Colors.blue,
title: Center(child: Text('Screen2')),
),
body: Container(
constraints: BoxConstraints.expand(),
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Consumer<ColorModel>(builder: (context, colorModel, child) {
return DropdownButton(
value: _value,
hint: Text("Select a color"),
focusColor: Colors.lightBlue,
onChanged: (int value) {
Navigator.pop(context, colors[value]);
},
items: [
DropdownMenuItem(value: 0, child: Text(names[0])),
DropdownMenuItem(value: 1, child: Text(names[1])),
DropdownMenuItem(value: 2, child: Text(names[2])),
],
);
}),
],
),
),
),
);
}
}
Navigator.push is tricky to use with Provider. It causes a lot of "Could not find the correct Provider above this Navigator Widget" errors. I've explained why in this answer to a related question.
Here's a quick overview of your situation:
Provider Scope
Architecture in question code:
MaterialApp
> provider(Screen A)
> provider(Screen B)
Architecture in solution below:
provider(MaterialApp)
> Screen A
> Screen B
Here's your code sample, shortened up, working with Provider, updating the background color on Page 1 from the Page 2.
I've put comments throughout the code to explain changes.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// - global var removed -
// Color bgColor = Colors.yellow[100];
void main() {
runApp(ProviderApp());
}
class ProviderApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
/// Define your Provider here, above MaterialApp
return ChangeNotifierProvider(
create: (context) => ColorModel(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: ScreenA()
),
);
}
}
class ScreenA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Thanks for your help :)')),
body: Container(
constraints: BoxConstraints.expand(),
//
// color: bgColor // - global var removed -
color: Provider.of<ColorModel>(context).bgColor,
// ↑ use your Provider state-stored value here ↑
//
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Change background color on this screen'),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child: Text('Go Screen B', style: TextStyle(color: Colors.white)),
// Navigator.push returns a Future, must async/await to use return value
onPressed: () async {
var result = await Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ScreenB()));
// note that this context is not Screen A context, but MaterialApp context
// see https://stackoverflow.com/a/66485893/2301224
print('>>> Button1-onPressed completed, result=$result');
},
),
],
),
),
);
}
}
/// This is your state object. Store your state here.
/// Create this once and use anywhere you need. Don't re-create this unless
/// you want to wipe out all state data you were holding/sharing.
class ColorModel with ChangeNotifier {
// color is the state info you want to store & share
Color bgColor = Colors.yellow[100]; // initialized to yellow
/// Update your state value and notify any interested listeners
void updateBgColor(Color newColor) {
bgColor = newColor;
notifyListeners();
}
/// - removed - replaced with updateBgColor ↑
/*void updateDisplay() {
notifyListeners();
}*/
}
class ScreenB extends StatelessWidget {
// all fields in StatelessWidgets should be final
//final int value; // this value isn't needed
final List<String> names = ['Red', 'Green', 'Blue'];
final List<Color> colors = [Colors.red[100], Colors.green[100], Colors.blue[100]];
#override
Widget build(BuildContext context) {
/// Instantiating your model & giving it to Provider to should only happen once per
/// Widget Tree that needs access to that state. e.g. MaterialApp for this solution
/// The state object & Provider below was repeated & has been commented out / removed.
/// This was wiping out any previously stored state and creating a new Provider / Inherited scope
/// to all children.
/*return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: ,
);*/
// - end of duplicate Provider removal -
return Scaffold(
appBar: AppBar(
title: Text('Screen2'),
),
body: Container(
alignment: Alignment.center,
child: Consumer<ColorModel>(builder: (context, colorModel, child) {
return DropdownButton(
//value: value, // this value isn't needed
hint: Text("Select a color"),
onChanged: (int value) {
colorModel.updateBgColor(colors[value]);
Navigator.pop(context, colors[value]);
},
items: [
DropdownMenuItem(value: 0, child: Text(names[0])),
DropdownMenuItem(value: 1, child: Text(names[1])),
DropdownMenuItem(value: 2, child: Text(names[2])),
],
);
}),
),
);
}
}