reshape image on flatter deep learning app - flutter

I am working on a flatter app to classify plant diseases using deep learning. When I take a picture to classify the disease, it appears with an error because the model I trained deals with 4D image, and the image I took is 3D. Is there a suggestion to solve this problem?
type here
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';
class UI extends StatefulWidget {
const UI({Key? key}) : super(key: key);
#override
_UIState createState() => _UIState();
}
class _UIState extends State<UI> {
List? _outputs;
XFile? _image;
bool _loading = false;
final ImagePicker _picker = ImagePicker();
#override
void initState() {
super.initState();
_loading = true;
loadModel().then((value) {
setState(() {
_loading = false;
});
});
}
loadModel() async {
await Tflite.loadModel(
model: "assets/model_unquant.tflite",
labels: "assets/labels.txt",
numThreads: 1,
);
}
classifyImage(File image) async {
var output = await Tflite.runModelOnImage(
path: image.path,
imageMean: 0.0,
imageStd: 255.0,
numResults: 10,
threshold: 0.2,
asynch: true);
setState(() {
_loading = false;
_outputs = output;
});
}
#override
void dispose() {
Tflite.close();
super.dispose();
}
Future getImageCamera() async {
var image =
await _picker.pickImage(source: ImageSource.camera, imageQuality: 50);
if (image == null) return null;
setState(() {
_loading = true;
_image = image;
});
classifyImage(File(_image!.path));
}
Future getImageGallery() async {
var image =
await _picker.pickImage(source: ImageSource.gallery, imageQuality: 50);
if (image == null) return null;
setState(() {
_loading = true;
_image = image;
});
classifyImage(File(_image!.path));
}
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Crop diseases'),
actions: [
IconButton(
onPressed: () {
getImageCamera();
},
icon: const Icon(
Icons.camera_alt,
color: Colors.white,
)),
IconButton(
onPressed: () {
getImageGallery();
},
icon: const Icon(
Icons.image,
color: Colors.white,
))
],
),
body: SafeArea(
child: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Expanded(
flex: 9,
child: _image == null
? Container(
margin: const EdgeInsets.all(10),
decoration: const BoxDecoration(
color:Colors.white,
borderRadius:
BorderRadius.all(Radius.circular(25.0)),
),
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.circular(15)),
padding: const EdgeInsets.all(20),
child: const Text(
"Upload an image",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
),
)
: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(File(_image!.path)),
fit: BoxFit.cover),
color: Colors.transparent,
borderRadius:
const BorderRadius.all(Radius.circular(25.0)),
),
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.circular(15)),
padding: const EdgeInsets.all(20),
child: Text(
_outputs?[0]["label"] ?? "",
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
),
),
),
Expanded(
flex: 2,
child: Card(
margin: const EdgeInsets.all(0),
//color: const Color(0xFFD4DCFF),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(15.0),
topLeft: Radius.circular(15.0),
),
),
child: Container(
width: double.infinity,
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(15.0),
topLeft: Radius.circular(15.0),
),
),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// Container(
// margin: const EdgeInsets.all(10),
// decoration: const BoxDecoration(
// color: Color(0xFF65708F),
// shape: BoxShape.circle,
// ),
// child: IconButton(
// onPressed: () {
// getImageCamera();
// },
// icon: const Icon(
// Icons.camera_alt,
// color: Colors.white,
// )),
// ),
// Container(
// margin: const EdgeInsets.all(10),
// decoration: const BoxDecoration(
// color: Color(0xFF65708F),
// shape: BoxShape.circle,
// ),
// child: IconButton(
// onPressed: () {
// getImageGallery();
// },
// icon: const Icon(
// Icons.image,
// color: Colors.white,
// )),
// )
// ],
// )
),
),
)
],
),
),
),
),
);
}
}
[![[![[![enter image description here](https://i.stack.imgur.com/9bYdu.jpg)](https://i.stack.imgur.com/9bYdu.jpg)](https://i.stack.imgur.com/gzexM.jpg)](https://i.stack.imgur.com/gzexM.jpg)](https://i.stack.imgur.com/BnjYt.jpg)]
how can i reshape this image?

Related

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.

Field has not been initialized

tags in my code is a List which is comes from previous page,
I want to be able to remove and add items to it in my current page,
first I tried to initialize it in my initState but when I want to remove tags it doesn't work.
I guessed it is about the initialization, so I removed it from initState but now I am getting this error message Field 'tags' has not been initialized. I will attach my full code and I appreciate any suggestions about it. Thanks.
PS: I tried initializing tags with tags=[] in my initState but I can't remove any of the tags. It has a GestureDetector to remove tags, when I press it nothing happens. I guess initializing in the build function causes it, but I don't know where to initialize it that I could be able to edit it while the list is coming from another screen.
also when I added tags = widget.tags.where((e) => e != null && e != "").toList(); to my initiState and I inspect tags value, there is an empty string in addtion to other values at the end of the list.
import 'dart:convert';
import 'dart:developer';
import 'package:double_back_to_close/toast.dart';
import 'package:flutter/material.dart';
import 'package:pet_store/main.dart';
import 'package:pet_store/widgets/tag_preview.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:async';
import 'dart:math';
import 'package:http/http.dart' as http;
import 'package:pet_store/widgets/tag_retrieve_preview.dart';
import 'utils/utils.dart';
class update_pet extends StatefulWidget {
var id;
var name;
var status;
var category;
var tags ;
update_pet(
{this.id, this.name, this.status, this.category, this.tags, Key? key})
: super(key: key);
#override
_update_petState createState() => _update_petState();
}
class _update_petState extends State<update_pet> {
final _picker = ImagePicker();
Future<void> _openImagePicker() async {
final XFile? pickedImage =
await _picker.pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
setState(() {
final bytes = File(pickedImage.path).readAsBytesSync();
base64Image = "data:image/png;base64," + base64Encode(bytes);
});
}
}
String? base64Image;
TextEditingController nameController = TextEditingController();
TextEditingController categoryController = TextEditingController();
TextEditingController tagController = TextEditingController();
late File imageFile;
late List<dynamic> tags;
bool isLoading = false;
void initState() {
super.initState();
nameController.text = widget.name;
categoryController.text = widget.category;
addTag();
}
void addTag() {
setState(() {
tags.add(tagController.text);
tagController.clear();
});
}
String? dropdownvalue;
var items = [
'available',
'pending',
'sold',
];
#override
Widget build(BuildContext context) {
tags = widget.tags.where((e) => e != null && e != "").toList();
// inspect(tags);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo,
title: const Text('Update a pet'),
leading: GestureDetector(
child: Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onTap: () {
// Navigator.pop(context);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
PetStoreHomePage(LoggedIn: true),
),
(route) => false,
);
},
),
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Card(
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
children: [
const ListTile(
// leading,
title: Text(
"General Information",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
TextField(
controller: nameController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Enter your pet's name",
),
),
DropdownButton(
hint: const Text('Select Status'),
value: dropdownvalue,
icon: const Icon(Icons.keyboard_arrow_down),
items: items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
],
),
),
elevation: 8,
shadowColor: Colors.grey.shade300,
margin: const EdgeInsets.all(20),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.white)),
),
Card(
child: Container(
padding: const EdgeInsets.all(10),
child: Column(
children: [
const ListTile(
// leading,
title: Text(
"Category",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
TextField(
controller: categoryController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Specify your pet's category",
),
),
],
),
),
elevation: 8,
shadowColor: Colors.grey.shade300,
margin:
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.white)),
),
Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
// leading,
title: Text(
"Tags",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Flexible(
fit: FlexFit.loose,
child: ListView.builder(
shrinkWrap: true,
itemCount: tags.length,
itemBuilder: (_, index) {
print(tags);
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 5.0, vertical: 3.0),
child: GestureDetector(
child: tagRetrievePreview(tags[index]),
onTap: () {
print("REMOVED "+tags[index]);
tags.removeAt(index);
}),
);
},
),
),
TextField(
controller: tagController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Specify your pet's tags",
suffixIcon: IconButton(
icon: const Icon(
Icons.add_circle_outline_sharp,
color: Color.fromARGB(255, 129, 128, 128),
size: 30,
),
onPressed: () {
addTag();
print(tags);
},
),
),
),
],
),
),
elevation: 8,
shadowColor: Colors.grey.shade300,
margin:
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.white)),
),
Card(
child: Column(
children: [
const ListTile(
title: Text(
"Images",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
(base64Image != null)
? SizedBox(
width: 100,
height: 100,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
image: DecorationImage(
image: image(base64Image!).image,
fit: BoxFit.fill),
)),
)
: SizedBox(
width: 100,
height: 100,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.grey.shade300,
),
child: Icon(
Icons.camera_alt,
color: Colors.grey.shade800,
size: 30,
),
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 100),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 129, 128, 128)),
padding: MaterialStateProperty.all(
const EdgeInsets.symmetric(horizontal: 20)),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
side: const BorderSide(
color: Color.fromARGB(255, 129, 128, 128),
width: 2.0,
),
),
),
),
child: const Text(
'Select Image',
style:
TextStyle(fontSize: 15.0, color: Colors.white),
),
onPressed: _openImagePicker),
),
],
),
elevation: 8,
shadowColor: Colors.grey.shade300,
margin:
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.white)),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 120),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.indigo),
padding: MaterialStateProperty.all(
const EdgeInsets.symmetric(horizontal: 40)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
side: const BorderSide(
color: Colors.indigo,
width: 2.0,
),
),
),
),
child: isLoading
? const SizedBox(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white)),
height: 15.0,
width: 15.0,
)
: const Text(
'Update Pet',
style:
TextStyle(fontSize: 17.0, color: Colors.white),
),
onPressed: () async {
if (nameController.text.isEmpty) {
nameController.text = widget.name;
}
if (tagController.text.isEmpty) {
tagController.text = widget.tags;
}
if (categoryController.text.isEmpty) {
categoryController.text = widget.category;
}
if (dropdownvalue == null) {
dropdownvalue = widget.status;
}
print('Pressed');
Map data = {
"id": random.nextInt(10000),
///random it integer
"name": nameController.text,
"category": {
"id": set_category_id(categoryController.text),
"name": categoryController.text,
},
"photoUrls": [base64Image],
"tags": set_tags(tags),
"status": dropdownvalue
};
var body = json.encode(data);
var response = await http.put(
Uri.parse(
"https://api.training.testifi.io/api/v3/pet"),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: body);
print(response.body);
print(response.statusCode);
if (response.statusCode == 201 ||
response.statusCode == 200) {
print('success');
Toast.show("Pet is successfully updated.", context);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
PetStoreHomePage(LoggedIn: true),
),
(route) => false,
);
} else {
Toast.show(
"ERROR! Updating pet failed. Please try again.",
context);
}
}),
),
],
),
),
),
);
}
}
tags = widget.tags.where((e) => e != null && e != "").toList();
This line in build method will constantly take value from widget.tags and create a list of items thats not null and empty.
Please add this in initState.
Just initialize it
List<dynamic> tags = [];
PS: I tried initializing tags with tags=[] in my initState but I can't
remove any of the tags.
You need to add setState to rebuild the page.

Can't reduce size of an elevated button

I am trying to reproduce Apple memo recorder button. Right now, I am trying to reduce the size of Stop Button. First, I have tried without the SizedBox and then with. I am getting the same result.Even if embedded in a SizedBox, I can not achieve what I want.
Please, can somebody tells me what I am missing? Thank you.
Container _RecordButton(){
return Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false?
_createRecordElevatedButton() : _createStopElevatedButton()),);
}
ElevatedButton _createRecordElevatedButton(
{IconData icon, Function onPressFunc}) {
return ElevatedButton(
onPressed: () {
if (isRecording = false){
setState(() {
isRecording = true;
});
}},
style: ButtonStyle(
shape: MaterialStateProperty.all(CircleBorder()),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/));
}
SizedBox _createStopElevatedButton(
{IconData icon, Function onPressFunc}) {
return SizedBox(
height: 14,
width: 14,
child: ElevatedButton(
onPressed: () {
/* if (isRecording = true){
setState(() {
isRecording = false;
});
}*/
},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10,10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
side: BorderSide(color: Colors.red)
)
),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/)),
);
}
Wrap your elevated button with container and give height and width accordingly.
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.grey)),
child: Container(
padding: EdgeInsets.all(7),
width: 50.0,
height: 50.0,
child: ElevatedButton(
onPressed: () {},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10, 10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(color: Colors.red))),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor: MaterialStateProperty.all(Colors.red),
),
child: null,
)),
),
Please replace your code with below code:
class MyElevatedButton extends StatefulWidget {
const MyElevatedButton({Key? key}) : super(key: key);
#override
_MyElevatedButtonState createState() => _MyElevatedButtonState();
}
class _MyElevatedButtonState extends State<MyElevatedButton> {
bool isRecording=false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton(icon: Icons.add)
: _createStopElevatedButton(icon: Icons.minimize,onPressFunc: (){})),
),
],
),
),
),
);
}
/* Container _RecordButton() {
return Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton()
: _createStopElevatedButton()),
);
}*/
Widget _createRecordElevatedButton(
// ignore: unused_element
{required IconData icon,/* VoidCallback onPressFunc*/}) {
return ElevatedButton(
onPressed: () {
if (isRecording = false) {
setState(() {
isRecording = true;
});
}
},
style: ButtonStyle(
shape: MaterialStateProperty.all(CircleBorder()),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor:
MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/
), child: Text('play'),);
}
// ignore: unused_element
SizedBox _createStopElevatedButton({required IconData icon, required VoidCallback onPressFunc}) {
return SizedBox(
height: 14,
width: 14,
child: ElevatedButton(
onPressed: () {
/* if (isRecording = true){
setState(() {
isRecording = false;
});
}*/
},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(10, 10)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
side: BorderSide(color: Colors.red))),
padding: MaterialStateProperty.all(EdgeInsets.all(20)),
backgroundColor:
MaterialStateProperty.all(Colors.red), // <-- Button color
/*overlayColor: MaterialStateProperty.resolveWith<Color>((states) {
if (states.contains(MaterialState.pressed))
return Colors.red; // <-- Splash color
}*/
), child: Text('onPressed'),),
);
}
}
Try this code :
MyElevatedButton
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class MyElevatedButton extends StatefulWidget {
const MyElevatedButton({Key? key}) : super(key: key);
#override
_MyElevatedButtonState createState() => _MyElevatedButtonState();
}
class _MyElevatedButtonState extends State<MyElevatedButton> {
bool isRecording=false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
border: Border.all(
width: 4.0,
color: Colors.grey,
),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(4.0),
child: isRecording == false
? _createRecordElevatedButton() /*_createRecordElevatedButton(icon: Icons.add,)*/
: _createStopElevatedButton()),
),
],
),
),
),
);
}
Widget _createRecordElevatedButton(){
return GestureDetector(
onTap: (){
setState(() {
isRecording = true;
});
print('clickOnPressedButton');
},
child: Container(
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(child: Text('Play',style: TextStyle(fontSize: 12,color: Colors.white),)),
),
);
}
Widget _createStopElevatedButton(){
return GestureDetector(
onTap: (){
setState(() {
isRecording = false;
});
print('clickOnPressedButton');
},
child: Container(
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(child: Text('Pause',style: TextStyle(fontSize: 12,color: Colors.white),)),
),
);
}
}

Flutter Getx notify all listeners

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

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!