Flutter Getx notify all listeners - flutter

I aim using a BottomNavigationBar that contains an icon with a badge that displays the number of products a user have in his shopping cart;
there is only one place to add an product to the cart which i call AddToCartRow :
class AddToCartRow extends StatefulWidget {
final productId;
AddToCartRow(this.productId);
#override
_AddToCartRowState createState() => _AddToCartRowState();
}
class _AddToCartRowState extends State<AddToCartRow> {
TextEditingController _text_controller = TextEditingController();
final CartController cartController = CartController();
int quantity = 1;
#override
void initState() {
super.initState();
_text_controller.text = quantity.toString();
}
void increment() {
setState(() {
quantity += 1;
_text_controller.text = quantity.toString();
});
}
void decrement() {
setState(() {
quantity -= 1;
_text_controller.text = quantity.toString();
});
}
void quantityChanged(val) {
setState(() {
quantity = int.parse(val);
});
}
void addToCart() {
var data = {
"product_id": widget.productId.toString(),
"quantity": quantity.toString(),
};
cartController.addToCart(data);
}
#override
Widget build(BuildContext context) {
return Obx(
() => Padding(
padding: EdgeInsets.all(10),
child: Row(
children: [
// Button
GestureDetector(
child: Container(
height: 50,
width: MediaQuery.of(context).size.width / 2 - 15,
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
decoration: BoxDecoration(
color: CupertinoTheme.of(context).primaryColor,
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"ADD TO CART ",
style: TextStyle(color: CupertinoColors.white),
),
Icon(
CupertinoIcons.bag,
color: CupertinoColors.white,
)
],
),
),
onTap: addToCart),
SizedBox(
width: 10,
child: Padding(
padding: const EdgeInsets.only(left: 15),
child: cartController.modifying.value == true
? CupertinoActivityIndicator()
: Container(),
),
),
// Count
Container(
width: MediaQuery.of(context).size.width / 2 - 15,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
height: 50,
child: Row(
children: [
Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: CupertinoColors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4),
bottomLeft: Radius.circular(4),
),
),
width: 50,
height: 50,
child: CupertinoButton(
padding: EdgeInsets.zero,
child: Icon(CupertinoIcons.minus),
onPressed: decrement),
),
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: CupertinoColors.white,
),
alignment: Alignment.center,
child: CupertinoTextField(
controller: _text_controller,
textAlign: TextAlign.center,
onChanged: quantityChanged,
style: TextStyle(
fontSize: 25,
color: CupertinoColors.secondaryLabel),
decoration: BoxDecoration(
borderRadius: BorderRadius.zero,
color: CupertinoColors.white),
)),
Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: CupertinoColors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(4),
bottomRight: Radius.circular(4),
),
),
width: 50,
height: 50,
child: CupertinoButton(
padding: EdgeInsets.zero,
child: Icon(CupertinoIcons.plus),
onPressed: increment),
)
],
),
),
],
),
)
],
),
),
);
}
}
And there is one place to view the products count (in the cart) in the BottomNavigationBar which is above the AddToCartRow in the widgets tree:
BottomNavigationBarItem(
icon: Obx(
() => Stack(
alignment: Alignment.topRight,
children: [
Icon(CupertinoIcons.bag),
Container(
decoration: BoxDecoration(
color: cartController.loading.value == true
? CupertinoColors.white
: CupertinoTheme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
alignment: Alignment.center,
width: 20,
height: 20,
child: cartController.loading.value == true
? CupertinoActivityIndicator()
: Text(
cartController.cartProductsCont.toString(),
style: TextStyle(
color: CupertinoColors.white,
fontWeight: FontWeight.bold),
),
)
],
),
),
activeIcon: Icon(CupertinoIcons.bag_fill),
label: 'Cart',
),
and the CartControllerClass:
class CartController extends GetxController {
var cartProducts = [].obs;
var cartProductsCont = 0.obs;
var emptyCart = true.obs;
var loading = true.obs;
var modifying = false.obs;
void getCart() async {
var response = await api.getCart();
response = response.data;
if (response["data"].length == 0) {
emptyCart.value = true;
cartProducts.clear();
} else {
emptyCart.value = false;
cartProducts.assignAll(response["data"]["products"]);
cartProductsCont.value = cartProducts.length;
}
loading.value = false;
modifying.value = false;
}
void addToCart(data) async {
loading.value = true;
modifying.value = true;
await api.addProductToCart(data).then((value) => getCart());
}}
in the first time when i call getCart from the widget that holds the BottomNavigatioBar every thing works great, but when i call getCart from AddToCartRow no thing happend , WHY ?

Your State class is not injecting the CartController instance into Get's State Manager using Get.put()
class _AddToCartRowState extends State<AddToCartRow> {
TextEditingController _text_controller = TextEditingController();
final CartController cartController = CartController();
int quantity = 1;
Get.put(CartController())
class _AddToCartRowState extends State<AddToCartRow> {
TextEditingController _text_controller = TextEditingController();
final CartController cartController = Get.put(CartController());
// You're missing a Get.put which Get ↑↑↑↑ needs to track
int quantity = 1;
}

Related

i cant update itemcount

hey why is my itemcount not working i have 6 rows in my database but when i run the code it show me only one row and the other rows not showing it
this is my code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class my_ads extends StatefulWidget {
const my_ads({Key? key}) : super(key: key);
#override
State<my_ads> createState() => _my_adsState();
}
List list = [];
int select_item = 0;
class _my_adsState extends State<my_ads> {
#override
Future ReadData() async {
var url = "https://***.***.***.**/getData.php";
var res = await http.get(Uri.parse(url));
if (res.statusCode == 200) {
var red = jsonDecode(res.body);
setState(() {
list.addAll(red);
});
print(list);
}
}
#override
void initState() {
super.initState();
GetData();
}
GetData() async {
await ReadData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: list.length,
itemBuilder: ((cts, i) {
return Container(
height: 800,
child: ListView(
children: [
Container(
margin: EdgeInsets.only(left: 70, right: 60),
height: 54.0,
width: 224.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xffF4AC47), width: 5),
color: Color(0xff42A9D2),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: new Center(
child: new Text(
"MyAds",
style: TextStyle(
fontSize: 25,
color: Color(0xff072A52),
fontFamily: 'Cairo'),
textAlign: TextAlign.center,
),
//end logo
)),
),
///start Section
Container(
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
height: 180.0,
width: 430.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff42A9D2), width: 5),
borderRadius: BorderRadius.circular(8)),
child: new Container(
child: Row(
children: [
Expanded(
child: Image(
image: AssetImage("assets/book.jpg"),
)),
Container(
margin: EdgeInsets.only(
left: 110, top: 30, right: 13),
child: Column(
children: [
Text(
"test",
style: TextStyle(
fontSize: 20, color: Colors.black87),
),
SizedBox(
height: 20,
),
Row(
children: [
Text("test2"),
Icon(Icons.perm_identity_rounded)
],
),
SizedBox(
height: 5,
),
Row(
children: [
Text("}"),
Column(
children: [Icon(Icons.store)],
)
],
),
],
),
)
],
)
//end logo
)),
),
],
),
);
})));
}
}
i tried to change ListView to ListTile but the design will be detroyed becuse i need to make the same design to other pages but my problem is with itemcount its not making any changes ! please if you have any ideas with my problem give me ansewrs

Not being able to read a Collection

I have my flutter app connected to my firebase proyect and im having trouble logging in, since with my code im not being able to read the collection i created
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
TextEditingController idController = TextEditingController();
TextEditingController passController = TextEditingController();
double screenHeight = 0;
double screenWidth = 0;
Color primary = const Color(0xffeef444c);
late SharedPreferences sharedPreferences;
get HomeScreen => null;
#override
Widget build(BuildContext context) {
final bool isKeyboardVisible =
KeyboardVisibilityProvider.isKeyboardVisible(context);
screenHeight = MediaQuery.of(context).size.height;
screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: [
isKeyboardVisible
? SizedBox(
height: screenHeight / 16,
)
: Container(
height: screenHeight / 2.5,
width: screenWidth,
decoration: BoxDecoration(
color: primary,
borderRadius: const BorderRadius.only(
bottomRight: Radius.circular(70),
),
),
child: Center(
child: Icon(
Icons.person,
color: Colors.white,
size: screenWidth / 5,
),
),
),
Container(
margin: EdgeInsets.only(
top: screenHeight / 15,
bottom: screenHeight / 20,
),
child: Text(
"Login",
style: TextStyle(
fontSize: screenWidth / 18,
fontFamily: "NexaBold",
),
),
),
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.symmetric(
horizontal: screenWidth / 12,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
fieldTitle("Employee ID"),
customField("Enter your employee id", idController, false),
fieldTitle("Password"),
customField("Enter your password", passController, true),
GestureDetector(
onTap: () async {
FocusScope.of(context).unfocus();
String id = idController.text.trim();
String password = passController.text.trim();
if (id.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Employee id is still empty!"),
));
} else if (password.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Password is still empty!"),
));
} else {
QuerySnapshot snap = await FirebaseFirestore.instance
.collection("Employee")
.where('id', isEqualTo: id)
.get();
try {
if (password == snap.docs[0]['password']) {
sharedPreferences =
await SharedPreferences.getInstance();
sharedPreferences
.setString('employeeId', id)
.then((_) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen));
});
} else {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text("Password is not correct!"),
));
}
} catch (e) {
String error = " ";
if (e.toString() ==
"RangeError (index): Invalid value: Valid value range is empty: 0") {
setState(() {
error = "Employee id does not exist!";
});
} else {
setState(() {
error = "Error occurred!";
});
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(error),
));
}
}
},
child: Container(
height: 60,
width: screenWidth,
margin: EdgeInsets.only(top: screenHeight / 40),
decoration: BoxDecoration(
color: primary,
borderRadius: const BorderRadius.all(Radius.circular(30)),
),
child: Center(
child: Text(
"LOGIN",
style: TextStyle(
fontFamily: "NexaBold",
fontSize: screenWidth / 26,
color: Colors.white,
letterSpacing: 2,
),
),
),
),
)
],
),
),
],
),
);
}
Widget fieldTitle(String title) {
return Container(
margin: const EdgeInsets.only(bottom: 12),
child: Text(
title,
style: TextStyle(
fontSize: screenWidth / 26,
fontFamily: "NexaBold",
),
),
);
}
Widget customField(
String hint, TextEditingController controller, bool obscure) {
return Container(
width: screenWidth,
margin: EdgeInsets.only(bottom: 12),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(2, 2),
),
],
),
child: Row(
children: [
Container(
width: screenWidth / 6,
child: Icon(
Icons.person,
color: primary,
size: screenWidth / 15,
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(right: screenWidth / 12),
child: TextFormField(
controller: controller,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: screenHeight / 35,
),
border: InputBorder.none,
hintText: hint,
),
maxLines: 1,
obscureText: obscure,
),
),
)
],
),
);
}
}
i have a collection called "Employee" with 2 parameters being "id" and "password". Please help and thanks in advance. im getting this error
if (e.toString() == > "RangeError (index): Invalid value: Valid value range is empty: 0") { setState(() { error = "Employee id does not exist!"; > });
which i think it means Im not being able to read the specific Collection, tried enabling internet connection in Android manifest but still not working`

How to fix "Bad State:No element " flutter sharedPreference?

In my code fetching word from firebase and the user can select words and if the user selects a word and after deselect that then display and save firebase that also. And when the user selects a word then colour also.
I want to add sharedPrefences for that.
Ex: if the user selects words and clicks the next button and after closes the app and reopens later then should save the selected words and deselected words and then colour only selected words.
image
code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:shared_preferences/shared_preferences.dart';
class uitry extends StatefulWidget {
const uitry({Key? key}) : super(key: key);
#override
State<uitry> createState() => _uitryState();
}
class _uitryState extends State<uitry> {
//list
List<Words12> wordList = [];
//collection path
Future<List<Words12>> fetchRecords() async {
var records = await FirebaseFirestore.instance
.collection('12words')
.where("categoryName", isEqualTo: "Objects12")
.get();
return mapRecords(records);
}
List<Words12> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
var _wordList =
records.docs.map((data) => Words12.fromJson(data.data())).toList();
return _wordList;
}
#override
void initState() {
super.initState();
dropdownValueselectedWord = selectedWord.first;
checkValueSelectedWord();
dropdownValueDeselectedWord = deSelectedWord?.first;
checkValueDeselectedWord();
}
List<String> selectedWord = [];
String? dropdownValueselectedWord = "";
checkValueSelectedWord() {
_getDataSelectedWord();
}
_saveDataSelectedWord(String dropdownValueSelectedWord) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString(
"SelectedWordObject", dropdownValueSelectedWord);
}
_getDataSelectedWord() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
dropdownValueselectedWord =
sharedPreferences.getString("SelectedWordObject") ?? selectedWord.first;
setState(() {});
}
List<String>? deSelectedWord = [];
String? dropdownValueDeselectedWord = "";
checkValueDeselectedWord() {
_getDataDeselectedWord();
}
_saveDataDeselectedWord(String dropdownValueDeselectedWord) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString(
"SelectedWordObject", dropdownValueDeselectedWord);
}
_getDataDeselectedWord() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
dropdownValueselectedWord =
sharedPreferences.getString("SelectedWordObject") ??
deSelectedWord?.first;
setState(() {});
}
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(Config.app_background4), fit: BoxFit.fill),
),
child: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: ListTile(
leading: GestureDetector(
child: const Icon(
Icons.arrow_back_ios_new_sharp,
color: Colors.black,
size: 24.0,
),
onTap: () => Navigator.pop(context),
),
title: const Padding(
padding: EdgeInsets.only(top: 32, right: 35),
child: Text(
"Under 18 months",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 18.00,
fontWeight: FontWeight.w700,
),
),
),
),
),
],
),
const SizedBox(
height: 00,
),
Padding(
padding: const EdgeInsets.only(top: 1, right: 0),
child: Column(
children: [
Material(
color: HexColor('#E92F54').withOpacity(0.9),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0).copyWith(
topLeft: const Radius.circular(28.0),
topRight: const Radius.circular(28.0),
),
),
child: SizedBox(
width: width * 0.94,
height: height * 0.062,
child: Column(
children: const <Widget>[
SizedBox(
height: 6.5,
),
Text('Understanding',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 16.0)),
Text('Object',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 15.0))
],
),
),
),
Material(
color: HexColor('#FFFBFB').withOpacity(0.7),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(2).copyWith(
bottomLeft: const Radius.circular(28.0),
bottomRight: const Radius.circular(28.0),
),
),
child: SizedBox(
width: width * 0.94,
height: height * 0.30, //white box height
child: Column(
children: [
SizedBox(
height: height * 0.18,
child: SingleChildScrollView(
child: Column(
//chip words
children: <Widget>[
const SizedBox(height: 10),
FutureBuilder<List<Words12>>(
future: fetchRecords(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(
'Error: ${snapshot.error}');
} else {
wordList = snapshot.data ?? [];
return Wrap(
children: wordList.map(
(word) {
bool isSelected = false;
if (selectedWord!.contains(
word.wordName)) {
isSelected = true;
}
return GestureDetector(
onTap: () {
if (!selectedWord!
.contains(
word.wordName)) {
if (selectedWord!
.length <
50) {
selectedWord!.add(
word.wordName);
deSelectedWord!
.removeWhere(
(element) =>
element ==
word.wordName);
setState(() {});
print(selectedWord);
}
} else {
selectedWord!.removeWhere(
(element) =>
element ==
word.wordName);
deSelectedWord!
.add(word.wordName);
setState(() {
// selectedHobby.remove(hobby);
});
print(selectedWord);
print(deSelectedWord);
}
},
child: Container(
margin: const EdgeInsets
.symmetric(
horizontal: 5,
vertical: 4),
child: Container(
padding:
const EdgeInsets
.symmetric(
vertical: 5,
horizontal: 12),
decoration: BoxDecoration(
color: isSelected
? HexColor(
'#3A97FF')
: HexColor(
'#D9D9D9'),
borderRadius:
BorderRadius
.circular(
18),
border: Border.all(
color: isSelected
? HexColor(
'#3A97FF')
: HexColor(
'#D9D9D9'),
width: 1)),
child: Text(
word.wordName,
style: TextStyle(
color: isSelected
? Colors.black
: Colors
.black,
fontSize: 14,
fontWeight:
FontWeight
.w700),
),
),
),
);
},
).toList(),
);
}
}),
],
),
),
),
],
),
),
),
],
),
),
const SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.only(top: 20, left: 0, bottom: 0),
child: Center(
child: SizedBox(
width: 160.0,
height: 35.0,
child: ElevatedButton(
style: ButtonStyle(
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: const BorderSide(
color: Colors.blueAccent,
),
),
),
),
onPressed: displayMessage,
child: const Text("next"),
),
),
),
),
],
),
))),
),
);
}
void displayMessage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
final sp = context.read<SignInProvider>();
FirebaseFirestore.instance.collection("objects").doc(sp.uid).set({
"speackSE": selectedWord,
"speackUN": deSelectedWord,
});
_saveDataSelectedWord(dropdownValueselectedWord!);
_saveDataDeselectedWord(dropdownValueDeselectedWord!);
}
}
Bad State: No Element error is thrown when you're trying to access an element in an iterable at a location that does not exist. Like accessing the first or last element of the list (using the List getters like .first, .last, etc.)
You're using selectedWord.first in case the required data is not found in the prefs. Most probably, there's no item in the list which is the reason for the error.
Check all the places where you've used .first for empty lists. Make sure that the lists are not empty before calling these getters.

Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?

I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
My Code :
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_clipboard_manager/flutter_clipboard_manager.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'URL Shortener',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: StartPage(),
);
}
}
class StartPage extends StatefulWidget {
#override
_StartPageState createState() => _StartPageState();
}
class _StartPageState extends State<StartPage> {
bool visibilityTag = false;
void _changed(bool visibility, String field) {
setState(() {
if (field == "tag") {
visibilityTag = visibility;
}
});
}
final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
String shortUrl = "";
String value = "";
String buttonText = "COPY!";
bool isChanged = true;
TextEditingController urlcontroller = TextEditingController();
getData() async {
var url = 'https://api.shrtco.de/v2/shorten?url=${urlcontroller.text}';
var response = await http.get(url);
var result = jsonDecode(response.body);
if (result['ok']) {
setState(() {
shortUrl = result['result']['short_link'];
});
} else {
print(response);
}
}
copy(String url) {
FlutterClipboardManager.copyToClipBoard(url).then((value) {});
}
buildRow(String data, bool original) {
return SingleChildScrollView(
child: original
? Container(
alignment: Alignment.center,
child: Text(
data,
))
: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
data,
),
ElevatedButton(
child: Text(buttonText),
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(300, 40),
),
onPressed: () {
copy(shortUrl);
setState(() {
if (isChanged == true) {
buttonText = "COPIED!";
}
});
},
),
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: ListView(
children: [
SvgPicture.asset(
'assets/logo.svg',
),
SvgPicture.asset(
'assets/illustration.svg',
),
Center(
child: Text(
"Let's get started!",
style: TextStyle(
fontSize: 20,
color: Color.fromRGBO(53, 50, 62, 10),
fontWeight: FontWeight.bold),
),
),
Center(
child: SizedBox(
width: 200,
height: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Paste your first link into the field to shorten it",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
color: Color.fromRGBO(76, 74, 85, 10),
fontWeight: FontWeight.bold)),
),
),
),
SizedBox(
height: 130,
child: Stack(
alignment: Alignment.center,
children: [
Container(
alignment: Alignment.centerRight,
color: Color.fromRGBO(59, 48, 84, 1),
child: SvgPicture.asset(
'assets/shape.svg',
color: Color.fromRGBO(75, 63, 107, 1),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 300,
height: 40,
child: TextField(
onChanged: (text) {
value = "URL : " + text;
},
controller: urlcontroller,
textAlign: TextAlign.center,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0),
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
fillColor: Colors.white,
filled: true,
hintText: 'Shorten a link here ...'),
),
),
SizedBox(
height: 10,
),
SizedBox(
width: 300,
child: ElevatedButton(
onPressed: getData,
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(60, 40),
),
child: Text('SHORTEN IT!'),
),
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow(value, true),
buildRow(shortUrl, false),
],
),
),
)
],
),
);
}
}
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
On State create a bool like
bool showCopyButton = false;
Change to true at
SizedBox(
width: 300,
child: ElevatedButton(
onPressed: ()async {
print("Button Click");
await getData();
setState(() {
showCopyButton = true;
});
},
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(60, 40),
),
child: Text('SHORTEN IT!'),
),
),
And wrap with Visibility Like
Visibility(
visible: showCopyButton,
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow("Text ", true),
buildRow("asdad", false),
],
),
),
),
)
or you can just if like
if (showCopyButton)
Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow("Text ", true),
buildRow("asdad", false),
],
),
),
),
Btw you need to use await before making it true.
Hope this helps:
import 'package:flutter/material.dart';
class Screen extends StatefulWidget {
#override
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
bool _paddingVisible = false;
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 10), () {
// Check if mounted == true, because the screen might closed
// before 10 seconds pass
if (mounted) {
// Setting padding visibility to true after 10 seconds
setState(() {
_paddingVisible = true;
});
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
// All your widgets
// When _paddingVisible becomes true it will be displayed
if (_paddingVisible) SizedBox(height: 10),
],
),
);
}
}

How can I create a function that pronounces the word when it's clicked?

I have this app for kids with vocabulary and I would like to know how I can create a function that pronounces the word that is written in English. I saw that Google has a Google translator API but couldn't find information on how to use it. Do you guys have any idea on how I can achieve that?
class AnimalsScreen extends StatelessWidget {
final DocumentSnapshot animals;
AnimalsScreen(this.animals);
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Card(
elevation: 7.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)
),
child: Column(
children: <Widget>[
Container(
height: 350.0,
width: 350.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(animals.data["image"]
),
fit: BoxFit.fill),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(50),
topRight: Radius.circular(50)))
),
Container(
height: 70.0,
width: 300.0,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Center(
child: AutoSizeText(animals.data["name"],
style: TextStyle(
fontFamily: 'Twiddlestix',
fontSize: 25,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
minFontSize: 15,
),
)
),
),
],
),
),
),
],
);
}
}
Just check out this example which i have made using your ui i have just passed the static string to it. There is a plugin named flutter_tts maybe this can work for you. Just check the example:
Link for the plugin : https://pub.dev/packages/flutter_tts
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
void main() => runApp(ApiCalling());
class ApiCalling extends StatefulWidget {
#override
_ApiCallingState createState() => _ApiCallingState();
}
enum TtsState { playing, stopped }
class _ApiCallingState extends State<ApiCalling> {
bool showLoader = false;
FlutterTts flutterTts;
TtsState ttsState = TtsState.stopped;
String _newVoiceText = 'CAT';
double volume = 0.5;
double pitch = 1.0;
double rate = 0.5;
#override
void initState() {
super.initState();
flutterTts = FlutterTts();
initSpeak();
}
initSpeak() {
flutterTts.setStartHandler(() {
setState(() {
ttsState = TtsState.playing;
});
});
flutterTts.setCompletionHandler(() {
setState(() {
ttsState = TtsState.stopped;
});
print('Speaking End');
});
flutterTts.setErrorHandler((msg) {
setState(() {
ttsState = TtsState.stopped;
});
});
}
#override
void dispose() {
super.dispose();
flutterTts.stop();
}
Future _speak() async {
await flutterTts.setVolume(volume);
await flutterTts.setSpeechRate(rate);
await flutterTts.setPitch(pitch);
if (_newVoiceText != null) {
if (_newVoiceText.isNotEmpty) {
var result = await flutterTts.speak(_newVoiceText);
if (result == 1) setState(() => ttsState = TtsState.playing);
}
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: GestureDetector(
onTap: () {
_speak();
},
child: Card(
elevation: 7.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: Column(
children: <Widget>[
Container(
height: 350.0,
width: 350.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'images/cat.jpg',
),
fit: BoxFit.fill),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(50),
topRight: Radius.circular(50)))),
Container(
height: 70.0,
width: 300.0,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Center(
child: AutoSizeText(
'CAT',
style: TextStyle(
fontFamily: 'Twiddlestix',
fontSize: 25,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
minFontSize: 15,
),
)),
),
],
),
),
),
),
],
),
),
),
);
}
}
Let me know if it works.
You can try this package, https://pub.dev/packages/text_to_speech_api or look for any other text to speech https://pub.dev/flutter/packages?q=text+to+speech .I didn't try any of them but looks like working.
Hope it helps!