Hello friends I am creating learning app I need little help here I have array list when anyone click any word it goes to next sacreen user go to next sacreen instead user come back to pervious sacreen for next word I want user click on next button or pervious button to show next word pervious word on same sacreen.instead coming back to my previous word how it possible and remember array word must shown from right left because it an Hebrew language app here my image and code?
enter image description here
enter image description here
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'Sounds.dart';
class Kamiz extends StatefulWidget {
#override
_KamizState createState() => _KamizState();
}
class _KamizState extends State<Kamiz> {
var kamiz=['פָּרָ','חָםָ','נָבָּ','עָוָ','אָםָ','מָרָ','כָּכָּ','מָמָ','פָּפָּ','בָּרָ','קָרָ','דָּרָ','וָרָ','הָרָ','תָּרָ','בָּם','כָּלָ','כָּר','שָׁלָ','סָרָ','כָּכָּ','אָםָ','חָםָ','אָל','כָּלָ'];
var list=['57.wav','48.wav','47.wav','46.wav','45.wav','55.wav','54.wav','53.wav','51.wav','50.wav','60.wav','61.wav','58.wav',
'57.wav','61.wav','65.wav','64.wav','63.wav','62.wav','missing.wav','70.wav','69.wav','48.wav','67.wav','66.wav'
];
var urduvowel=['پارا','خاما','نابا','عاوا','آما','مارا','کاکا','ماما','پاپا','بارا','قارا','دارا','وارا','ہارا','تارا','باما',
'کالا','کارا','شالا','سارا','کاکا','آما','خاما','الا','کالا'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Kamatz',style:GoogleFonts.davidLibre(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
),
body: GridView.builder(
itemCount: kamiz.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5,
),
itemBuilder: (BuildContext context,int index){
return Padding(
padding:EdgeInsets.all(10.0),
child: GestureDetector(
onTap: () {
Navigator.push (
context,
MaterialPageRoute(builder: (context) => Sounds(kamiz[index],list[index],urduvowel[index])),
);
},
child: Container(
decoration: BoxDecoration(
color: Colors.black12,
border: Border.all(color: Colors.blueAccent)
),
child: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: [
Text(kamiz[index],style:GoogleFonts.davidLibre(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
Text(urduvowel[index],style:GoogleFonts.davidLibre(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
],
),
),
),
),
),
) ;
}
)
);
}
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_cache_manager_firebase/flutter_cache_manager_firebase.dart';
class Sounds extends StatefulWidget {
#override
_SoundsState createState() => _SoundsState();
String word;
var sounds;
var urdu;
Sounds(this.word,this.sounds,this.urdu);
}
class _SoundsState extends State<Sounds> {
final Completer<WebViewController> _controller = Completer<WebViewController>();
var audio;
AudioPlayer audioPlayer = AudioPlayer();
#override
void initState() {
super.initState();
audio='''
<!DOCTYPE html>
<html>
<body>
<audio id="englishAudio">
<source src="https://firebasestorage.googleapis.com/v0/b/hebrewapp-453d2.appspot.com/o/practicesounds%2F${widget.sounds}?alt=media&token=603fc7fc-6794-424d-84c6-3627d0d81d68" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button onclick="UrduAudio()" type="button">Listen Word</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>
<script>
var x = document.getElementById("englishAudio");
var y = document.getElementById("urduAudio");
function UrduAudio() {
x.play();
}
function englishAudio() {
y.play();
}
function pauseAudio() {
x.pause();
y.pause();
}
</script>
</body>
</html>
''';
}
#override
Widget build(BuildContext context) {
#override
String audioplay='''
<!DOCTYPE html>
<html>
<body>
<audio id="englishAudio">
<source src="https://firebasestorage.googleapis.com/v0/b/hebrewapp-453d2.appspot.com/o/practicesounds%2F${widget.sounds}?alt=media&token=603fc7fc-6794-424d-84c6-3627d0d81d68" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button onclick="UrduAudio()" type="button">Listen Word</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>
<script>
var x = document.getElementById("englishAudio");
var y = document.getElementById("urduAudio");
function UrduAudio() {
x.play();
}
function englishAudio() {
y.play();
}
function pauseAudio() {
x.pause();
y.pause();
}
</script>
</body>
</html>
''';
return Scaffold(
appBar: AppBar(
title: Text(
'Kamatz',style:GoogleFonts.davidLibre(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
widget.urdu+'/'+widget.word,style:GoogleFonts.davidLibre(
fontSize: 70,
)),
SizedBox(height: 30,),
Center(
child: Padding(
padding:EdgeInsets.only(left: 90),
child: Container(
constraints: BoxConstraints(maxHeight: 100,),
child: WebView(
initialUrl:Uri.dataFromString(audio, mimeType: 'text/html').toString(),
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
}, //
)
),
),
),
Padding(
padding:EdgeInsets.only(left: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('PERV'),
Icon(
Icons.arrow_left,
size: 70.0,
),
Icon(
Icons.arrow_right,
size: 70.0,
),
Text('Next'),
],
),
)
],
),
),
),
);
}
}
use - for previous and + for next
var kamiz=['פָּרָ','חָםָ','נָבָּ','עָוָ','אָםָ','מָרָ','כָּכָּ','מָמָ','פָּפָּ','בָּרָ','קָרָ','דָּרָ','וָרָ','הָרָ','תָּרָ','בָּם','כָּלָ','כָּר','שָׁלָ','סָרָ','כָּכָּ','אָםָ','חָםָ','אָל','כָּלָ'];
int index = 0;
int prev = kamiz[index-1];
int next = kamiz[index+1];
Make sure to check bounds.
Related
I have an app that pulls quotes from an api and displays it.
I am struggling to get my refresh button to work. When the refresh button is pressed a new quote should load.
The current code I have for the page is:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:share_plus/share_plus.dart';
import './Quote.dart';
class QuoteData extends StatefulWidget {
const QuoteData({Key? key}) : super(key: key);
#override
_QuoteDataState createState() => _QuoteDataState();
}
// call the API and fetch the response
Future<Quote> fetchQuote() async {
final response = await http.get(Uri.parse('https://favqs.com/api/qotd'));
if (response.statusCode == 200) {
return Quote.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load Quote');
}
}
class _QuoteDataState extends State<QuoteData>
with AutomaticKeepAliveClientMixin {
#override
bool get wantKeepAlive => true;
late Future<Quote> quote;
late Future<List<Quote>> wholeQuotes;
#override
void initState() {
super.initState();
quote = fetchQuote();
}
#override
Widget build(BuildContext context) {
super.build(context);
return FutureBuilder<Quote>(
future: quote,
builder: (context, snapshot) {
if (snapshot.hasData) {
return SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: const EdgeInsets.only(left: 50.0),
child: Text(
snapshot.data!.quoteText,
style: const TextStyle(
fontSize: 30.0,
color: Colors.white,
fontFamily: 'quoteScript'),
),
),
const SizedBox(
height: 20.0,
),
Text(
'-${snapshot.data!.quoteAuthor}-',
style: const TextStyle(
fontSize: 23.0,
color: Colors.white,
fontFamily: 'quoteScript'),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//share button
IconButton(
icon: const Icon(
Icons.share,
color: Colors.white,
),
onPressed: () {
Share.share(
'${snapshot.data!.quoteText}--${snapshot.data!.quoteAuthor}');
},
),
//refresh button
IconButton(
icon: const Icon(
Icons.share,
color: Colors.white,
),
onPressed: () {
fetchQuote();
},
),
],
),
],
),
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return const Center(child: CircularProgressIndicator());
},
);
}
}
How can I get the refresh button to refresh the page and load a new quote from the api and display it?
Any help would be appreciated.
Reset future using setState.
Future<Quote> quote;
...
IconButton(
...
onPressed: () {
setState(() {
quote = fetchQuote();
});
},
)
Did you try to use setState under onPressed()? You can do something like:
onPressed: () {
setState(()
Share.share(
'${snapshot.data!.quoteText}--${snapshot.data!.quoteAuthor}');
)},
For instance: I have a main Icon so when you click on it, it opens a pop-up window with smaller icons/images to select from. So if you select one of the pictures from that pop-up it replaces the main Icon to that specific image.
I have spent hours trying to figure out how to replace icon images but nothing seems to work.
I have created an example (I have used flutter_speed_dial to make expandable buttons but it's not necessary). You can adjust it to your needs:
class _TestState extends State<Test> {
var fabIcon = Icons.expand_less;
var button1Icon = Icons.home;
var button2Icon = Icons.shop;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: SpeedDial(
icon: fabIcon,
backgroundColor: Color(0xFF801E48),
visible: true,
curve: Curves.bounceIn,
children: [
// FAB 1
SpeedDialChild(
child: Icon(button1Icon),
backgroundColor: Color(0xFF801E48),
onTap: () {
var temp = fabIcon;
setState(() {
fabIcon = button1Icon;
button1Icon = temp;
});
},
labelStyle: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
fontSize: 16.0),
labelBackgroundColor: Color(0xFF801E48)),
// FAB 2
SpeedDialChild(
child: Icon(button2Icon),
backgroundColor: Color(0xFF801E48),
onTap: () {
var temp = fabIcon;
setState(() {
fabIcon = button2Icon;
button2Icon = temp;
});
},
labelStyle: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
fontSize: 16.0),
labelBackgroundColor: Color(0xFF801E48))
],
),
),
);
}
}
Using showDialog(...) is the solution.
Hope this will help you and others.
you can look at this example:
import 'package:flutter/material.dart';
class IconDialogScreen extends StatefulWidget {
const IconDialogScreen({Key? key}) : super(key: key);
#override
State<IconDialogScreen> createState() => _IconDialogScreenState();
}
class _IconDialogScreenState extends State<IconDialogScreen> {
IconData icon = Icons.abc;
List<IconData> icons = [
Icons.abc,
Icons.person_add,
Icons.person,
Icons.person_remove,
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: TextButton(
onPressed: onIconClicked,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 20,
children: [Icon(icon, size: 50), const Text("change icon")],
),
),
)
],
),
);
}
void onIconClicked() async {
IconData? _icon = await showDialog<IconData?>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Select one icon'),
content: Wrap(
spacing: 10,
runSpacing: 10,
children: icons.map<Widget>((e) {
return ElevatedButton(
onPressed: () {
Navigator.of(context).pop(e);
},
child: Icon(e, size: 50));
}).toList(),
),
);
},
);
if (_icon != null) {
setState(() {
icon = _icon;
});
}
}
}
Hi guys I'm new in flutter and need your help. In this case, i'm able to add the budget and retrieve it to list view. but now I'm trying show only 1 list for each category but count for the amount? so if the user add the new budget, the amount will be count and updated to the list view (with the same currency). Anyone can help me how to list the the same category but with updated amount if the user add the budget in the budget code? Please help. Thank you. For the database, I'm using Firestore in the firebase
choose budget category
import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/detail.dart';
import 'package:monger_app/theme/colors.dart';
class BudgetSettings extends StatefulWidget {
#override
_BudgetSettingsState createState() => _BudgetSettingsState();
}
class _BudgetSettingsState extends State<BudgetSettings> {
List<Container> categorylist = new List();
var character=[
{"name":"Food", "image":"food.png"},
{"name":"Social-Life", "image":"travel.png"},
{"name":"Transportation", "image":"transportation.png"},
{"name":"Beauty", "image":"makeup.png"},
{"name":"Household", "image":"household.png"},
{"name":"Education", "image":"education.png"},
{"name":"Health", "image":"health.png"},
{"name":"Gift", "image":"gift.png"},
{"name":"Other", "image":"other.png"},
];
_makelist() async {
for (var i = 0; i < character.length; i++) {
final newcharacter = character[i];
final String image = newcharacter["image"];
categorylist.add(
new Container(
padding: new EdgeInsets.all(20.0),
child: new Card( child:
SingleChildScrollView(
child: new Column(
children: <Widget>[
new Hero(
tag: newcharacter['name'],
child: new Material(
child: new InkWell(
onTap: ()=> Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context)=> new Detail(name: newcharacter['name'], image: image,),
)),
child:
new Image.asset("assets/$image", fit: BoxFit.contain,),
)
),
),
//new Image.asset('assets/$image', fit: BoxFit.cover,),
new Padding(padding: new EdgeInsets.all(5.0),),
new Text(newcharacter['name'], style: new TextStyle(fontSize: 18.0),),
],
),
),
),
),
);
}
}
#override
void initState() {
_makelist();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: primary,
title: Text(getTranslated((context), "budget_settings"),
),),
body: new GridView.count(
crossAxisCount: 2,
children: categorylist,
),
);
}
}
Add budget code
import 'package:dropdownfield/dropdownfield.dart';
import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/account.dart';
import 'package:monger_app/page/budgetsettings.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Detail extends StatefulWidget {
Detail({this.name, this.image});
final String name;
final String image;
#override
_DetailState createState() => _DetailState();
}
class _DetailState extends State<Detail> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text(getTranslated((context), "budget_settings"),),
elevation: 0,
brightness: Brightness.light,
backgroundColor: primary,
leading: IconButton(
onPressed: (){
Navigator.pop(context, MaterialPageRoute(builder: (context) => Account()));
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: new ListView(
children: <Widget>[
new Container(
height: 250.0,
child:
new Hero(tag: widget.name,
child: new Material(
child: new InkWell(
child: new Image.asset("assets/${widget.image}", fit: BoxFit.contain,),
)
))
),
new Name(name: widget.name,),
],
),
);
}
}
class Name extends StatefulWidget {
Name({this.name});
final String name;
#override
_NameState createState() => _NameState();
}
class _NameState extends State<Name> {
#override
String selectCurrency;
final currencySelected = TextEditingController();
var _formKey = GlobalKey<FormState>();
List <String> currencycategories = [
"IDR",
"MYR",
"USD",
"CNY"
];
Widget build(BuildContext context) {
final amount = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
CollectionReference collect= firestore.collection("Budget");
final FirebaseAuth _auth = FirebaseAuth.instance;
final User user =_auth.currentUser;
final uid = user.uid;
return Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Container(
child: Center(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: Text(
widget.name,
textAlign: TextAlign.center,
style: new TextStyle(
fontSize: 25.0,
color: primary,
fontWeight: FontWeight.bold,
),
),
),
Row(
children: <Widget> [
new Expanded(child: new DropDownField(
controller: currencySelected,
labelText: getTranslated((context), "currency_hint"),
enabled: true,
itemsVisibleInDropdown: 4,
items: currencycategories,
onValueChanged: (dynamic value) {
selectCurrency = value;
},
value: selectCurrency,
required: false,
),
flex: 2,
),
new SizedBox(
width: 10.0,
),
new Expanded(child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Please fill up the text fields';
},
controller: amount,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: getTranslated((context), "budget_enter"),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: secondary),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
),
flex: 2,
)],
),
Padding(
padding: EdgeInsets.all(20.0),
child: ElevatedButton(
onPressed: () async {
final FirebaseAuth _auth = FirebaseAuth
.instance;
final User user = _auth.currentUser;
final uid = user.uid;
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
collect.add({
'name': this.widget.name,
'currency': selectCurrency,
'amount': amount.text,
});
amount.text = "";
Navigator.pop(context);
},
child: Text(getTranslated((context), "save_button").toUpperCase(), style: TextStyle (
fontSize: 14,
)),
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20.0)),
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
side: BorderSide(color: secondary)
),
),
),
),
)
],
),
)
)
],
),
)
);
}
}
Retrieve it to list view code
import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/transaction.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import './transaction.dart' as expense;
import './transaction.dart' as income;
class TransactionMonthly extends StatefulWidget {
#override
_TransactionMonthlyState createState() => _TransactionMonthlyState();
}
class _TransactionMonthlyState extends State<TransactionMonthly> with SingleTickerProviderStateMixin {
TabController controller;
#override
void initState() {
controller = new TabController(vsync: this, length: 2);
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(getTranslated(context, 'budget_title'),),
elevation: 0,
brightness: Brightness.light,
backgroundColor: primary,
leading: IconButton(
onPressed: (){
Navigator.pop(context, MaterialPageRoute(builder: (context) => Transactions()));
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('Budget').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return ListView(
children: snapshot.data.docs.map((document) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
SizedBox(width: 10,),
Text(document.get('name'),style: TextStyle(fontSize: 16,
color: primary,
fontWeight: FontWeight.w600
),),
],
),
SizedBox(height: 10,),
Row(children: [
SizedBox(width: 10,),
Text(document.get('currency'),style: TextStyle(fontSize: 16,
color: primary,
fontWeight: FontWeight.w600
),),
SizedBox(width: 10,),
Text(document.get('amount'),style: TextStyle(fontSize: 16,
color: primary,
fontWeight: FontWeight.w600
),),
],
),
SizedBox(height: 8,),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: (){
Widget cancelButton = FlatButton(child: Text("Cancel"),
onPressed: (){
Navigator.pop(context);
},
);
Widget deleteButton = FlatButton(child: Text("Delete"),
onPressed: (){
FirebaseFirestore.instance.collection('Budget').doc(document.id).delete();
Navigator.pop(context);
},
);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Delete Budget'),
content: Text('Are you sure want to delete it?'),
actions: [
cancelButton,
deleteButton,
],
),
);
//_showDeleteDialog();
//_showDeleteDialog(document: document);
},
child: Row(
children: [
Icon(Icons.delete_forever_outlined,
color: Colors.red,
),
SizedBox(width: 6,),
Text('Delete', style: TextStyle(fontSize: 16,
color: Colors.red,
fontWeight: FontWeight.w600
), ),
],
),
)
],
)
],)
);
}).toList(),
);
}
return Center(
child: CircularProgressIndicator(),
);
}
),
);
}
}
I think what you want is a sort of group by name so that you show the food category with 160 in your example instead of two times the same category (Correct me if i am wrong). What i suggest is to first create a class named Budget with your three attributes name, currency and amount. When you receive your data in TransactionMonthly Streambuilder you need to group your snapshot data by name. Once you done that you create a list of budgets List<Budget> budgets so that you add the sum of amount per name of budgets.
Here is a sample code that you can use, you can simply copy paste it and try on DartPad by yourself:
import 'package:collection/collection.dart';
//DATA coming from your Firebase collection
Map<String, dynamic> data1 = {
'name':"Food",
'currency': "IDR",
'amount': 100,
};
Map<String, dynamic> data2 = {
'name':"Food",
'currency': "IDR",
'amount': 60,
};
Map<String, dynamic> data3 = {
'name':"Beauty",
'currency': "USD",
'amount': 120,
};
//Your Budget class
class Budget{
String currency;
String name;
int amount;
#override
String toString(){
return "Budget: {currency: $currency, name: $name, amount: $amount}";
}
Budget({required this.currency, required this.name, required this.amount});
}
void main(){
List<Map<String, dynamic>> snapshot = [data1, data2, data3];
List<Budget> budgets = [];
//you group your budgets by name so you will have: {'Food': [data1, data2], 'Beauty':[data3]}
final groupByName = groupBy(snapshot, (Map<String, dynamic> doc)=>doc['name']);
print(groupByName);
int totalAmount = 0;
String currency = "";
groupByName.forEach((name, value){
//because we grouped by name every value will have same currency
currency = value[0]['currency'];
//Here we calculate the sum of all Food
totalAmount = value.map((e)=>e['amount']).reduce((v, e)=> v+e);
budgets.add(Budget(currency: currency, amount: totalAmount, name: name));
});
//budgets is your final list to use in your listView
print(budgets);
}
I'm trying to use provider in my flutter app to allow the user to change the font size for some widgets.
I'm following the method described in github.com/flutter/samples/blob/master/provider_counter/lib/main.dart but the font size isn't changing.
I have a UI widget which shows plus and minus buttons:
import "package:flutter/material.dart";
import './size_controller.dart';
import 'package:provider/provider.dart';
class TypeSize extends StatelessWidget {
final _standardSize = 20.0;
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(20.0),
child: Row(
children: <Widget>[
Text(
"Change type size: ",
style: TextStyle(fontSize: _standardSize),
),
ButtonTheme(
minWidth: 50,
child: RaisedButton(
onPressed: () {
if (_standardSize < 23.0) {
Provider.of<FontSizeController>(context, listen: false).increment(_standardSize);
}
},
child: Text(
"+", style: TextStyle(
color: Colors.white,
fontSize: 30),
),
color: Colors.green,
),
),
ButtonTheme(
minWidth: 50,
child: RaisedButton(
onPressed: () {
if (_standardSize > 20.0) {
Provider.of<FontSizeController>(context, listen: false).decrement(_standardSize);
}
},
child: Text(
"-", style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
color: Colors.green,
),
),
],
),
);
}
}
FontSizeController looks like this:
import 'package:flutter/material.dart';
class FontSizeController with ChangeNotifier {
double value = 20.0;
void increment(value) {
value ++;
notifyListeners();
}
void decrement(value) {
value --;
notifyListeners();
}
}
and finally the widget that I want to change looks like this:
import 'package:flutter/material.dart';
// import 'package:wfa_ambo_bloc/main.dart';
import 'package:provider/provider.dart';
import '../controllers/size_controller.dart';
class Comfort extends StatefulWidget {
#override
_ComfortState createState() => _ComfortState();
}
class _ComfortState extends State<Comfort> {
int _comfortSliderValue = 3;
// double _standardSize = 20;
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 40),
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: ChangeNotifierProvider(
create: (context) => FontSizeController(),
child: Container(
padding: EdgeInsets.all(20.0),
child: Consumer<FontSizeController>(
builder: (
context,
sizeController,
child) => Text(
"How comfortable was your journey?",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.w400,
fontFamily: "Roboto",
letterSpacing: 0.5,
fontSize: sizeController.value,
),
),
),
),
),
),
... etc
Nothing is happening when the buttons are clicked. Can anybody help please?
The example that I'm trying to adapt is all contained within the main() but I've separated out my widgets to try and make everything cleaner - is that what is making the difference?
No need to use a variable in your widget (remove _standardSize).
Just keep the value in your ChangeNotifier and use it directly (through a getter) :
import 'package:flutter/material.dart';
class FontSizeController with ChangeNotifier {
double _value = 20.0;
int get value => _value;
void increment() {
_value++;
notifyListeners();
}
void decrement() {
_value--;
notifyListeners();
}
}
Then on plus and minus buttons, simply increment or decrement value from your ChangeNotifier :
// on plus button pressed
Provider.of<FontSizeController>(context, listen: false).increment();
// on minus button pressed
Provider.of<FontSizeController>(context, listen: false).decrement();
Finally in the widget where you want your text to be sized :
fontSize: Provider.of<FontSizeController>(context, listen: true).value
I have a screen where users can add a location. Here, I have separated all my widgets into there own files as illustrated below;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/location/location_help_screen.dart';
import 'package:fluttershare/widgets/common_widgets/customDivider.dart';
import 'package:uuid/uuid.dart';
import '../../widgets/camp_type_select.dart';
import '../../widgets/extra_location_notes.dart';
import '../../widgets/location_input.dart';
import '../../widgets/opening_times.dart';
import '../../widgets/post_media.dart';
import '../../widgets/space_avalibility.dart';
import '../../widgets/utility_type_select.dart';
import '../../widgets/width_restriction.dart';
import '../../widgets/height_restriction.dart';
import '../../models/locations.dart';
import '../../models/user.dart';
import '../home.dart';
class AddNewLocation extends StatefulWidget {
static const routeName = '/add-new-location';
final User currentUser;
AddNewLocation({this.currentUser});
_AddNewLocationState createState() => _AddNewLocationState();
}
class _AddNewLocationState extends State<AddNewLocation> {
String postId = Uuid().v4();
final _scaffoldKey = GlobalKey<ScaffoldState>();
PlaceLocation _pickedLocation;
int storyPostCount = 0;
bool isLoading = false;
void _selectPlace(double lat, double lng) {
_pickedLocation = PlaceLocation(lattitude: lat, longitude: lng);
}
getLocationPostCount() async {
setState(() {
isLoading = true;
});
QuerySnapshot snapshot = await locationPostRef
.document(currentUser.id)
.collection('user_location_posts')
.getDocuments();
setState(() {
storyPostCount = snapshot.documents.length;
});
}
createLocationPostInFirestore(
{String mediaUrl,
String description,
double heightRestriction,
double widthRestriction}) {
locationPostRef
.document(currentUser.id)
.collection("user_location_posts")
.document(postId)
.setData({
"postId": postId,
"ownerId": currentUser.id,
"username": currentUser.username,
"description": description,
"timestamp": timestamp,
"lattitude": _pickedLocation.lattitude,
"longitude": _pickedLocation.longitude,
"max_height": heightRestrictionValue.toStringAsFixed(0),
"max_width": widthRestrictionValue.toStringAsFixed(0),
});
}
handlePostSubmit() {
createLocationPostInFirestore(
heightRestriction: heightRestrictionValue,
widthRestriction: widthRestrictionValue,
);
SnackBar snackbar = SnackBar(
content: Text("Profile Updated"),
);
_scaffoldKey.currentState.showSnackBar(snackbar);
setState(() {
postId = Uuid().v4();
});
}
buildUploadUserHeader() {
return Container(
margin: EdgeInsets.only(bottom: 10),
height: 200,
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Container(
color: Colors.blue,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundImage:
CachedNetworkImageProvider(currentUser.photoUrl)),
),
],
),
),
),
Expanded(
flex: 6,
child: Container(
color: Colors.pink,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text(currentUser.displayName),
],
),
),
),
],
),
);
}
buildCampUploadForm() {
return Container(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
//buildUploadUserHeader(), //TODO: This is the profile header that is dissabled for now. Work on possibly a header in the future.
Container(
padding: EdgeInsets.all(15),
child: Column(
children: <Widget>[
CampTypeSelect(),
CustomDivider(),
LocationInput(_selectPlace),
CustomDivider(),
HeightRestriction(),
WidthRestriction(),
SpaceAvalibility(),
OpeningTimes(),
CustomDivider(),
PostMedia(),
CustomDivider(),
UtilityServices(),
CustomDivider(),
ExtraLocationNotes(),
Container(
height: 80,
margin: EdgeInsets.only(top: 10, bottom: 10),
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
color: Colors.black,
onPressed: () => handlePostSubmit(),
child: Text(
"SUBMIT",
style: Theme.of(context).textTheme.display2,
),
padding: EdgeInsets.all(20),
),
)
],
),
),
],
),
),
],
),
));
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text(
'Add New Location',
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
// action button
IconButton(
icon: Icon(Icons.info_outline),
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) => LocationSubmitHelpScreen()),
);
},
),
// action button
IconButton(
icon: Icon(Icons.close),
color: Colors.black,
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
body: buildCampUploadForm(),
backgroundColor: Colors.white,
);
}
}
What I am trying to do is pass the data back from the widget ExtraLocationNotes()
to the function createLocationPostInFirestore().
For context, this is what my widget looks like;
import 'package:flutter/material.dart';
import 'common_widgets/custom_form_card.dart';
class ExtraLocationNotes extends StatefulWidget {
_ExtraLocationNotesState createState() => _ExtraLocationNotesState();
}
class _ExtraLocationNotesState extends State<ExtraLocationNotes> {
TextEditingController descriptionController = TextEditingController();
#override
Widget build(BuildContext context) {
return CustomFormCard(
child: Column(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Text(
"EXTRA INFORMATION",
style: TextStyle(
fontSize: 18.0,
color: Colors.black,
fontWeight: FontWeight.w400,
letterSpacing: 2.0,
),
),
],
),
),
SizedBox(height: 20),
TextFormField(
controller: descriptionController,
maxLines: 6,
maxLength: 250,
maxLengthEnforced: true,
style:
new TextStyle(fontSize: 18.0, height: 1.3, color: Colors.black),
decoration: const InputDecoration(
hintText:
"Please write a description of this location for fellow travellers.",
alignLabelWithHint: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.only(),
borderSide: BorderSide(color: Colors.black),
),
),
),
],
),
);
}
}
How do I pass the data back to the parent widget?
You need a callback, which will be triggered in the child widget then the value will be updated in the parent widget:
// 1- Define a pointers to executable code in memory, which is the callback.
typedef void MyCallback(String val);
class ExtraLocationNotes extends StatefulWidget {
// 2- You will pass it to this widget with the constructor.
final MyCallback cb;
// 3- ..pass it to this widget with the constructor
ExtraLocationNotes({this.cb});
_ExtraLocationNotesState createState() => _ExtraLocationNotesState();
}
class _ExtraLocationNotesState extends State<ExtraLocationNotes> {
//..
//...
RaisedButton(
//..
// 4- in any event inside the child you can call the callback with
// the data you want to send back to the parent widget:
onPressed: () {
widget.cb("Hello from the other side!");
}
),
}
Then inside the parent widget you need to catch the data which sent form the child:
class AddNewLocation extends StatefulWidget {
//...
_AddNewLocationState createState() => _AddNewLocationState();
}
class _AddNewLocationState extends State<AddNewLocation> {
// 1- Global var to store the data that we're waiting for.
String _dataFromMyChild = "";
buildCampUploadForm() {
return Container(
//...
//...
// 2- Pass the callback with the constructor of the child, this
// will update _dataFromMyChild's value:
ExtraLocationNotes(cb: (v) => setState(() => _dataFromMyChild = v)),
//..
}
// then
createLocationPostInFirestore() {
// Use _dataFromMyChild's value here
}
}
You can use the BuildContext object to get the context widget (might no be the parent!) couldn't read it all but as i understand that you need to pass the info from the child to the parent ,and you can do it with some like this :-
(context.widget as MyType).doStuff();
Note.
please check first with
print(context.widget.runtimeType);
but to make a better solution make a mutable data object that is passed from parent to the child so when changes happens it reflect's on the parent so you can separate business logic from ui logic.