Am new to flutter and am having issues giving same values to some of the dropdown items. Here is the code for the dropdown below
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 20.0, right: 5.0, top: 5.0),
child: new Container(
alignment: Alignment.center,
height: 40.0,
decoration: new BoxDecoration(
color: Colors.cyan,
borderRadius: new BorderRadius.circular(30.0)),
child: DropdownButton<int>(
items: [
DropdownMenuItem<int>(
child: Text('S&P500'),
value: 10,
),
DropdownMenuItem<int>(
child: Text('WS30'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('TV-NDX'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('AUS200'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('JS225'),
value: 100,
),
DropdownMenuItem<int>(
child: Text('UK100'),
value: 1,
),DropdownMenuItem<int>(
child: Text('FCH1'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('STOXX50E'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('GDAX'),
value: 1,
),DropdownMenuItem<int>(
child: Text('BITCOIN'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('ETHEREUM'),
value: 1,
),
DropdownMenuItem<int>(
child: Text('NGS'),
value: 1000,
),
DropdownMenuItem<int>(
child: Text('CRUDEOIL'),
value: 100,
),
DropdownMenuItem<int>(
child: Text('UKOIL'),
value: 100,
),
DropdownMenuItem<int>(
child: Text('SPX-NDX'),
value: 10,
),
DropdownMenuItem<int>(
child: Text('SMI'),
value: 1,
),
],
onChanged: (int value) {
setState(() {
asset = value;
});
},
hint: Text("TRADEVIEW",
style: new TextStyle(
fontSize: 15.0, color: Colors.black),),
value: asset,
),
),
),
),
You can use a class to hold name and value. so you can identify duplicate value with name
For demo only, I did not list all you data
code snippet
class Data {
String name;
int value;
Data({
this.name,
this.value,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
name: json["name"] == null ? null : json["name"],
value: json["value"] == null ? null : json["value"],
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
"value": value == null ? null : value,
};
}
List<Data> dataList = [
Data(name: 'CRUDEOIL', value: 100),
Data(name: "UKOIL", value: 100)
];
DropdownButton<Data>(
items: dataList.map<DropdownMenuItem<Data>>((Data value) {
return DropdownMenuItem<Data>(
value: value,
child: Text(value.name),
);
}).toList(),
onChanged: (Data value) {
setState(() {
asset = value;
print('${asset.name} ${asset.value}');
});
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
String name;
int value;
Data({
this.name,
this.value,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
name: json["name"] == null ? null : json["name"],
value: json["value"] == null ? null : json["value"],
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
"value": value == null ? null : value,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Data asset;
List<Data> dataList = [
Data(name: 'CRUDEOIL', value: 100),
Data(name: "UKOIL", value: 100)
];
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) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Padding(
padding:
const EdgeInsets.only(left: 20.0, right: 5.0, top: 5.0),
child: new Container(
alignment: Alignment.center,
height: 40.0,
decoration: new BoxDecoration(
color: Colors.cyan,
borderRadius: new BorderRadius.circular(30.0)),
child: DropdownButton<Data>(
items: dataList.map<DropdownMenuItem<Data>>((Data value) {
return DropdownMenuItem<Data>(
value: value,
child: Text(value.name),
);
}).toList(),
onChanged: (Data value) {
setState(() {
asset = value;
print('${asset.name} ${asset.value}');
});
},
hint: Text(
"TRADEVIEW",
style: new TextStyle(fontSize: 15.0, color: Colors.black),
),
value: asset,
),
),
),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Related
I want to create an evaluation app in flutter with multiple dropdownbuttons. The dropdownbuttons should contain a text with a value, for example: dropdownbutton1: "Text"; Value(2), dropdownbutton2: "Text"; Value2(4) and there is also an another button "evaluate", if i click on the "evaluate" button it should go to the next screen and the next screen displays the total of the value (it should be 6= value(2) + value2(4).
My next thought would be statemanagement, but i dont know how to do it right now.
I searched everywhere in the internet but couldnt find anything.
I am new to flutter. Is there a way to do it with statemanagement and how it could be look like?
Definitely you should implement a flavor of state management, both for the communication between the pages as well as to feed data to the dropdown menus, and holding on to the selected values from the dropdowns.
My suggestion would be to go with something as simple as the Provider state management strategy, and leverage the widgets that facilitate listening to changes occurring on the application. This strategy makes your app more decouples, maintains a clean separation of concerns and allows for good maintenance.
You can create a Provided service (i.e. DropdownService) that holds to the values of the dropdown menus as a list of dropdown options, as well as two properties that hold on to the selected values from the dropdowns (i.e. selectedFirstOption, selectedSecondOption). Upon triggering changes on both DropDownButton widgets, you can trigger a notification for the widget to rebuild itself, updating its selections, and holding on to the selected value.
A button will trigger the evaluation and navigation to the next page, only if both selectedFirstOption and selectedSecondOption are not null, then the next page also consumes the provided DropdownService, pulls the data persisted for both selections, add the values and displays it to the user.
I threw something together as an example to illustrate my point below:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => DropdownService()
)
],
child: MyApp()
)
);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<DropdownService>(
builder: (context, dropdownService, child) {
return Container(
padding: const EdgeInsets.all(30),
child: Column(
children: [
const Text('First dropdown:'),
DropdownButton<DropdownOption>(
value: dropdownService.selectedFirstOption,
icon: const Icon(Icons.arrow_drop_down),
elevation: 16,
onChanged: (DropdownOption? newValue) {
dropdownService.selectedFirstOption = newValue!;
},
items: dropdownService.firstDropdown.map((DropdownOption option) {
return DropdownMenuItem<DropdownOption>(
value: option,
child: Text(option.text!),
);
}).toList(),
),
const SizedBox(height: 20),
const Text('Second dropdown:'),
DropdownButton<DropdownOption>(
value: dropdownService.selectedSecondOption,
icon: const Icon(Icons.arrow_drop_down),
elevation: 16,
onChanged: (DropdownOption? newValue) {
dropdownService.selectedSecondOption = newValue!;
},
items: dropdownService.secondDropdown.map((DropdownOption option) {
return DropdownMenuItem<DropdownOption>(
value: option,
child: Text(option.text!),
);
}).toList(),
),
const SizedBox(height: 20),
Material(
color: Colors.amber,
child: TextButton(
onPressed: dropdownService.selectedFirstOption != null
&& dropdownService.selectedSecondOption != null ? () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => NextPage())
);
} : null,
child: const Text('Evaluate', style: TextStyle(color: Colors.black)
)
)
)
]
)
);
}
);
}
}
class NextPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
DropdownService dropdownService = Provider.of<DropdownService>(context, listen: false);
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('The result of ${dropdownService.selectedFirstOption!.text!} and ${dropdownService.selectedSecondOption!.text!}:'),
const SizedBox(height: 20),
Text('${dropdownService.selectedFirstOption!.value! + dropdownService.selectedSecondOption!.value!}',
style: const TextStyle(fontSize: 50)
),
],
),
),
);
}
}
class DropdownService extends ChangeNotifier {
List<DropdownOption> firstDropdown = [
DropdownOption(text: 'Value (5)', value: 5),
DropdownOption(text: 'Value (6)', value: 6),
DropdownOption(text: 'Value (7)', value: 7),
];
DropdownOption? _selectedFirstOption; // = DropdownOption(text: 'Select Value', value: -1);
DropdownOption? _selectedSecondOption; // = DropdownOption(text: 'Select Value', value: -1);
DropdownOption? get selectedFirstOption => _selectedFirstOption;
DropdownOption? get selectedSecondOption => _selectedSecondOption;
set selectedFirstOption(DropdownOption? value) {
_selectedFirstOption = value;
notifyListeners();
}
set selectedSecondOption(DropdownOption? value) {
_selectedSecondOption = value;
notifyListeners();
}
List<DropdownOption> secondDropdown = [
DropdownOption(text: 'Value (1)', value: 1),
DropdownOption(text: 'Value (2)', value: 2),
DropdownOption(text: 'Value (3)', value: 3),
];
}
class DropdownOption {
String? text;
double? value;
DropdownOption({ this.text, this.value });
}
If you run this code (also provided as a Gist) through DartPad.dev, you should see the following output:
EDIT: Im retarded, i figured it out
used the widget. to get access to the class variable
swapped out the Text("fsfd); for my list variable resulting in
child: Consumer<WidgetDataNotify>(
builder: (context,datatonotify,child){
print("value == ${datatonotify.value}");
return FuctionListSet[datatonotify.value];
},
child: Text("${provtest.value}"),
i've been following
Flutter provider state not updating in consumer widget
to try and understand the process along with the documentation and videos ect ect.
and i cannot figure out how to ensure im using the same instance of a provider across classes (dart files)
My program is composed of widgets and a radiolist that when it's clicked will update the provider to it's index value which then from a list in my main (thats wrapped) in a consumer will update depending on the interger affecting the list
provider file:
class WidgetDataNotify extends ChangeNotifier {
int value=0;
//int get grabvalue => value;
// Widget SelectedWidget=SingleButtonMovementFunction();
// Widget get pickedWidget =>SelectedWidget=FuctionListSet[value];
void UpdateWidgetList(int picker){
value = picker;
print("updated value to $value");
notifyListeners();
}
}
RadioList code: Problem here is i dont know how to communicate that provider value i've passed in
class RadioListBuilder extends StatefulWidget {
final int num;
static int value=0;
final WidgetDataNotify provider;
const RadioListBuilder({Key key, this.num,this.provider}) : super(key: key);
#override
RadioListBuilderState createState() {
return RadioListBuilderState();
}
}
class RadioListBuilderState extends State<RadioListBuilder> {
static int test;
int _value;
#override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) {
return Column(
children: [
Container(
height: 60,
width: MediaQuery.of(context).size.width,
color: Colors.brown[800],
child: RadioListTile(
selectedTileColor: Colors.amber,
activeColor: Colors.amber,
tileColor: Colors.black54,
value: index,
groupValue: _value,
onChanged: (x) => setState((){
_value = x;
///provider.UpdateWidgetList(x); /// providing the value to the provider
///ideally would call the function
Activated_Function_Selected=index;
print("Activated fuction is indexed at $Activated_Function_Selected and it's name is == ${FunctionList[index].characters}");
}),
title: Text("${FunctionList[index]}",style: TextStyle(color: Colors.white,fontSize: 18,),softWrap: true,maxLines: 2,),
),
),
Divider(color: Colors.black,height: 10,thickness: 10,),
],
);
},
itemCount: widget.num,
);
}
}
Start of my main function has this to ensure the context would be the same
#override
Widget build(BuildContext context) {
WidgetDataNotify provtest = Provider.of<WidgetDataNotify>(context,listen: true);
return Scaffold(
appBar: AppBar(
i pass this on into my radio list
Expanded(
flex:2 ,
child: Container(
color: Colors.deepPurple,
child: RadioListBuilder(num: FunctionList.length,provider: provtest,),
),
),
then i have my consumer listen out for it
Expanded(
flex: 3,
child: Container(
color: Colors.orangeAccent,
//
// child: Selector<WidgetDataNotify, int>(
// selector: (context,model) => model.value,
// builder: (context,value,child){
// print("accesed value==$value");
// return Center(
// child: FuctionListSet[value],
// );
// },
// child: Text("AAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
// ),
child: Consumer<WidgetDataNotify>(
builder: (context,datatonotify,child){
print("value == ${datatonotify.value}");
testA=datatonotify.value;
print("test == $testA");
return Text("faf");
},
child: Text("${provtest.value}"),
),
),
//),),
),
I am trying the code from this video: https://www.youtube.com/watch?v=4AUuhhSakro (or the github: https://github.com/khaliqdadmohmand/flutter_dynamic_dropdownLists/blob/master/lib/main.dart)
The issue is that when we (the viewers of the video) tries to "go back" to change the initial state (not app state, like county or province), the app crashes with this error:
There should be exactly one item with [DropdownButton]'s value: 14.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 827 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
I believe the problem is when the dropdown is built the first time, it can have a null string as the value parameter of the dropdown, but the second time around it crashes on the assert (if you set it to null you crash at value==null and if you don't reset the variable you are using for value then in the new dropdownlist this value is not in the items. (where the count has to be == 1)
This has been racking my brain in my own project too, I thought I had it working, but apparently it's still very much broken.
Flutter : I have error when work with tow dropdown button load one from another
This is a similar problem and that solution has an async in it (but this is simply not working for me).
You can copy paste run full code below
You can in onChanged add _myCity = null;
code snippet
onChanged: (String Value) {
setState(() {
_myState = Value;
_myCity = null;
_getCitiesList();
print(_myState);
});
},
working demo
full code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
_getStateList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dynamic DropDownList REST API'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
alignment: Alignment.topCenter,
margin: EdgeInsets.only(bottom: 100, top: 100),
child: Text(
'KDTechs',
style: TextStyle(fontWeight: FontWeight.w800, fontSize: 20),
),
),
//======================================================== State
Container(
padding: EdgeInsets.only(left: 15, right: 15, top: 5),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: _myState,
iconSize: 30,
icon: (null),
style: TextStyle(
color: Colors.black54,
fontSize: 16,
),
hint: Text('Select State'),
onChanged: (String Value) {
setState(() {
_myState = Value;
_myCity = null;
_getCitiesList();
print(_myState);
});
},
items: statesList?.map((item) {
return DropdownMenuItem(
child: Text(item['name']),
value: item['id'].toString(),
);
})?.toList() ??
[],
),
),
),
),
],
),
),
SizedBox(
height: 30,
),
//======================================================== City
Container(
padding: EdgeInsets.only(left: 15, right: 15, top: 5),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: _myCity,
iconSize: 30,
icon: (null),
style: TextStyle(
color: Colors.black54,
fontSize: 16,
),
hint: Text('Select City'),
onChanged: (String Value) {
setState(() {
_myCity = Value;
print(_myCity);
});
},
items: citiesList?.map((item) {
return DropdownMenuItem(
child: Text(item['name']),
value: item['id'].toString(),
);
})?.toList() ??
[],
),
),
),
),
],
),
),
],
),
);
}
//=============================================================================== Api Calling here
//CALLING STATE API HERE
// Get State information by API
List statesList;
String _myState;
String stateInfoUrl = 'http://cleanions.bestweb.my/api/location/get_state';
Future<String> _getStateList() async {
await http.post(stateInfoUrl, headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, body: {
"api_key": '25d55ad283aa400af464c76d713c07ad',
}).then((response) {
var data = json.decode(response.body);
// print(data);
setState(() {
statesList = data['state'];
});
});
}
// Get State information by API
List citiesList;
String _myCity;
String cityInfoUrl =
'http://cleanions.bestweb.my/api/location/get_city_by_state_id';
Future<String> _getCitiesList() async {
await http.post(cityInfoUrl, headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, body: {
"api_key": '25d55ad283aa400af464c76d713c07ad',
"state_id": _myState,
}).then((response) {
var data = json.decode(response.body);
setState(() {
citiesList = data['cities'];
});
});
}
}
I have created a GameBoard widget that I want to populate with 16 GameTile widgets that I have also created. For the purpose of the game the GameTile widgets are using the Positioned widget. How do I generate 16 tiles without having to type out each one?
Here is my GameBoard widget code:
return Container(
width: _myScreenWidth * 0.80,
height: _myScreenWidth * 0.80,
child: Stack(
children: [
List.generate(16, (index) {
return GameTile(value: tileValue[index], color: tileColor[index], x: tileXCoordinate[index], y: tileYCoordinate[index]);
}),
],
),
);
Here is my GameTile code:
return Positioned(
left: x,
bottom: y,
child: PhysicalModel(
borderRadius: BorderRadius.circular(10.0),
color: color,
child: Container(
width: _tileWidth,
height: _tileHeight,
child: Center(
child: Text(
value.toString(),
textAlign: TextAlign.center,
style: new TextStyle(
fontSize: _myScreenWidth * 0.07,
color: backgroundColor,
fontWeight: FontWeight.bold,
),
),
),
),
),
);
Any help is much appreciated.
Use a function and a List to store your generated widget
and display it with function
code snippet
List<Widget> getList() {
List<Widget> widgeList = [];
for (var i = 0; i < 10; i++) {
for (var item in widget.items) {
widgeList.add(Positioned(
left: item.x,
bottom: item.y,
child: PhysicalModel(
borderRadius: BorderRadius.circular(10.0),
color: Colors.blueAccent,
child: Container(
width: item.tileWidth,
height: item.tileHeight,
child: Center(
child: Text(
item.value,
textAlign: TextAlign.center,
style: new TextStyle(
//fontSize: _myScreenWidth * 0.07,
//color: backgroundColor,
fontWeight: FontWeight.bold,
),
),
),
),
),
));
}
}
return widgeList;
}
...
body: Stack(
children: getList(),
),
and your game class look like this, it just a demo I did not recreate all your attribute
class Game {
double x;
double y;
double tileWidth;
double tileHeight;
String value;
Game({
this.x,
this.y,
this.tileWidth,
this.tileHeight,
this.value,
});
factory Game.fromJson(Map<String, dynamic> json) => Game(
x: json["x"],
y: json["y"],
tileWidth: json["tileWidth"],
tileHeight: json["tileHeight"],
value: json["value"],
);
Map<String, dynamic> toJson() => {
"x": x,
"y": y,
"tileWidth": tileWidth,
"tileHeight": tileHeight,
"value": value,
};
}
full code
import 'package:flutter/material.dart';
import 'dart:convert';
void main() => runApp(MyApp());
List<Game> gameFromJson(String str) =>
List<Game>.from(json.decode(str).map((x) => Game.fromJson(x)));
String gameToJson(List<Game> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Game {
double x;
double y;
double tileWidth;
double tileHeight;
String value;
Game({
this.x,
this.y,
this.tileWidth,
this.tileHeight,
this.value,
});
factory Game.fromJson(Map<String, dynamic> json) => Game(
x: json["x"],
y: json["y"],
tileWidth: json["tileWidth"],
tileHeight: json["tileHeight"],
value: json["value"],
);
Map<String, dynamic> toJson() => {
"x": x,
"y": y,
"tileWidth": tileWidth,
"tileHeight": tileHeight,
"value": value,
};
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
static String data =
'[ {"x" : 1.0, "y" : 2.0, "tileWidth" : 100.0, "tileHeight" : 200.0, "value" : "test"}, {"x" : 10.0, "y" : 20.0, "tileWidth" : 100.0, "tileHeight" : 200.0, "value" : "test 2"} ] ';
List<Game> items = gameFromJson(data);
_MyHomePageState 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++;
});
}
List<Widget> getList() {
List<Widget> widgeList = [];
for (var i = 0; i < 10; i++) {
for (var item in widget.items) {
widgeList.add(Positioned(
left: item.x,
bottom: item.y,
child: PhysicalModel(
borderRadius: BorderRadius.circular(10.0),
color: Colors.blueAccent,
child: Container(
width: item.tileWidth,
height: item.tileHeight,
child: Center(
child: Text(
item.value,
textAlign: TextAlign.center,
style: new TextStyle(
//fontSize: _myScreenWidth * 0.07,
//color: backgroundColor,
fontWeight: FontWeight.bold,
),
),
),
),
),
));
}
}
return widgeList;
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Stack(
children: getList(),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
demo, Widget 2 is on top of Widget 1
enter code herehey all of master , i have code for filter data on api json, i want my user can select specific teacher by specific locatioin on drop down. the search by name are already work, but the dropdown i don't know how to implement it, to take effect on my json api slection.
here is my code
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
title: "Para Dai",
home: new DropDown(),
));
}
class DropDown extends StatefulWidget {
DropDown() : super();
// end
final String title = "DropDown Demo";
#override
DropDownState createState() => DropDownState();
}
class Province {
int id;
String name;
Province(this.id, this.name);
static List<Province> getProvinceList() {
return <Province>[
Province(1, 'Central Java'),
Province(2, 'East kalimantan'),
Province(3, 'East java'),
Province(4, 'Bali'),
Province(5, 'Borneo'),
];
}
}
// ADD THIS
class District {
int id;
String name;
District(this.id, this.name);
static List<District> getDistrictList() {
return <District>[
District(1, 'Demak'),
District(2, 'Solo'),
District(3, 'Sidoarjo'),
District(4, 'Bandung'),
];
}
}
class DropDownState extends State<DropDown> {
String finalUrl = '';
List<Province> _provinces = Province.getProvinceList();
List<DropdownMenuItem<Province>> _dropdownMenuItems;
Province _selectedProvince;
// ADD THIS
List<District> _disctricts = District.getDistrictList();
List<DropdownMenuItem<District>> _dropdownMenuDistricts;
District _selectedDistrict;
#override
void initState() {
_dropdownMenuItems = buildDropdownMenuItems(_provinces);
_dropdownMenuDistricts = buildDropdownDistricts(_disctricts); // Add this
_selectedProvince = _dropdownMenuItems[0].value;
_selectedDistrict = _dropdownMenuDistricts[0].value; // Add this
super.initState();
}
List<DropdownMenuItem<Province>> buildDropdownMenuItems(List provinceses) {
List<DropdownMenuItem<Province>> items = List();
for (var province in provinceses) {
items.add(
DropdownMenuItem(
value: province,
child: Text(province.name),
),
);
}
return items;
}
// ADD THIS
List<DropdownMenuItem<District>> buildDropdownDistricts(
List<District> districts) {
List<DropdownMenuItem<District>> items = List();
for (var district in districts) {
items.add(
DropdownMenuItem(
value: district,
child: Text(district.name),
),
);
}
return items;
}
onChangeDropdownItem(Province newProvince) {
// Add this
final String url =
'https://onobang.com/flutter/index.php?province=${newProvince.name}&district=${_selectedDistrict.name}';
setState(() {
_selectedProvince = newProvince;
finalUrl = url; // Add this
});
}
onChangeDistrict(District newDistrict) {
// Add this
final String url =
'https://onobang.com/flutter/index.php?province=${_selectedProvince.name}&district=${newDistrict.name}';
setState(() {
_selectedDistrict = newDistrict;
finalUrl = url; // Add this
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(
title: new Text("DropDown Button Example"),
),
body: new Container(
margin: const EdgeInsets.all(0.0),
padding: const EdgeInsets.all(13.0),
child: new Column(
children: <Widget>[
new Container(
margin: const EdgeInsets.all(0.0),
padding: const EdgeInsets.all(13.0),
decoration: new BoxDecoration(
border: new Border.all(color: Colors.blueGrey)),
child: new Text(
"Welcome to teacher list app, please select teacher by province / district and name"),
),
new Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Prov : "),
SizedBox(
height: 20.0,
),
DropdownButton(
value: _selectedProvince,
items: _dropdownMenuItems,
onChanged: onChangeDropdownItem,
),
SizedBox(
height: 20.0,
),
// Text('Selected: ${_selectedProvince.name}'),
// SizedBox(
// height: 20.0,
// ),
Text(" Dist : "),
SizedBox(
height: 20.0,
),
DropdownButton(
value: _selectedDistrict,
items: _dropdownMenuDistricts,
onChanged: onChangeDistrict,
),
SizedBox(
height: 20.0,
),
// Text('Selected: ${_selectedDistrict.name}'),
// SizedBox(
// height: 20.0,
// ),
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Text('$finalUrl'),
// ),
],
),
new Card(
child: new Center(
child: TextFormField(
decoration: InputDecoration(labelText: 'Teacher Name'),
))),
new FlatButton(
color: Colors.blue,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
padding: EdgeInsets.all(8.0),
splashColor: Colors.blueAccent,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondWidget(value:"$finalUrl"))
);
// what action to show next screen
},
child: Text(
"Show List",
),
),
],
),
),
),
);
}
}
// ignore: must_be_immutable
class SecondWidget extends StatelessWidget
{
String value;
SecondWidget({Key key, #required this.value}):super(key:key);
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(title: Text("Page 2"),),
body: Column(children: <Widget>[
Text("I wish Show JSON Mysql listview with this URL : "+this.value),
RaisedButton(child: Text("Go Back"),
onPressed: () {
Navigator.pop(context);
}),
],)
);
}
}
any help very thanks before iam a beginner in flutter, and very dificult to learn flutter
Edit
If you mean click Menu Item and change _buildSearchResults's content,
your _buildSearchResults is based on List _searchResult, modify content as you do in onSearchTextChanged will work. In RaisedButton, you can do this with onPressed
RaisedButton(
padding: const EdgeInsets.all(8.0),
textColor: Colors.white,
color: Colors.blue,
onPressed: (newDistrict) {
setState(() {
_myDistrict = newDistrict;
_searchResult.clear();
//recreate your _searchResult again.
});
},
child: new Text("Submit"),
)
onChanged: (newDistrict) {
setState(() {
_myDistrict = newDistrict;
_searchResult.clear();
//recreate your _searchResult again.
});
},
If I understand you clear, you are trying to create DropdownMenuItem via JSON string get from API.
JSON from different API, you can join them
List<Map> _jsonApi1 = [
{"id": 0, "name": "default 1"}
];
List<Map> _jsonApi2 = [
{"id": 1, "name": "second 2"},
{"id": 2, "name": "third 3"}
];
List<Map> _myJson = new List.from(_jsonApi1)..addAll(_jsonApi2);
Generate menuitem
new DropdownButton<String>(
isDense: true,
hint: new Text("${_jsonApi1[0]["name"]}"),
value: _mySelection,
onChanged: (String newValue) {
setState(() {
_mySelection = newValue;
});
print(_mySelection);
},
items: _myJson.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: new Text(
map["name"],
),
);
}).toList(),
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
List<Map> _jsonApi1 = [
{"id": 0, "name": "default 1"}
];
List<Map> _jsonApi2 = [
{"id": 1, "name": "second 2"},
{"id": 2, "name": "third 3"}
];
List<Map> _myJson = new List.from(_jsonApi1)..addAll(_jsonApi2);
class _MyHomePageState extends State<MyHomePage> {
String _mySelection;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Container(
height: 500.0,
child: new Center(
child: new DropdownButton<String>(
isDense: true,
hint: new Text("${_jsonApi1[0]["name"]}"),
value: _mySelection,
onChanged: (String newValue) {
setState(() {
_mySelection = newValue;
});
print(_mySelection);
},
items: _myJson.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: new Text(
map["name"],
),
);
}).toList(),
),
),
),
],
),
),
);
}
}