flutter update text on screen - flutter

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

Related

How to create a favorite buton in hive flutter?

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);
},

How to return Alert in widget in flutter

I'm trying to create a custom Alert dialogue using this package rflutter_alert . But when return the Alert it gives me this error
The argument type 'Future<bool?>' can't be assigned to the parameter type 'Widget?'.
Update:
here i created a custom widget of dialogue
class DialogueTwoButton extends StatelessWidget {
DialogueTwoButton(
{Key? key,
context,
required this.text1,
required this.text2,
required this.onpres1,
required this.onpress2})
: super(key: key);
final String text1;
final String text2;
final Function onpres1;
final Function onpress2;
#override
Widget build(BuildContext context) {
return _onAlertButtonsPressed(context, text1, text2, onpres1, onpress2);
}
var alertStyle = AlertStyle(
animationType: AnimationType.fromTop,
isCloseButton: false,
isOverlayTapDismiss: false,
descStyle: GoogleFonts.montserrat(color: Colors.black, fontSize: 18),
titleStyle: GoogleFonts.montserrat(
color: Colors.red,
),
);
_onAlertButtonsPressed(context, desc, title, onPressYes, onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
color: HexColor("#5344ed")),
DialogButton(
child: Text(
"No",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
and here is my other file where i'm creating a button
updateProduct() {
DialogueTwoButton(
onpres1: () {},
onpress2: () {},
text1: 'df',
text2: 'dsf',
);
bottomButton(context, () {
updateProduct();
}, "Update Product"),
and updateProduct(); on this mehtod calling the custom class dialogue, but it's not showing , i want to do this something in this way.
please help how to do this.
you missing one closing ) bracket after ).show()
_onAlertButtonsPressed(context,desc,title,onPressYes,onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
color: HexColor("#5344ed")),
DialogButton(
child: Text(
"No",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
Complete src code:
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(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: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _textEditingController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("title"),
),
body: Column(
children: [
InkWell(onTap: (){
_onAlertButtonsPressed(context,"test","title",(){},(){});
}, child: Text("test")),
],
),
);
}
}
_onAlertButtonsPressed(context,String desc,String title,onPressYes,onPressNo) {
return Alert(
context: context,
//style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
//style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
//color: HexColor("#5344ed")
),
DialogButton(
child: Text(
"No",
// style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
// color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
Try below code hope its helpful to you. remove Container and Widget
onAlertButtonsPressed(context, desc, title, onPressYes, onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
),
onPressed: onPressYes,
),
DialogButton(
child: Text(
"No",
),
onPressed: onPressNo,
)
],
).show();
}

How do you display a bunch of the same widget in Flutter?

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

how to filter json from dropdown in flutter

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(),
),
),
),
],
),
),
);
}
}

Dynamically add widgets to a column's children in flutter

I'm creating a quiz app and need to display mcq options dynamically based on how many options there are for a particular question.
So for example:
Now the code for the buttons is here :
final quizOptions = Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Column(
children: <Widget>[
SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(questions[questionNum].options[0],
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(questions[questionNum].options[1],
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
],
),
),
);
As you can see, what I am able to do is to "fix" 2 buttons. Is there a way to dynamically add buttons based on how many options there are for that particular question ?
I have a list named questions and it is a list of questions (which is a class):
class Question {
String title;
List options;
String imagePath;
Question(
{this.title, this.options, this.imagePath,});
}
//Example:
Question(
title: "How fast does the drone go ?",
options: ['80km/h', '90km/h', '100km/h'],
imagePath: "assets/images/drones1.jpg",
)
You should iterate through your options to create SimpleRoundButton
...................................
child: Column(
children: questions[questionNum].options.map<Widget>(
(option) => SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(option,
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
).toList(),
.........................
I made a complete example that I use dynamic widgets to show and hide widgets on screen, you can see it running online on dart fiddle, too.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List item = [
{"title": "Button One", "color": 50},
{"title": "Button Two", "color": 100},
{"title": "Button Three", "color": 200},
{"title": "No show", "color": 0, "hide": '1'},
];
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Dynamic Widget - List<Widget>"),backgroundColor: Colors.blue),
body: Column(
children: <Widget>[
Center(child: buttonBar()),
Text('Click the buttons to hide it'),
]
)
)
);
}
Widget buttonBar() {
return Column(
children: item.where((e) => e['hide'] != '1').map<Widget>((document) {
return new FlatButton(
child: new Text(document['title']),
color: Color.fromARGB(document['color'], 0, 100, 0),
onPressed: () {
setState(() {
print("click on ${document['title']} lets hide it");
final tile = item.firstWhere((e) => e['title'] == document['title']);
tile['hide'] = '1';
});
},
);
}
).toList());
}
}
Maybe it helps someone. If it was is useful to you, let me know clicking in up arrow, please. Thanks.
https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1