How can I repurpose boost button widgets in flutter? - flutter

I have a question here, I created an increase button widget in a separate file (component)...
increase_button_widget.dart
import 'package:flutter/material.dart';
class IncreaseButtonWidget extends StatefulWidget {
const IncreaseButtonWidget({super.key});
#override
State<IncreaseButtonWidget> createState() => _IncreaseButtonWidgetState();
}
class _IncreaseButtonWidgetState extends State<IncreaseButtonWidget> {
int _counterValue = 0;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return CounterButton(
loading: false,
onChange: (int val) {
setState(() {
_counterValue = val;
});
},
count: _counterValue,
countColor: Colors.blue,
buttonColor: Colors.blue,
progressColor: Colors.blue,
);
}
}
Here I will reuse it more than once in my application...
increase.dart
import 'package:increase/widgets/increase_button_widget.dart';
import 'package:flutter/material.dart';
class MyPassagerClassPage extends StatefulWidget {
const MyPassagerClassPage({super.key});
#override
State<MyPassagerClassPage> createState() => _MyPassagerClassPageState();
}
enum SingingCharacter { economy, business, first }
class _MyPassagerClassPageState extends State<MyPassagerClassPage> {
SingingCharacter? _character = SingingCharacter.economy;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Passager & Class"),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.check_outlined),
tooltip: 'Go to the next page',
onPressed: () {
Navigator.pop(context);
},
),
],
),
body: Column(
children: [
const SizedBox(height: 20),
const Text(
'Passengers',
style: TextStyle(fontSize: 30),
),
const ListTile(
leading: Icon(Icons.accessibility_outlined),
title: Text('Adults'),
subtitle: Text('12+ years'),
trailing: IncreaseButtonWidget(),
),
const ListTile(
leading: Icon(Icons.boy_outlined),
title: Text('Children'),
subtitle: Text('2-11 years'),
trailing: IncreaseButtonWidget(),
),
const ListTile(
leading: Icon(Icons.child_care_outlined),
title: Text('Infants'),
subtitle: Text('Under 2 years'),
trailing: IncreaseButtonWidget(),
),
const DividerWidget(),
const SizedBox(height: 25),
const Text(
'Class',
style: TextStyle(fontSize: 30),
),
ListTile(
title: const Text('Economy'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.economy,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
),
ListTile(
title: const Text('Business'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.business,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
),
ListTile(
title: const Text('First'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.first,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
),
const DividerWidget(),
],
),
);
}
}
In this case i used this widget 3 times...
My question is how to get the value of each of these increase buttons separately to be able to get them in a different variable...
Hence, in this case, each of these widgets has input data that I will need later to do another calculation.

Related

How to pass a entire list to a new page

I have been trying to pass a entire List to a new page but a receiver this error " Exception has occurred. RangeError (RangeError (index): Invalid value: Valid value range is empty: 0) ". I believe the problem is on the page that is sending the list, since the error is apparently because the list is empty, right?
This is the code of my page that a sending the List:
import 'package:flutter/material.dart';
import 'package:flutter_cont`enter code here`ador/main.dart';
import 'package:flutter_contador/view/LeitorEAN_View.dart';
import 'package:sqflite/sqflite.dart';
import 'package:flutter_contador/data/produto.dart';
class ListaDeProdutos extends StatefulWidget {
final Future<Database>? database;
const ListaDeProdutos({Key? key, this.database}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _ListaDeProdutosState();
}
}
class _ListaDeProdutosState extends State<ListaDeProdutos> {
List<Produto> listaproduto = List.empty(growable: true);
#override
void initState() {
fetchProdutos();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Produto'),
bottom: AppBar(
automaticallyImplyLeading: false,
elevation: 0,
title: Container(
width: double.infinity,
height: 40,
color: Colors.white,
child: const Center(
child: TextField(
// controller: _controller,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
// hintText: (Get.put(LeitorCodigoBarrasControle()).valorCodigoBarras),
hintText: ('Buscar...'),
),
),
),
),
),
),
body: ListView.builder(
itemCount: listaproduto.length,
itemBuilder: (context, index,) {
return Card(
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LeitorCodigoBarras(database: database, listaproduto: [],)),
);
}, // alterar quantidade do produto com leitor EAN
onLongPress: (){openUpdateProdutoView(index);}, // alterar quantidade do produto manualmente
// onLongPress: (){ deleteRecord(listaproduto[index]);}, // deletar o produto
leading: Text(listaproduto[index].codigo,style: const TextStyle(fontSize: 25)),
subtitle: Column(
children: [
Text(listaproduto[index].descricao,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16)
),
Text(listaproduto[index].codigoEAN,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16)),
],
),
trailing: Text(listaproduto[index].quantidade.toString(),style: const TextStyle(fontSize: 20)),
));
}),
);
}
void fetchProdutos() async {
final db = await widget.database;
final List<Map<String, dynamic>> maps =
await db!.query(Produto.tableName);
var list = List.generate(maps.length, (i) {
return Produto(
id: maps[i]['id'],
codigo: maps[i]['codigo'],
descricao: maps[i]['descricao'],
codigoEAN: maps[i]['codigoEAN'],
quantidade: maps[i]['quantidade'],
);
});
setState(() {
listaproduto.clear();
listaproduto.addAll(list);
});
}
// void deleteRecord(Produto produto) async {
// final db = await widget.database;
// db!.delete(Produto.tableName,
// where: 'id = ?', whereArgs: [produto.id]);
//
// fetchProdutos();
// }
void openUpdateProdutoView(int index) async {
bool doUpdate = await Navigator.pushNamed(context, "/updateProduto",
arguments: listaproduto[index]) as bool;
if (doUpdate) {
fetchProdutos();
}
}
}
This is the code of my page that a receiving the List:
import 'package:flutter/material.dart';
import 'package:flutter_contador/data/Produto.dart';
import 'package:scan/scan.dart';
import 'package:sqflite/sqflite.dart';
class LeitorCodigoBarras extends StatefulWidget {
const LeitorCodigoBarras(
{Key? key, required this.database, required this.listaproduto})
: super(key: key);
final Future<Database>? database;
final List<Produto> listaproduto;
#override
_LeitorCodigoBarrasState createState() => _LeitorCodigoBarrasState();
}
class _LeitorCodigoBarrasState extends State<LeitorCodigoBarras> {
List<Produto> listaproduto = List.empty(growable: true);
ScanController controller = ScanController();
var quantidadeEditController = TextEditingController();
var index = 0;
var quantidade = 0;
var scanResult = '';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 80,
title: const Text(
'Leitor EAN',
textAlign: TextAlign.center,
),
elevation: 0.0,
backgroundColor: const Color(0xFF333333),
leading: GestureDetector(
onTap: () => Navigator.of(context).pop(),
child: const Center(
child: Icon(
Icons.cancel,
color: Colors.white,
)),
),
actions: [
IconButton(
icon: const Icon(Icons.save),
onPressed: () {
}),
IconButton(
icon: const Icon(Icons.flashlight_on),
onPressed: () {
controller.toggleTorchMode();
})
],
),
body: Column(
children: [
SizedBox(
height: 400,
child: ScanView(
controller: controller,
scanAreaScale: .7,
scanLineColor: const Color.fromARGB(255, 51, 255, 0),
onCapture: (data) {
setState(() {
scanResult = data;
for (var i = 0; i < listaproduto.length; i++) {
if (listaproduto[i].codigoEAN == scanResult) {
index = i;
}else{
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text("Código EAN não encontrado.")));
}
}
});
controller.resume();
},
),
),
SingleChildScrollView(
child: ListTile(
title: Text(
'Produto ${widget.listaproduto[index].codigo}',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 40),
),
subtitle: Text(
'0000000',
textAlign: TextAlign.center,
),
),
),
const SizedBox(
child: ListTile(
title: Text(
'10',
textAlign: TextAlign.center,
),
leading: Icon(Icons.add),
trailing: Icon(Icons.remove),
),
),
],
),
);
}
}
You pass your list as an argument to a named route, but you do not take the argument anywhere on the page where you receive the list.
Inside your build add this to receive the list:
List<Produto> list = ModalRoute.of(context)!.settings.arguments as List<Produto>;
See here: https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments

How to make collapse paneItem in navigationpane in fluent ui in flutter

I am trying to do collapse paneItem in navigationpane after a lot of searcb and i didn't found anything about that if anyone used fluent ui with flutter and know how to do that it will be nice
That is mycode:
import 'dart:ui';
import 'package:fluent_ui/fluent_ui.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return FluentApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.dark,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
int _selectedindex = 0;
bool _visible = true;
TextEditingController search = TextEditingController();
final autoSuggestBox = TextEditingController();
final values = ['Blue', 'Green', 'Yellow', 'Red'];
String? comboBoxValue;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
void initState() {
search.text = 'Search';
super.initState();
}
#override
Widget build(BuildContext context) {
return NavigationView(
appBar: NavigationAppBar(
title: Text(widget.title),
),
pane: NavigationPane(
displayMode: PaneDisplayMode.compact,
onChanged: (newindex) {
setState(() {
_selectedindex = newindex;
});
},
footerItems: [
PaneItemSeparator(),
PaneItem(
icon: const Icon(FluentIcons.settings),
title: const Text('Settings'),
),
],
selected: _selectedindex,
autoSuggestBox: AutoSuggestBox(
controller: TextEditingController(),
placeholder: 'Search',
trailingIcon: Icon(FluentIcons.search),
items: const ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
),
autoSuggestBoxReplacement: const Icon(FluentIcons.search),
items: [
PaneItem(
icon: const Icon(FluentIcons.settings),
title: const Text('page 0')),
PaneItemHeader(header: Text('data')),
PaneItem(
icon: const Icon(FluentIcons.settings),
title: const Text('page 1')),
]),
content: NavigationBody(index: _selectedindex, children: [
ScaffoldPage(
padding: EdgeInsets.only(top: 0),
header: _visible
? InfoBar(
title: const Text('Update available'),
content:
const Text('Restart the app to apply the latest update.'),
severity: InfoBarSeverity.info,
onClose: () {
setState(() => _visible = false);
})
: null,
content: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 200,
child: AutoSuggestBox(
controller: autoSuggestBox,
items: const [
'Blue',
'Green',
'Red',
'Yellow',
'Grey',
],
onSelected: (text) {
print(text);
}),
),
SizedBox(
height: 20,
),
SizedBox(
width: 200,
child: Combobox<String>(
placeholder: Text('Selected list item'),
isExpanded: true,
items: values
.map((e) => ComboboxItem<String>(
value: e,
child: Text(e),
))
.toList(),
value: comboBoxValue,
onChanged: (value) {
// print(value);
if (value != null) setState(() => comboBoxValue = value);
},
),
),
SizedBox(
height: 20,
),
FilledButton(
style: ButtonStyle(
backgroundColor: ButtonState.all(Colors.blue)),
onPressed: () {
// showDialog(
// context: context,
// builder: (context) {
// return ContentDialog(
// title: Text('No WiFi connection'),
// content: Text('Check your connection and try again'),
// actions: [
// Button(
// child: Text('Ok'),
// onPressed: () {
// Navigator.pop(context);
// })
// ],
// );
// },
// );
},
child: const Icon(FluentIcons.add),
)
],
),
),
),
const ScaffoldPage(
header: PageHeader(
title: Text(
'Your Page 1',
textAlign: TextAlign.center,
)),
content: Center(child: Text('Page 1')),
),
const ScaffoldPage(
header: PageHeader(
title: Text(
'Your Page 2',
textAlign: TextAlign.center,
)),
content: Center(child: Text('Page 2')),
),
const ScaffoldPage(
header: PageHeader(
title: Text(
'Your Page 3',
textAlign: TextAlign.center,
)),
content: Center(child: Text('Page 3')),
),
]),
);
}
}
I am trying to do multi-level of paneItem in navigationpane in fluent ui in flutter but i don't know how to do that if anyone used fluent ui with flutter and know how to do that it will be nice

Flutter RadioListTile change Radio(icon) color

I have trouble changing Radio List Tile icon color.
I tried to use ListTileTheme but not worked.
By the way, I'm using RadioListTile in a dialog but I don't think that this affects it.
Code.
ListTileTheme(
iconColor: AppColors.green,
textColor: AppColors.green,
child: SimpleDialog(
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(10),
),
title: Text(
"Select Restaurant",
style: Theme.of(context)
.textTheme
.headline3,
textAlign:
TextAlign.center,
),
children: [
Divider(),
RadioListTile(
title: const Text(
'Name and Address'),
value: 1,
groupValue:
_isRadioSelected,
onChanged: (v) {
setState(() {
_isRadioSelected =
v;
});
},
),
],
),
);
Theme(
data: Theme.of(context).copyWith(
unselectedWidgetColor: Colors.green,
disabledColor: Colors.green
),
child: RadioListTile(
title: const Text('Name and Address'),
value: 1,
groupValue: _isRadioSelected,
onChanged: (v) {
setState(() {
_isRadioSelected = v;
});
},
),
)
Use Theme for change some theme param in current widget.
You can build a custom simple radio list widget by using the below code.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class GroupModel {
String text;
int index;
bool selected;
GroupModel({this.text, this.index, this.selected});
}
class MyApp extends StatefulWidget {
#override
_State createState() => new _State();
}
class _State extends State<MyApp> {
int _value2 = 0;
List<GroupModel> _group = [
GroupModel(text: "Item 1", index: 1, selected: true),
GroupModel(text: "Item 2", index: 2, selected: false),
GroupModel(text: "Item 3", index: 3, selected: false),
];
Widget makeRadioTileList() {
List<Widget> list = new List<Widget>();
for (int i = 0; i < _group.length; i++) {
list.add(new RadioListTile(
value: _group[i].index,
groupValue: _value2,
selected: _group[i].selected,
onChanged: (val) {
setState(() {
for (int i = 0; i < _group.length; i++) {
_group[i].selected = false;
}
_value2 = val;
_group[i].selected = true;
});
},
activeColor: Colors.purple,
controlAffinity: ListTileControlAffinity.trailing,
title: new Text(
' ${_group[i].text}',
style: TextStyle(
color: _group[i].selected ? Colors.black : Colors.grey,
fontWeight:
_group[i].selected ? FontWeight.bold : FontWeight.normal),
),
));
}
Column column = new Column(
children: list,
);
return column;
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('RadioListTile Example'),
),
body: new Container(
padding: new EdgeInsets.all(30.0),
child: new Center(
child: new Column(
children: <Widget>[makeRadioTileList()],
),
),
),
);
}
}

How to implement a Flutter Search App Bar

There are a lot of tutorials but rather than help me to move forward, I get lost in all possible options or I don't know how to improve the code (I would like to use an application that displays a list that use more than only the name of three fruits or three cities ?)
I found tutorials to create a nice SearchBar with the ability to display the result based on the first letters typed.
I don't understand how to edit the tutorial with a data list that includes a title associated with the content.
I don't understand how to display the result if the first letter is lowercase or uppercase.
Would it be possible to help me to make a simple basic code that could serve everyone including beginners like me?
DataList.dart
List<ListWords> listWords = [
ListWords('oneWord', 'OneWord definition'),
ListWords('twoWord', 'TwoWord definition.'),
ListWords('TreeWord', 'TreeWord definition'),
];
class ListWords {
String titlelist;
String definitionlist;
ListWords(String titlelist, String definitionlist) {
this.titlelist = titlelist;
this.definitionlist = definitionlist;
}
}
Searchbar.dart
import 'package:flutter/material.dart';
import 'package:test_searchbar/DataList.dart';
class SearchBar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search App'),
actions: <Widget>[
IconButton(icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch(listWords));
})
],
),
drawer: Drawer(),
);
}
}
class DataSearch extends SearchDelegate<String> {
final List<ListWords> listWords;
DataSearch(this.listWords);
#override
List<Widget> buildActions(BuildContext context) {
//Actions for app bar
return [IconButton(icon: Icon(Icons.clear), onPressed: () {
query = '';
})];
}
#override
Widget buildLeading(BuildContext context) {
//leading icon on the left of the app bar
return IconButton(
icon: AnimatedIcon(icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {
// show some result based on the selection
return Center(
child: Text(query),
);
}
#override
Widget buildSuggestions(BuildContext context) {
// show when someone searches for something
final suggestionList = query.isEmpty
? listWords
: listWords.where((p) => p.startsWith(query)).toList();
return ListView.builder(itemBuilder: (context, index) => ListTile(
onTap: () {
showResults(context);
},
trailing: Icon(Icons.remove_red_eye),
title: RichText(
text: TextSpan(
text: suggestionList[index].titlelist.substring(0, query.length),
style: TextStyle(
color: Colors.red, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: suggestionList[index].titlelist.substring(query.length),
style: TextStyle(color: Colors.grey))
]),
),
),
itemCount: suggestionList.length,
);
}
}
To create a search appbar, you will need a stateful widget with the following code,
Inside your State class,
TextEditingController _searchQueryController = TextEditingController();
bool _isSearching = false;
String searchQuery = "Search query";
Inside Scaffold, your appbar should be like,
appBar: AppBar(
leading: _isSearching ? const BackButton() : Container(),
title: _isSearching ? _buildSearchField() : _buildTitle(context),
actions: _buildActions(),
),
Define the required following methods for displaying and managing searchbar,
Widget _buildSearchField() {
return TextField(
controller: _searchQueryController,
autofocus: true,
decoration: InputDecoration(
hintText: "Search Data...",
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.white30),
),
style: TextStyle(color: Colors.white, fontSize: 16.0),
onChanged: (query) => updateSearchQuery(query),
);
}
List<Widget> _buildActions() {
if (_isSearching) {
return <Widget>[
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
if (_searchQueryController == null ||
_searchQueryController.text.isEmpty) {
Navigator.pop(context);
return;
}
_clearSearchQuery();
},
),
];
}
return <Widget>[
IconButton(
icon: const Icon(Icons.search),
onPressed: _startSearch,
),
];
}
void _startSearch() {
ModalRoute.of(context)
.addLocalHistoryEntry(LocalHistoryEntry(onRemove: _stopSearching));
setState(() {
_isSearching = true;
});
}
void updateSearchQuery(String newQuery) {
setState(() {
searchQuery = newQuery;
});
}
void _stopSearching() {
_clearSearchQuery();
setState(() {
_isSearching = false;
});
}
void _clearSearchQuery() {
setState(() {
_searchQueryController.clear();
updateSearchQuery("");
});
}
This is the best way to implement an app searchbar in any flutter screen.
Finally, I managed to do this. This is a good starting point for the Search Show in a list. Does this are correct?
DataList.dart
List<ListWords> listWords = [
ListWords('oneWord', 'OneWord definition'),
ListWords('twoWord', 'TwoWord definition.'),
ListWords('TreeWord', 'TreeWord definition'),
];
class ListWords {
String titlelist;
String definitionlist;
ListWords(String titlelist, String definitionlist) {
this.titlelist = titlelist;
this.definitionlist = definitionlist;
}
}
SearchBar.dart
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:test_searchbar/DataList.dart';
import 'package:test_searchbar/detail.dart';
class SearchBar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search App'),
actions: <Widget>[
IconButton(icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch(listWords));
})
],
),
body: Center(
child: Text('default content')
),
drawer: Drawer(),
);
}
}
class DataSearch extends SearchDelegate<String> {
final List<ListWords> listWords;
DataSearch(this.listWords);
#override
List<Widget> buildActions(BuildContext context) {
//Actions for app bar
return [IconButton(icon: Icon(Icons.clear), onPressed: () {
query = '';
})];
}
#override
Widget buildLeading(BuildContext context) {
//leading icon on the left of the app bar
return IconButton(
icon: AnimatedIcon(icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {
// show some result based on the selection
final suggestionList = listWords;
return ListView.builder(itemBuilder: (context, index) => ListTile(
title: Text(listWords[index].titlelist),
subtitle: Text(listWords[index].definitionlist),
),
itemCount: suggestionList.length,
);
}
#override
Widget buildSuggestions(BuildContext context) {
// show when someone searches for something
final suggestionList = query.isEmpty
? listWords
: listWords.where((p) => p.titlelist.contains(RegExp(query, caseSensitive: false))).toList();
return ListView.builder(itemBuilder: (context, index) => ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Detail(listWordsDetail: suggestionList[index]),
),
);
},
trailing: Icon(Icons.remove_red_eye),
title: RichText(
text: TextSpan(
text: suggestionList[index].titlelist.substring(0, query.length),
style: TextStyle(
color: Colors.red, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: suggestionList[index].titlelist.substring(query.length),
style: TextStyle(color: Colors.grey)),
]),
),
),
itemCount: suggestionList.length,
);
}
}
detail.dart
import 'package:flutter/material.dart';
import 'package:test_searchbar/DataList.dart';
class Detail extends StatelessWidget {
final ListWords listWordsDetail;
Detail({Key key, #required this.listWordsDetail}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
brightness: Brightness.dark,
title: const Text('Détail', style: TextStyle(color: Colors.white)),
iconTheme: IconThemeData(color: Colors.white),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(listWordsDetail.titlelist +' (on detail page)'),
Text(listWordsDetail.definitionlist),
],
),
)
);
}
}
It would be best if the return from the detail page opens the Searchbar page with the default content and the closed searchbar ...
There is a ready to use widget for this:
AppBar with search switch on pub.dev:
https://pub.dev/packages/app_bar_with_search_switch
appBar: AppBarWithSearchSwitch(
onChanged: (text) {
searchText.value = text;
}, // or use: onSubmitted: (text) => searchText.value = text,
appBarBuilder: (context) {
return AppBar(
title: Text('Example '),
actions: [
AppBarSearchButton(), // button to activate search
],
Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(93, 25, 72, 1),
toolbarHeight: 60.0,
title: TextField(
cursorColor: Colors.white,
decoration: InputDecoration(
hintText: " Search...",
border: InputBorder.none,
suffixIcon: IconButton(
icon: Icon(Icons.search),
color: Color.fromRGBO(93, 25, 72, 1),
onPressed: () {},
)),
style: TextStyle(color: Colors.white, fontSize: 15.0),
),
),
);

Dropdownbutton value in flutter not changing during onchange event

I am new to using a Dropdownbutton but I copied this code from a material example and the value is not changing when I pick a different category. Im not sure whats going on but the value changes internally when I debug but the displayed text stays at the default setting which is "Choose a goal category".
DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.check_circle_outline),
iconSize: 24,
elevation: 16,
style: TextStyle(
color: Colors.blue[300]
),
underline: Container(
height: 2,
color: Colors.blue[300],
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
updateCategory(newValue);
});
},
items: <String>['Choose a goal category', 'Financial', 'Physical', 'Family', 'Mental', 'Social', 'Spiritual', 'Personal']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
Replace this.
items : <String>['Choose a goal category', 'Financial', 'Physical', 'Family', 'Mental', 'Social', 'Spiritual', 'Personal']
.map((String dropDownStringItem){
return DropdownMenuItem<String>{
value : dropDownStringItem,
...
}
}).toList(),
I hope to help you
Step 1: declare String dropdownValue; do not set value
Step 2: use hint and set to Text('Choose a goal category')
Step 3: items remove string "Choose a goal category"
code snippet
String dropdownValue;
...
DropdownButton<String>(
hint: Text('Choose a goal category'),
value: dropdownValue,
icon: Icon(Icons.check_circle_outline),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.blue[300],
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'Financial', 'Physical', 'Family', 'Mental', 'Social', 'Spiritual', 'Personal'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String dropdownValue;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Center(
child: DropdownButton<String>(
//isDense: true,
hint: Text('Choose a goal category'),
value: dropdownValue,
icon: Icon(Icons.check_circle_outline),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.blue[300],
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'Financial', 'Physical', 'Family', 'Mental', 'Social', 'Spiritual', 'Personal'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
],
),
);
}
}