DropdownButton is not dropping down in my custom header in Flutter - flutter

I have a DropdownButton in my custom header widget that doesn't work. If I put the button in the content of the program it works fine, but not in the header. I get no errors.
This is the widget:
import 'package:flutter/material.dart';
class TestBar extends StatelessWidget {
const TestBar({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
height: 80.0,
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: const [
Text('Text', style: TextStyle(fontSize: 18.0),),
SizedBox(width: 20.0,),
DropTest(
items: [
'Collections',
'Item 1',
'Item 2',
'Item 3',
],
),
SizedBox(width: 20.0,),
Text('Text', style: TextStyle(fontSize: 18.0),),
SizedBox(width: 20.0,),
],
),
);
}
}
class DropTest extends StatelessWidget {
final List<String> items;
const DropTest({Key? key, required this.items}) : super(key: key);
#override
Widget build(BuildContext context) {
return DropdownButton(
value: items[0],
elevation: 0,
style: const TextStyle(fontSize: 18.0),
icon: const Icon(Icons.keyboard_arrow_down_outlined, size: 20,),
underline: Container(height: 0,),
items: items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(fontSize: 18.0),
),
);
}).toList(),
onChanged: (String? newValue) {
switch (newValue) {
case 'Cucine':
return _goToPath(cucineRoute);
case 'Bagni':
return _goToPath(bagniRoute);
case 'Living':
return _goToPath(livingRoute);
default:
return;
}
},
);
}
}
void _goToPath(String navigationPath) {
//navigation to a certain page;
}
And this is where I use the header widget:
import 'package:flutter/material.dart';
import 'package:responsive_builder/responsive_builder.dart';
import 'package:sito_woodandstone/settings/constants.dart';
import 'package:sito_woodandstone/widgets/navigation_bar/test_bar.dart';
class LayoutTemplate extends StatelessWidget {
final Widget child;
const LayoutTemplate({Key? key, required this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return ResponsiveBuilder(
builder: (context, sizingInformation) => Scaffold(
backgroundColor: colorBackground,
body: Column(
children: [
const TestBar(),
//NavBar(),
Expanded(
child: child,
),
],
),
),
);
}
}
This is where the LayoutTemplate is used in the main function
import 'package:flutter/material.dart';
import 'package:sito_woodandstone/locator.dart';
import 'package:sito_woodandstone/routing/rout_names.dart';
import 'package:sito_woodandstone/routing/router.dart';
import 'package:sito_woodandstone/services/navigation_serivice.dart';
import 'package:sito_woodandstone/views/layout_template/layout_template.dart';
void main() {
setupLocator();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Wood & Stone',
theme: ThemeData(
textTheme:
Theme.of(context).textTheme.apply(fontFamily: 'HeadingPro')),
builder: (context, child) => LayoutTemplate(child: child!),
navigatorKey: locator<NavigationService>().navigatorKey,
onGenerateRoute: generateRoute,
initialRoute: cucineRoute,
);
}
}
The Dropdown button below in the content is working but the one above is not image
I tried to remove the responsive builder but that is not the problem. I think there is something off in the main function, but I can't figure out what it is... Any ideas? Please help

Related

setState() or markNeedsBuild() called during build. (TextInputSettingsTile)

I'm new and I'm writing the settings section of my app in Flutter (I'm using this package: https://pub.dev/packages/flutter_settings_screens).
I get this error "setState() or markNeedsBuild() called during build." when the value of my TextInputSettingsTile changes.
I read a lot of information on the net but I still don't understand what is the problem.
This is my main.dart:
import 'package:flutter/material.dart';
import 'pages/home.dart';
import 'pages/settings_page.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
Future main() async {
await Settings.init(cacheProvider: SharePreferenceCache());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const LoginPage(title: 'TEST'),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<LoginPage> createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
final _username = TextEditingController();
final _password = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('TEST'),
actions: <Widget>[
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SettingsPage()),
);
},
icon: const Icon(Icons.settings))
],
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(
20, 0, 20, 10),
child: TextField(
controller: _username,
decoration: InputDecoration(
icon: const Icon(Icons.email),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'username'),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
20, 5, 20, 10),
child: TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
icon: const Icon(Icons.password_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'password'),
)),
ElevatedButton(
onPressed: () => {},
child: const Text('LOGIN'))
],
),
),
);
}
}
This is my settings general page:
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'settings/connection_page.dart';
class SettingsPage extends StatefulWidget {
#override
SettingsPageState createState() => SettingsPageState();
}
class SettingsPageState extends State<SettingsPage> {
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Settings')
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.all(12),
children: [
const SizedBox(height: 5,),
SettingsGroup(
title: 'GENERAL', children: const <Widget>[
ConnectionPage()
]
),
],
),
),
);
}
This is my settings specific page (where I'm getting the error):
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class ConnectionPage extends StatelessWidget {
const ConnectionPage({Key? key}) : super(key: key);
static const keyServer = 'key-server';
#override
Widget build(BuildContext context) => SimpleSettingsTile(
title: 'Connection',
subtitle: 'Parameters',
leading: const FaIcon(FontAwesomeIcons.clipboardList),
child: SettingsScreen(
title: 'Connection',
children: <Widget>[
buildServer(),
],
),
);
Widget buildServer() => TextInputSettingsTile(
settingKey: keyServer,
title: 'Server',
initialValue: ''
);
}
What can I do in order to fix this error?
Thank you all.
Some method underneath it is calling a setState during a build. Identify it and use the addPostFrameCallback method.
Example:
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'settings/connection_page.dart';
class SettingsPage extends StatefulWidget {
#override
SettingsPageState createState() => SettingsPageState();
}
class SettingsPageState extends State<SettingsPage> {
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Settings')
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.all(12),
children: [
const SizedBox(height: 5,),
WidgetsBinding.instance.addPostFrameCallback((_){
SettingsGroup(
title: 'GENERAL', children: const <Widget>[
ConnectionPage()
]),
});
],
),
),
);
}
Try verify as ths example. Try wrapping it into WidgetsBinding.instance.addPostFrameCallback((_)

I have a tab bar with 4 tabs, i wants to validate all the tabs data from main class? how to achieve it in flutter with Provider

Class A has 4 tabs, each tab has its own classes and fields, is there a elegant way to validate all the classes/tabs from Class A using Provider architecture.
Take a look at the official tutorial documentation. It's going to explain step by step how to create a model that shares states between other widgets.
I've also made the prototype below and a live demo on DartPad to help you out with your exact problem.
Data
A
B
Summary
No Data
With Data
Below is the code from DartPad as a minimum-reproducible-example. There is the Model provider where the data resides for every widget to access it. The classes A, B, and Summary each one consumes the Model data using the Consumer<Model>. Every time the Model changes it notifies all consumers (the listeners) of the change and then the widgets can be updated with the new data.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
enum BEnum {
test1,
test2,
}
class Model extends ChangeNotifier {
String _aText = '';
BEnum? _bEnum;
String get aText => _aText;
BEnum? get bEnum => _bEnum;
setText(String text) {
_aText = text;
notifyListeners();
}
setBEnum(BEnum? bEnum) {
_bEnum = bEnum;
notifyListeners();
}
}
void main() {
runApp(MultiProvider(providers: [
ChangeNotifierProvider(create: (_) => Model()),
], child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _selectedIndex = 0;
final _tabs = [
const A(),
const B(),
const Summary(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(24),
child: Center(child: _tabs[_selectedIndex]),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.abc), label: 'A'),
BottomNavigationBarItem(icon: Icon(Icons.bolt), label: 'B'),
BottomNavigationBarItem(icon: Icon(Icons.list), label: 'Summary'),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
}
class A extends StatelessWidget {
const A({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: [
const Text(
'A',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
Consumer<Model>(
builder: (context, model, child) {
return TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'A',
),
onChanged: (value) => model.setText(value),
);
},
)
],
);
}
}
class B extends StatelessWidget {
const B({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Consumer<Model>(
builder: (context, model, _) {
return Column(
children: [
const Text(
'B',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
Expanded(
child: ListView.builder(
itemCount: BEnum.values.length,
itemBuilder: (context, index) {
final bEnum = BEnum.values[index];
return RadioListTile<BEnum?>(
title: Text(bEnum.name),
groupValue: model.bEnum,
value: bEnum,
onChanged: (value) => model.setBEnum(value),
);
},
),
),
],
);
},
);
}
}
class Summary extends StatelessWidget {
const Summary({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Consumer<Model>(
builder: (context, model, _) {
return Column(
children: [
const Text(
'Summary',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
Row(
children: [
const Text('A text: ',
style: TextStyle(fontWeight: FontWeight.bold)),
Text(model.aText),
],
),
Row(
children: [
const Text('B selection: ',
style: TextStyle(fontWeight: FontWeight.bold)),
Text(model.bEnum?.name ?? 'None'),
],
),
],
);
},
);
}
}

Why is the refreshing pull in the App not working?

I'm building my app with Flutter 2.10.5 and Dart 2.16.2.
When i try to refresh the demo content whith a pull, nothing happens. I have multiple navigation routes for different content. So the demo is a litte bit complex.
The main.dart includes the basic code for the app. I use the NavDrawer Widget to build the different pages. Every route is defined in the navigation.dart file, which reference to the content widgets.
My code so far is:
import 'dart:core';
import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of the application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo Company',
theme: ThemeData(),
debugShowCheckedModeBanner: false,
home: const HomePage(title: 'Demo Company'),
);
}
}
class _HomePageState extends State<HomePage> {
#override
initState() {
super.initState();
}
Widget _infoTile(String title, String subtitle) {
return ListTile(
title: Text(title),
subtitle: Text(subtitle.isEmpty ? 'Not set' : subtitle),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: const NavDrawer(),
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
_infoTile('App name', 'Demo App....'),
// Multiple Liste Tiles...
],
),
),
);
}
}
//----------------------------------------------------------------------
// navigation.dart
//----------------------------------------------------------------------
class NavDrawer extends StatelessWidget {
const NavDrawer({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const <Widget>[
Text(
'Navigation',
style: TextStyle(color: Colors.white, fontSize: 30),
),
SizedBox(height: 30.0),
Text('Firstname', style: TextStyle(color: Colors.black, fontSize: 15)),
Text('Accountname', style: TextStyle(color: Colors.black, fontSize: 15)),
],
),
),
ListTile(
leading: const Icon(Icons.notifications),
title: const Text('Demo'),
onTap: () {
Navigator.push(
context,
Demo.route(),
);
},
),
// Multiple Navigation List Tiles...
],
),
);
}
}
//----------------------------------------------------------------------
// demo.dart
//----------------------------------------------------------------------
class HomePage extends StatefulWidget {
const HomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<HomePage> createState() => _HomePageState();
}
class Demo extends StatefulWidget {
const Demo({Key? key}) : super(key: key);
static Route route() {
return CupertinoPageRoute(builder: (_) => const Demo());
}
#override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
final _data = <WordPair>[];
#override
void initState() {
super.initState();
_data.addAll(generateWordPairs().take(20));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Woolha.com Flutter Tutorial'),
),
body: _buildList(),
);
}
Widget _buildList() {
return RefreshIndicator(
onRefresh: _refreshData,
child: ListView.builder(
padding: const EdgeInsets.all(20.0),
itemBuilder: (context, index) {
WordPair wordPair = _data[index];
return _buildListItem(wordPair.asString, context);
},
itemCount: _data.length,
),
);
}
Widget _buildListItem(String word, BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(word),
),
);
}
Future _refreshData() async {
await Future.delayed(const Duration(seconds: 3));
_data.clear();
_data.addAll(generateWordPairs().take(20));
setState(() {});
}
}
class ShowMessages extends StatelessWidget {
final String type;
final Color color;
const ShowMessages({Key? key, required this.type, required this.color}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView(
//color: color,
physics: const AlwaysScrollableScrollPhysics(),
children: [
ListTile(
title: Text(
type,
style: Theme.of(context).textTheme.bodyText1,
),
),
]);
}
}
Copy this code to DartPad
What is wrong?
Well for me this code... works
I copied it into Dartpad, then Dev Tools in browser (F12) > Device Emulation > Responsive. And you can use pull to refresh.
Of course this doesn't work using web view and mouse. I believe this gesture is not supported.

How to change variable with getx?

As in the codes I mentioned below, my question is actually simple, but I couldn't find a simple answer on the internet. All the sources I found are going through the same example. There is no simple explanation, but there is good stackoverflow. Let me ask my question without further ado.
I can specify a variable in getx and print that variable on other pages. What I want to do now is I want to change the getx variable in the main file, how can I do that?
I'm posting the wrong version of the code I want to do below for you to understand.
code in getx folder
class numcontroller extends GetxController {
var derece = 20.obs;
}
code is second page
numcontroller deneme = Get.put(numcontroller());
Container(
margin: const EdgeInsets.fromLTRB(27, 10, 0, 0),
child: Row(
children: [
Container(
margin: const EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text('${deneme.derece.value}',
style: const TextStyle(
fontSize: 45,
fontFamily: 'YesevaOne',
color: Color(0xFF2d4b70)),
),
),
The code I want to run in main.dart
derece = 20
or
derece = 30
When I change the degree manually on main.dart, I want it to change on the second page as well.
EDİTİNG
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:teemapp4/Controller/switch_controller.dart';
import 'routes/app_pages.dart';
import 'routes/app_routes.dart';
import 'themes/app_theme.dart';
//0xFF2d4b70
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: AppRoutes.DASHBOARD,
getPages: AppPages.list,
debugShowCheckedModeBanner: false,
theme: AppTheme.light,
darkTheme: AppTheme.dark,
themeMode: ThemeMode.system,
);
}
}
this is my main.dart code but i am using a bottombar i made with getx. I'm looking for how to change the data in that file through this code.
I don't think So you need to update your main.dart file.
You can add a button on your first page to update values like:
firstPage.dart
class FirstPage extends StatelessWidget {
FirstPage({Key? key}) : super(key: key);
NumController numController = Get.put(NumController());
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
numController.updateDerece(30);
},
child: Text(
"Update Value",
),
),
ElevatedButton(
onPressed: () {
Get.to(() => SecondPage());
},
child: Text("Go To Second Screen"),
),
],
),
),
);
}
}
secondPage.dart
class SecondPage extends StatelessWidget {
SecondPage({Key? key}) : super(key: key);
NumController numController = Get.find<NumController>();
#override
Widget build(BuildContext context) {
return Container(
child: Text(
numController.derece.toString(),
),
);
}
}
Or You can directly update the value on your second page like:
secondPage.dart
class SecondPage extends StatelessWidget {
SecondPage({Key? key}) : super(key: key);
NumController numController = Get.put(NumController());
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
//Any Number You can pass in Function
numController.updateDerece(30);
},
child: Text(
"Update Value",
),
),
Obx(
() => Container(
child: Text(
numController.derece.toString(),
),
),
),
],
),
),
);
}
}
numController.dart
import 'package:get/get.dart';
class NumController extends GetxController {
var _derece = 20.obs;
int get derece => _derece.value;
void updateDerece(int value) {
_derece.value = value;
}
}
Try using this way. And update your derece variable value using updateDerece method.
var _derece = 20.obs;
double get derece => _derece.value;
void updateDerece(double value) {
_derece.value = value;
}
////
Obx(() {
return Container(
margin: const EdgeInsets.fromLTRB(27, 10, 0, 0),
child: Row(
children: [
Container(
margin: const EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text(
'${deneme.derece}',
style: const TextStyle(
fontSize: 45,
fontFamily: 'YesevaOne',
color: Color(0xFF2d4b70)),
),
),
],
),
);
})

Failed assertion:'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) return item.value == value;}).length == 1'

class DropDown extends StatefulWidget {
const DropDown({
this.data,
this.hint,
Key key,
}) : super(key: key);
final List<String> data;
final String hint;
#override
_DropDownState createState() => _DropDownState();
}
String _chosenValue1;
class _DropDownState extends State<DropDown> {
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
width: 250,
padding: const EdgeInsets.all(0.0),
child: DropdownButton<String>(
iconSize: 30,
isExpanded: true,
value: _chosenValue1,
//elevation: 5,
items: widget.data.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
hint: Text(
widget.hint,
style: TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
onChanged: (String value) {
setState(() {
_chosenValue1 = value;
});
},
),
),
);
}
}
DropDown(
data: [
'Non-Blanchable',
'Partial thickness skin',
'Full thickness skin loss involving damage or necrosis',
'Obscured by necrosis'
],
hint: 'Assessment',
),
DropDown(
data: [
'Indistinct, diffuse,none ',
'Distinct,outline clearly'
],
hint: 'Assessment',
),
i have been stuck on this problem for a while now, When i have the same data inside the data it works however all the dropdown would become the same, I want to be able to have different data for different dropdown , but when i do so the error is caused and i cant figure out whats wrong with it
import 'package:flutter/material.dart';
class DropDown extends StatefulWidget {
DropDown({
this.data,
this.hint,
this.initialValue,
Key? key,
}) : super(key: key);
final List<String>? data;
final String? hint;
final String? initialValue;
String chosenValue1 = "";
#override
_DropDownState createState() => _DropDownState();
}
class _DropDownState extends State<DropDown> {
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
width: 250,
padding: const EdgeInsets.all(0.0),
child: DropdownButton<String>(
iconSize: 30,
isExpanded: true,
value: widget.initialValue!.isEmpty ? null : widget.initialValue!,
//elevation: 5,
items: widget.data!.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
hint: Text(
widget.hint!,
style: const TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
onChanged: (value) {
setState(() {
widget.chosenValue1 = value!;
});
},
),
),
);
}
}
import 'package:flutter/material.dart';
import 'dropdown.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: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropDown(
data: const [
'Non-Blanchable',
'Partial thickness skin',
'Full thickness skin loss involving damage or necrosis',
'Obscured by necrosis'
],
hint: 'Assessment',
initialValue: "Non-Blanchable",
),
DropDown(
data: const [
'Indistinct, diffuse,none',
'Distinct,outline clearly'
],
hint: 'Assessment',
initialValue: "",
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Use the above code it will fix ur error
I tried running your code and, after making your data and hint required params and moving the chosenValue variable inside your _DropDownState, it works perfectly fine. Can you maybe share some steps with how to reproduce the error that you're seeing, because I see two different dropdowns with values I can select independently of each other.
As per your description of how to reproduce the error, I've tried adding navigation between two screens, but it still all works as intended.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Dropdowns(),
);
}
}
class Dropdowns extends StatelessWidget {
const Dropdowns();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(40),
child: Column(
children: [
Text('This is the first screen'),
DropDown(
data: [
'Non-Blanchable',
'Partial thickness skin',
'Full thickness skin loss involving damage or necrosis',
'Obscured by necrosis'
],
hint: 'Assessment',
),
DropDown(
data: ['Indistinct, diffuse,none ', 'Distinct,outline clearly'],
hint: 'Assessment',
),
ElevatedButton(
child: Text('Go to second screen'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondScreen(),
),
);
},
),
],
),
),
);
}
}
class DropDown extends StatefulWidget {
const DropDown({
required this.data,
required this.hint,
Key? key,
}) : super(key: key);
final List<String> data;
final String hint;
#override
_DropDownState createState() => _DropDownState();
}
class _DropDownState extends State<DropDown> {
String? _chosenValue1;
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
width: 250,
padding: const EdgeInsets.all(0.0),
child: DropdownButton<String>(
iconSize: 30,
isExpanded: true,
value: _chosenValue1,
//elevation: 5,
items: widget.data.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
hint: Text(
widget.hint,
style: TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
onChanged: (String? value) {
setState(() {
_chosenValue1 = value;
});
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SECOND SCREEN'),
),
body: Padding(
padding: EdgeInsets.all(40),
child: Column(
children: [
Text('This is the second screen'),
DropDown(
data: [
'Non-Blanchable',
'Partial thickness skin',
'Full thickness skin loss involving damage or necrosis',
'Obscured by necrosis'
],
hint: 'Assessment',
),
DropDown(
data: ['Indistinct, diffuse,none ', 'Distinct,outline clearly'],
hint: 'Assessment',
),
],
),
),
);
}
}
onChanged: (String value) {
setState(() {
_chosenValue = value;
selcat = null; use dropdown as category
_chosenValue == null
? Container()
: _chosenValue == "hi"
? _hi()
: _chosenValue == "hello"
? _hello()
: Container(),