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
Related
I have the following code where i have buttons. i wpould like to get the numbers of the buttons to store the data and then also display the values on the screen in the text boxes in the order of them being inputted.
I will later on need to store the data in a DB when a user clicks next
How many numbers can be pressed will depend on a variable so it can vary between 1 and 12 numbers before hitting next.
I number which has been inputted should also be able to be changed. Should they then be a button aswell or how would i go about this?
THanks so much for the help
import 'package:flutter/material.dart';
import 'package:flutter_grid_button/flutter_grid_button.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(
// 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.purple,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required 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
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++;
});
}
Size screenSize(BuildContext context) {
return MediaQuery.of(context).size;
}
double screenHeight(BuildContext context, {double dividedBy = 1}) {
return screenSize(context).height / dividedBy;
}
double screenWidth(BuildContext context, {double dividedBy = 1}) {
return screenSize(context).width / dividedBy;
}
List<String> test =[];
#override
Widget build(BuildContext context) {
const textStyle = TextStyle(fontSize: 26);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('VIS Scoring'),
),
body: Builder(builder: (context) {
return Padding(
padding: EdgeInsets.only(top: 15, bottom: 0, left: 5, right: 5),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if(test == [])...[
Text("A is greater than 10"),
]else...[
Text("A is less than or Equal to 10")
],
Text(
"Hello World",
),
Text(
test.toString(),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Hello World",
),
Text(
"Hello World",
),
Text(
"Hello World",
),
],
),
Expanded(
//padding: const EdgeInsets.all(18.0),
child: GridButton(
textStyle: textStyle,
borderColor: Colors.grey[300],
borderWidth: 2,
onPressed: (dynamic val) {
test.add(val);
print(test);
// ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(
// content: Text(val.toString()),
// duration: Duration(milliseconds: 4000),
// ),
//
// );
},
items: [
[
GridButtonItem(
title: "9",
),
GridButtonItem(
title: "10",
),
GridButtonItem(
title: "X",
),
],
[
GridButtonItem(
title: "6",
),
GridButtonItem(
title: "7",
),
GridButtonItem(
title: "8",
),
],
[
GridButtonItem(
title: "3",
),
GridButtonItem(
title: "4",
),
GridButtonItem(
title: "5",
),
],
[
GridButtonItem(
title: "0",
),
GridButtonItem(
title: "1",
color: Colors.white,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
GridButtonItem(
title: "2",
color: Colors.white,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
],
[],
[
GridButtonItem(
title: "Back",
color: Colors.blue[900],
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
GridButtonItem(
title: "Next",
color: Colors.deepOrangeAccent,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
]
],
),
),
],
),
);
}),
),
);
}
}
You can use List and store data there - according to order of button beign pressed.
When you press button there should be some function which checks if button should be pressed or how many times. Maybe same as in 3)
When you put data into the list you can use SetState to update values in TextBoxes
I am trying to create a favorite button for my app. Which work is to change and save color, while the user presses it, So I decided to use hive db for it. When the icon button is tapped; the color get changed, which indicates to the user that it's been marked as their favorite. The problem is when I tap it again(if the user wants to unmark it ) though the color get changed ,when i move to other page or hot start/reload the page, the color changed back to it former self automatically(To the color when it was first pressed).I want the color reactive through the button and be saved. How can I solve this issue?(I am kinda confused at the key part. Maybe that's where the problem occurred)
class p1 extends StatefulWidget {
#override
_p1State createState() => _p1State();
}
class _p1State extends State<p1> {
Box box;
bool _isFavorite = false;
_p1State();
#override
void initstate(){
super.initState();
// Get reference to an already opened box
box = Hive.box(FAVORITES_BOX);
final data = box.get(_isFavorite).containskey("1" != null ? Colors.white:Colors.red );
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body:Stack(
children:<Widget>[
Image(
image:AssetImage("Image/Chowsun1.jpg"),
fit:BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Align(alignment: Alignment.center,
child: Text(' "\n The entire world , \n is not worth \n A single Tear.\n'
' " \n -Imam Hazrat Ali (R) '
,style: TextStyle(fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900 ) )
),
Stack ( children: [Positioned(
top:90,
right: 20,
child:const Text(' 1 ',
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
fontFamily: "Comforter"
),
),
)], ),
Align(
alignment: Alignment.bottomCenter,
child: (
IconButton(
icon: Icon(
Icons.favorite,
color:_isFavorite ? Colors.white: Colors.red
),
onPressed: () {
setState(() {
_isFavorite= !_isFavorite;
});
if(box.containsKey(1)){
box.delete(1);
}else
box.put(1, _isFavorite);
}
)
)
)])
),
);
}
}
I see you're using a bool _isFavorite to record a like, and then you check for the value of is favorite again to know if to give a like or remove the like, well under the hood your hive is working but basically, the code you're using to update the color is not coming from the hive so when you reupdate your state, e.g Hot Reload everything is reset to the initial leaving your favorite button unchanged.
You basically just need to re-model your logic for it to work properly.
import 'package:hive_flutter/hive_flutter.dart';
void main() async {
await Hive.initFlutter();
await Hive.openBox("favorites");
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Box? box = Hive.box("favorites");
bool _isFavorite = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Stack(
children: <Widget>[
Align(
alignment: Alignment.center,
child: Text(
' "\n The entire world , \n is not worth \n A single Tear.\n'
' " \n -Imam Hazrat Ali (R) ',
style: TextStyle(
fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900),
),
),
Stack(
children: [
Positioned(
top: 90,
right: 20,
child: const Text(
' 1 ',
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
fontFamily: "Comforter"),
),
)
],
),
Align(
alignment: Alignment.bottomCenter,
child: (IconButton(
icon: Icon(Icons.favorite,
color: box!.isEmpty ? Colors.white : Colors.red),
onPressed: () {
setState(() {
_isFavorite = !_isFavorite;
});
if (box!.isEmpty)
box!.put("isFavorite", _isFavorite);
else
box!.delete("isFavorite");
},
)),
)
],
),
),
);
}
}
You can directly initialize hive while it is already open
Box box = Hive.box(FAVORITES_BOX);
bool _isFavorite = false;
#override
void initState() {
super.initState();
_isFavorite = box.get(0) ?? false;
}
And changing value
onPressed: () {
setState(() {
_isFavorite = !_isFavorite;
});
box.put(0, _isFavorite);
},
I try create TextEditingController and send to this controller to my function and I want to use at buttononPressed method. When I click button and printed function variable it came empty map. How can I send controllers to other functions ?
Here is my code:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'funcs.dart';
class EmailRegister extends StatefulWidget {
EmailRegister() : super();
#override
_EmailRegisterState createState() => _EmailRegisterState();
}
class _EmailRegisterState extends State<EmailRegister> {
TextEditingController _email;
TextEditingController _pass;
TextEditingController _name;
var Controllers = new Map();
#override
void initState() {
_email = new TextEditingController();
_pass = new TextEditingController();
_name = new TextEditingController();
Controllers['email'] = _email;
Controllers['name'] = _name;
Controllers['pass'] = _pass;
super.initState();
}
#override
void dispose(){
_email.dispose();
_pass.dispose();
_name.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(height: 30),
CreateFormLabel("Email", 20, 20, false, _email),
const SizedBox(height: 20),
CreateFormLabel("UserName", 20, 20, false, _name),
const SizedBox(height: 20),
CreateFormLabel("Password", 20, 20, true, _pass),
const SizedBox(height: 20),
CreateFormButton(
"register",
18,
40.0,
10.0,
40.0,
10.0,
Colors.blue,
Colors.white,
Colors.white, Controllers),
],
),
),
);
}
}
and CreateFormButton code:
import 'package:flutter/material.dart';
Widget CreateFormLabel(
String text, double edgeInsetL, double edgeInsetR, bool obscureText, controller) {
return Container(
margin: EdgeInsets.only(right: edgeInsetR, left: edgeInsetL),
child: TextField(
obscureText: obscureText,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: text,
),
controller: controller,
),
);
}
Widget CreateFormButton(String text, double FontSize, double L, double T,
double R, double B, color, textClor, splashColor, controllers) {
return Center(
child: FlatButton(
onPressed: () {
print(controllers);
},
child: Text(
text,
style: TextStyle(fontSize: FontSize),
),
padding: EdgeInsets.fromLTRB(L, T, R, B),
color: color,
textColor: textClor,
splashColor: splashColor,
),
);
}
You can use Map<String, TextEditingController> Controllers = new Map();
code snippet
Widget CreateFormButton(
String text,
double FontSize,
double L,
double T,
double R,
double B,
color,
textClor,
splashColor,
Map<String, TextEditingController> controllers) {
return Center(
child: FlatButton(
onPressed: () {
print(Controllers['email'].text);
print(Controllers['name'].text);
print(Controllers['pass'].text);
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: EmailRegister(),
);
}
}
class EmailRegister extends StatefulWidget {
EmailRegister() : super();
#override
_EmailRegisterState createState() => _EmailRegisterState();
}
class _EmailRegisterState extends State<EmailRegister> {
TextEditingController _email;
TextEditingController _pass;
TextEditingController _name;
Map<String, TextEditingController> Controllers = new Map();
#override
void initState() {
_email = new TextEditingController();
_pass = new TextEditingController();
_name = new TextEditingController();
Controllers['email'] = _email;
Controllers['name'] = _name;
Controllers['pass'] = _pass;
super.initState();
}
#override
void dispose() {
_email.dispose();
_pass.dispose();
_name.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(height: 30),
CreateFormLabel("Email", 20, 20, false, _email),
const SizedBox(height: 20),
CreateFormLabel("UserName", 20, 20, false, _name),
const SizedBox(height: 20),
CreateFormLabel("Password", 20, 20, true, _pass),
const SizedBox(height: 20),
CreateFormButton("register", 18, 40.0, 10.0, 40.0, 10.0,
Colors.blue, Colors.white, Colors.white, Controllers),
],
),
),
);
}
Widget CreateFormLabel(String text, double edgeInsetL, double edgeInsetR,
bool obscureText, controller) {
return Container(
margin: EdgeInsets.only(right: edgeInsetR, left: edgeInsetL),
child: TextField(
obscureText: obscureText,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: text,
),
controller: controller,
),
);
}
Widget CreateFormButton(
String text,
double FontSize,
double L,
double T,
double R,
double B,
color,
textClor,
splashColor,
Map<String, TextEditingController> controllers) {
return Center(
child: FlatButton(
onPressed: () {
print(Controllers['email'].text);
print(Controllers['name'].text);
print(Controllers['pass'].text);
},
child: Text(
text,
style: TextStyle(fontSize: FontSize),
),
padding: EdgeInsets.fromLTRB(L, T, R, B),
color: color,
textColor: textClor,
splashColor: splashColor,
),
);
}
}
working demo
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.
);
}
}
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(),
),
),
),
],
),
),
);
}
}