Flutter : share a record - flutter

Im using record_mp3 package to record an audio file, can i share this record via whatsapp and other social media ?
Thanks in advance

You can copy paste run full code below
You can use package https://pub.dev/packages/esys_flutter_share
code snippet
onPressed: () async {
print('recordFilePath ${recordFilePath}');
File file = File(recordFilePath);
Uint8List bytes = await file.readAsBytes() as Uint8List;
await Share.file(
'yourmusic', 'yourmusic.mp3', bytes, 'audio/mpeg');
}
working demo
full code
import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:record_mp3/record_mp3.dart';
import 'dart:io';
import 'dart:typed_data';
import 'package:esys_flutter_share/esys_flutter_share.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String statusText = "";
bool isComplete = false;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: GestureDetector(
child: Container(
height: 48.0,
decoration: BoxDecoration(color: Colors.red.shade300),
child: Center(
child: Text(
'start',
style: TextStyle(color: Colors.white),
),
),
),
onTap: () async {
startRecord();
},
),
),
Expanded(
child: GestureDetector(
child: Container(
height: 48.0,
decoration: BoxDecoration(color: Colors.blue.shade300),
child: Center(
child: Text(
RecordMp3.instance.status == RecordStatus.PAUSE
? 'resume'
: 'pause',
style: TextStyle(color: Colors.white),
),
),
),
onTap: () {
pauseRecord();
},
),
),
Expanded(
child: GestureDetector(
child: Container(
height: 48.0,
decoration: BoxDecoration(color: Colors.green.shade300),
child: Center(
child: Text(
'stop',
style: TextStyle(color: Colors.white),
),
),
),
onTap: () {
stopRecord();
},
),
),
],
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Text(
statusText,
style: TextStyle(color: Colors.red, fontSize: 20),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
play();
},
child: Container(
margin: EdgeInsets.only(top: 30),
alignment: AlignmentDirectional.center,
width: 100,
height: 50,
child: isComplete && recordFilePath != null
? Text(
"播放",
style: TextStyle(color: Colors.red, fontSize: 20),
)
: Container(),
),
),
]),
floatingActionButton: FloatingActionButton(
onPressed: () async {
print('recordFilePath ${recordFilePath}');
File file = File(recordFilePath);
Uint8List bytes = await file.readAsBytes() as Uint8List;
await Share.file(
'yourmusic', 'yourmusic.mp3', bytes, 'audio/mpeg');
},
child: Icon(Icons.share),
backgroundColor: Colors.green,
)),
);
}
Future<bool> checkPermission() async {
Map<PermissionGroup, PermissionStatus> map = await new PermissionHandler()
.requestPermissions(
[PermissionGroup.storage, PermissionGroup.microphone]);
print(map[PermissionGroup.microphone]);
return map[PermissionGroup.microphone] == PermissionStatus.granted;
}
void startRecord() async {
bool hasPermission = await checkPermission();
if (hasPermission) {
statusText = "正在录音中...";
recordFilePath = await getFilePath();
isComplete = false;
RecordMp3.instance.start(recordFilePath, (type) {
statusText = "录音失败--->$type";
setState(() {});
});
} else {
statusText = "没有录音权限";
}
setState(() {});
}
void pauseRecord() {
if (RecordMp3.instance.status == RecordStatus.PAUSE) {
bool s = RecordMp3.instance.resume();
if (s) {
statusText = "正在录音中...";
setState(() {});
}
} else {
bool s = RecordMp3.instance.pause();
if (s) {
statusText = "录音暂停中...";
setState(() {});
}
}
}
void stopRecord() {
bool s = RecordMp3.instance.stop();
if (s) {
statusText = "录音已完成";
isComplete = true;
setState(() {});
}
}
void resumeRecord() {
bool s = RecordMp3.instance.resume();
if (s) {
statusText = "正在录音中...";
setState(() {});
}
}
String recordFilePath;
void play() {
if (recordFilePath != null && File(recordFilePath).existsSync()) {
AudioPlayer audioPlayer = AudioPlayer();
audioPlayer.play(recordFilePath, isLocal: true);
}
}
int i = 0;
Future<String> getFilePath() async {
Directory storageDirectory = await getApplicationDocumentsDirectory();
String sdPath = storageDirectory.path + "/record";
var d = Directory(sdPath);
if (!d.existsSync()) {
d.createSync(recursive: true);
}
return sdPath + "/test_${i++}.mp3";
}
}

Related

Error while uploading image onto Firebase Storage

I am trying to build a image picker using flutter. I want the user to be able to select an image and upload it onto firebase storage so that it can be later retrieved. I am using an image picker to select the image from the gallery and I am then setting the image selected as a file. I am then creating a reference called firebaseStorageRef and using firebaseStorageRef.putFile(_selectedImage!) to upload the data.
However, I am getting the error:
Restarted application in 553ms.
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_storage/object-not-found] No object exists at the desired reference.
main.dart:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blog/views/homePage.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: "Blog App",
themeMode: ThemeMode.dark,
debugShowCheckedModeBanner: false,
home: homePage());
}
}
create_blog.dart code:
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blog/services/crud.dart';
import 'package:image_picker/image_picker.dart';
import 'package:random_string/random_string.dart';
import 'package:firebase_core/firebase_core.dart';
class CreateBlog extends StatefulWidget {
const CreateBlog({super.key});
#override
State<CreateBlog> createState() => _CreateBlogState();
}
class _CreateBlogState extends State<CreateBlog> {
late String authorName, title, desc;
bool isloading = false;
CRUDMethods crudMethods = new CRUDMethods();
File? _selectedImage;
Future getImage() async {
var image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final image_path = File(image.path);
setState(() {
_selectedImage = image_path;
});
}
uploadBlog() async {
if (_selectedImage != null) {
// Uploading image to Firestore
setState(() {
isloading = true;
});
var firebaseStorageRef = FirebaseStorage.instance
.ref()
.child("blogImages")
.child("${randomAlphaNumeric(9)}.jpg");
try {
var task = firebaseStorageRef
.putFile(_selectedImage!)
.whenComplete(() => Navigator.pop(context));
} catch (error) {
print(error);
}
} else {}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
Text(
"Flutter",
style: TextStyle(
fontSize: 22,
color: Colors.black,
),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
]),
backgroundColor: Colors.transparent,
elevation: 0,
actions: <Widget>[
GestureDetector(
onTap: () {
uploadBlog();
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Icon(
Icons.file_upload,
color: Colors.black,
)))
],
),
backgroundColor: Colors.white,
body: isloading
? Container(
alignment: Alignment.center,
child: CircularProgressIndicator(color: Colors.teal),
)
: Container(
child: Column(
children: <Widget>[
SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
getImage();
},
child: _selectedImage != null
? Container(
margin: EdgeInsets.symmetric(horizontal: 30),
height: 150,
width: MediaQuery.of(context).size.width,
child: Image.file(
_selectedImage!,
fit: BoxFit.cover,
),
)
: Container(
margin: EdgeInsets.symmetric(horizontal: 30),
height: 150,
width: MediaQuery.of(context).size.width,
child: Icon(Icons.add_a_photo),
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(6)),
),
),
SizedBox(
height: 8,
),
Container(
margin: EdgeInsets.symmetric(horizontal: 30),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: "Author Name"),
onChanged: (val) {
authorName = val;
},
),
TextField(
decoration: InputDecoration(hintText: "Title"),
onChanged: (val) {
title = val;
},
),
TextField(
decoration: InputDecoration(hintText: "Description"),
onChanged: (val) {
desc = val;
},
)
],
),
)
],
)),
);
}
}
crud.dart code:
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class CRUDMethods {
Future<void> addData(blogData) async {
FirebaseFirestore.instance
.collection("blogs")
.add(blogData)
.catchError((e) {
print(e);
});
}
}

Flutter - Variable in function available when building Widget

If I understood correctly (but clearly I don't) when you need a var available when you build the widget you need to call the function in the initState(). The function is 'void getDevices()'
I need var _documentsIds to build DropdownMenuItem.
var _documentsIds is docs ID from a query I make to FirebaseFirestore
How do I make _documentsIds available to be used in my Widget?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:safegaurd/constants.dart';
import 'package:flutter_time_picker_spinner/flutter_time_picker_spinner.dart';
import 'package:safegaurd/screens/log_in_page.dart';
import 'package:safegaurd/components/buttons_navigate.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'new_device_page.dart';
class DeviceSelectionPage extends StatefulWidget {
const DeviceSelectionPage({Key? key}) : super(key: key);
static const String id = 'device_selection_page';
#override
State<DeviceSelectionPage> createState() => _DeviceSelectionPageState();
}
class _DeviceSelectionPageState extends State<DeviceSelectionPage> {
final _auth = FirebaseAuth.instance;
User? loggedInUser;
final firestoreInstance = FirebaseFirestore.instance;
final String devices = 'devices';
List? _documentsIds;
bool showSpinner = false;
String? selectedValue;
final bool checkOne = false;
Color sDeviceAlways = Colors.white54;
Color sDeviceTime = Colors.white54;
FontWeight sDeviceAlwaysW = FontWeight.normal;
FontWeight sDeviceTimeW = FontWeight.normal;
#override
void initState() {
super.initState();
getCurrentUser();
getDevices();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
getDevices();
};
} catch (e) {
print(e);
}
}
void getDevices() async {
var firebaseUser = FirebaseAuth.instance.currentUser?.email;
print('firebaseUser: $firebaseUser');
var query = await firestoreInstance
.collection(devices)
.where('email', isEqualTo: '$firebaseUser')
.get();
var _documentsIds = query.docs.map((doc) => doc.id).toList();
print('_documentsIds: $_documentsIds');
}
#override
Widget build(BuildContext context) {
print('_documentsIds: $_documentsIds');
return Scaffold(
appBar: AppBar(
leading: null,
actions: [
IconButton(
onPressed: () {
_auth.signOut();
Navigator.pop(context);
},
icon: Icon(Icons.close))
],
title: const Text('Device Selection page'),
),
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
child: Text(
'SAFEGAURD',
style: kAppTextStyle,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 380,
padding: const EdgeInsets.symmetric(horizontal: 24.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.lightBlueAccent, width: 1.0),
borderRadius: kBorderRadius),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text(
'Safegaurd Devices',
style: TextStyle(color: Colors.white54, fontSize: 25),
),
style:
const TextStyle(color: Colors.orange, fontSize: 25),
borderRadius: kBorderRadius,
iconSize: 40,
elevation: 16,
onChanged: (value) {
setState(() {
selectedValue = value.toString();
setState(() {
selectedValue;
print(selectedValue);
});
});
},
value: selectedValue,
items: _documentsIds?.map((itemsList) {
return DropdownMenuItem<String>(
value: itemsList,
child: Text(itemsList),
);
}).toList(),
),
),
)
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Save Settings',
onPressed: () {},
width: 200,
),
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Claim new Device',
onPressed: () {
Navigator.pushNamed(context, NewDevicePage.id);
},
width: 200,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Buttons_Navigate(
colour: Colors.orange,
title: 'Back',
onPressed: () {
Navigator.pushNamed(context, LogInPage.id);
},
width: 40)
],
)
],
)),
));
}
}
wall, you can use futureBuilder and show A CircularProgressBar until the query is done check the documentation here: FutureBuilder
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:safegaurd/constants.dart';
//import 'package:flutter_time_picker_spinner/flutter_time_picker_spinner.dart';
import 'package:safegaurd/screens/log_in_page.dart';
import 'package:safegaurd/components/buttons_navigate.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'new_device_page.dart';
class DeviceSelectionPage extends StatefulWidget {
const DeviceSelectionPage({Key? key}) : super(key: key);
static const String id = 'device_selection_page';
#override
State<DeviceSelectionPage> createState() => _DeviceSelectionPageState();
}
class _DeviceSelectionPageState extends State<DeviceSelectionPage> {
final _auth = FirebaseAuth.instance;
User? loggedInUser;
final firestoreInstance = FirebaseFirestore.instance;
final String devices = 'devices';
List? _documentsIds;
bool showSpinner = false;
//bool _isSelected1 = false;
//bool _isSelected2 = false;
//DateTime _dateTime = DateTime.now();
String? selectedValue;
final bool checkOne = false;
Color sDeviceAlways = Colors.white54;
Color sDeviceTime = Colors.white54;
FontWeight sDeviceAlwaysW = FontWeight.normal;
FontWeight sDeviceTimeW = FontWeight.normal;
#override
void initState() {
super.initState();
getCurrentUser();
getDevices();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
getDevices();
};
} catch (e) {
print(e);
}
}
Future<List<dynamic>> getDevices() async {
var firebaseUser = FirebaseAuth.instance.currentUser?.email;
print('firebaseUser: $firebaseUser');
var query = await firestoreInstance
.collection(devices)
.where('email', isEqualTo: '$firebaseUser')
.get();
List<String> _documentsIds = query.docs.map((doc) => doc.id).toList();
print('_documentsIds: $_documentsIds');
return _documentsIds;
}
#override
Widget build(BuildContext context) {
print('_documentsIds: $_documentsIds');
return Scaffold(
appBar: AppBar(
leading: null,
actions: [
IconButton(
onPressed: () {
_auth.signOut();
Navigator.pop(context);
},
icon: Icon(Icons.close))
],
title: const Text('Device Selection page'),
),
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
child: Text(
'SAFEGAURD',
style: kAppTextStyle,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 380,
padding: const EdgeInsets.symmetric(horizontal: 24.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.lightBlueAccent, width: 1.0),
borderRadius: kBorderRadius),
child: DropdownButtonHideUnderline(
child: FutureBuilder<List> (
future: getDevices(),
builder: (BuildContext context, AsyncSnapshot<List> snapshot){
if (!snapshot.hasData) {
return const Text('Waiting Devices',style: TextStyle(color: Colors.white54, fontSize: 25));
} else {
return DropdownButton(
hint: const Text(
'Safegaurd Devices',
style: TextStyle(color: Colors.white54, fontSize: 25),
),
style:
const TextStyle(color: Colors.orange, fontSize: 25),
borderRadius: kBorderRadius,
iconSize: 40,
elevation: 16,
onChanged: (value) {
setState(() {
selectedValue = value.toString();
setState(() {
selectedValue;
print(selectedValue);
});
});
},
value: selectedValue,
items: snapshot.data?.map((_documentsIds) =>
DropdownMenuItem<String>(
value: _documentsIds,
child: Text(_documentsIds),
)
).toList(),
);
}
}
)
),
)
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Save Settings',
onPressed: () {},
width: 200,
),
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Claim new Device',
onPressed: () {
Navigator.pushNamed(context, NewDevicePage.id);
},
width: 200,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Buttons_Navigate(
colour: Colors.orange,
title: 'Back',
onPressed: () {
Navigator.pushNamed(context, LogInPage.id);
},
width: 40)
],
)
],
)),
));
}

I dont want to display all the records of table in listview but I want to display records of only particular customer in flutter

I have a screen which shows list of customers using listview. Next when I click on a customer I want to show the notes(records) only of that particular customer(customerId) in next screen in listview. I know how to display all the records of table. but how to display only certain records?? Neither there is any error nor the listview is being displayed. I dont know where am I going wrong.
List<CustomerNote> cnoteList;
int count = 0;
if (cnoteList == null) {
cnoteList = List<CustomerNote>();
updateCustomerNotes();
}
db_service.dart
Future<List<CustomerNote>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("noteDetails WHERE custId = '$customer'");
int count = res.length;
List<CustomerNote> cnotelist = List<CustomerNote>();
for (int i = 0; i < count; i++) {
cnotelist.add(CustomerNote.fromMap(res[i]));
}
return cnotelist;
}
People_List.dart //this is the file which displays list of customers
import 'package:customer/models/Note.dart';
import 'package:customer/models/addCustomer.dart';
import 'package:customer/screens/New_Note.dart';
import 'package:customer/screens/Note_info.dart';
import 'package:customer/screens/User_Settings.dart';
import 'package:customer/screens/add_person.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
class People_List extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return People_ListState();
}
}
class People_ListState extends State<People_List> with SingleTickerProviderStateMixin{
DBService dbService = DBService();
List<AddCustomer> customerList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
var _isSelectedItemIndex;
TextEditingController _searchQuery;
bool _isSearching = false;
String searchQuery = "Search query";
#override
void initState() {
super.initState();
_searchQuery = new TextEditingController();
}
void _startSearch() {
print("open search box");
ModalRoute
.of(context)
.addLocalHistoryEntry(new LocalHistoryEntry(onRemove: _stopSearching));
setState(() {
_isSearching = true;
});
}
void _stopSearching() {
_clearSearchQuery();
setState(() {
_isSearching = false;
});
}
void _clearSearchQuery() {
print("close search box");
setState(() {
_searchQuery.clear();
updateSearchQuery("Search query");
});
}
Widget _buildTitle(BuildContext context) {
var horizontalTitleAlignment =
Platform.isIOS ? CrossAxisAlignment.center : CrossAxisAlignment.start;
return new InkWell(
onTap: () => scaffoldKey.currentState.openDrawer(),
child: new Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: horizontalTitleAlignment,
children: <Widget>[
const Text(''),
],
),
),
);
}
Widget _buildSearchField() {
return new TextField(
controller: _searchQuery,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Search...',
border: InputBorder.none,
hintStyle: const TextStyle(color: Colors.white30),
),
style: const TextStyle(color: Colors.white, fontSize: 16.0),
onChanged: updateSearchQuery,
);
}
void updateSearchQuery(String newQuery) {
setState(() {
searchQuery = newQuery;
});
print("search query " + newQuery);
}
List<Widget> _buildActions() {
if (_isSearching) {
return <Widget>[
new IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
if (_searchQuery == null || _searchQuery.text.isEmpty) {
Navigator.pop(context);
return;
}
_clearSearchQuery();
},
),
];
}
return <Widget>[
new IconButton(
icon: const Icon(Icons.search),
onPressed: _startSearch,
),
];
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
if (customerList == null) {
customerList = List<AddCustomer>();
updateListView();
}
return Scaffold(
appBar: new AppBar(
leading: _isSearching ? const BackButton() : null,
title: _isSearching ? _buildSearchField() : _buildTitle(context),
actions: _buildActions(),
),
body:getCustomerListView(),
floatingActionButton: FloatingActionButton(
onPressed: () {
navigateToCustomer(AddCustomer(), 'Add Person');
},
child: const Icon(Icons.add),
),
bottomNavigationBar:Row (
children: <Widget>[
buildNavBarItem(Icons.home,0,"Home"),
buildNavBarItem(Icons.fiber_new_rounded,1,"Upcoming"),
buildNavBarItem(Icons.history,2,"History"),
buildNavBarItem(Icons.account_circle,3,"Account"),
],
),
);
}
ListView getCustomerListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
/*trailing: CircleAvatar(
backgroundColor: getPriorityColor(this.noteList[position].priority),
child: getPriorityIcon(this.noteList[position].priority),
),*/
title: Text(this.customerList[position].custName, style: titleStyle,),
//subtitle: Text(this.customerList[position].date),
onTap: () {
},
),
);
},
);
}
void navigateToCustomer(AddCustomer customer, String title) async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
return AddPerson(customer, title);
}));
if (result == true) {
updateListView();
}
}
void updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
Future<List<AddCustomer>> customerListFuture = dbService.getCustomerList();
customerListFuture.then((customerList) {
setState(() {
this.customerList = customerList;
this.count = customerList.length;
});
});
});
}
Widget buildNavBarItem(IconData icon,int index,title) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return GestureDetector(
onTap: () {
setState(() {
_isSelectedItemIndex=index;
if(_isSelectedItemIndex==3) {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => User_Settings()));
}
});
},
child: Container(
height: height * 0.09,
width: width / 4,
decoration: index==_isSelectedItemIndex?BoxDecoration(
border: Border(
bottom: BorderSide(width: 4,color: Theme.of(context).primaryColor),
),
gradient: LinearGradient(colors: [
Theme.of(context).primaryColor.withOpacity(0.3),
Theme.of(context).primaryColor.withOpacity(0.015),
],begin: Alignment.bottomCenter,end: Alignment.topCenter)
):BoxDecoration(),
child: Column(
children: <Widget>[
InkWell(
child: Icon(icon,
color: index==_isSelectedItemIndex? Theme.of(context).primaryColor:Colors.black54,
),
),
Text(title)
],)),
);
}
}
Note_Info.dart
class Note_Info extends StatefulWidget{
final String appBarTitle;
final AddCustomer customer;
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
return Note_InfoState(this.customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
CustomerNote note=CustomerNote();
DBService dbService = DBService();
List<CustomerNote> cnoteList;
int count = 0;
String appBarTitle;
AddCustomer customer;
Note_InfoState(this.customer, this.appBarTitle);
PickedFile _imageFile;
final ImagePicker _picker = ImagePicker();
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custNameController = TextEditingController();
void getImage(ImageSource source) async {
final pickedFile = await _picker.getImage(
source: source);
setState(() {
_imageFile = pickedFile;
});
}
#override
Widget build(BuildContext context) {
if (noteList == null) {
noteList = List<CustomerNote>();
updateCustomerNotes();
}
var height = MediaQuery.of(context).size.height;
custNameController.text = customer.custName;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote()));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNoteListView(),
),
// second tab bar view widget
Container(
child: Center(
child: Text(
'Pending Items',
),
),
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
void updateCustomerNotes() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int customerId=customer.custId;
Future<List<CustomerNote>> noteListFuture = dbService.getCustomerNotes(customerId);
noteListFuture.then((cnoteList) {
setState(() {
this.cnoteList = cnoteList;
//this.count = cnoteList.length;
});
});
});
}
ListView getNoteListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
title: Text(this.cnoteList[position].note, style: titleStyle,),
subtitle: Text(this.cnoteList[position].date),
trailing: GestureDetector(
child: Icon(Icons.delete, color: Colors.grey,),
onTap: () {
},
),
onTap: () {
},
),
);
},
);
}
void _showSnackBar(BuildContext context, String message) {
final snackBar = SnackBar(content: Text(message));
Scaffold.of(context).showSnackBar(snackBar);
}
Widget ImageProfile() {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('images/person_icon.jpg')
),
);
}
}
If u want to get some specific data from the server then you need to provide (where: ) in your query such as
List<Map> result = await db.query(
DatabaseHelper.table,
columns: columnsToSelect,
where: whereString,
whereArgs: whereArguments);
// print the results
result.forEach((row) => print(row));
// {_id: 1, name: Bob, age: 23}
}
Note your query can be different from the above one.
and if you want to get the same specific data from already fetched data then also you need to use the where clause such as
final outData = responseData.where((i) => i.userId == customerId).toList();
and then pass the outData to next page through params.

How to pass speech to text field in flutter?

I have an application in Flutter that translates speech to text, the problem is that I have not found a way to put the results in input or a TextField in Flutter, so far it only transcribes to text which cannot (obviously) be modified. How to put the results in a TextField?
This is my code:
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
class SpeechScreen extends StatefulWidget {
#override
_SpeechScreenState createState() => _SpeechScreenState();
}
class _SpeechScreenState extends State<SpeechScreen> {
stt.SpeechToText _speech;
bool _isListening = false;
String _textSpeech = 'Presiona el botón para iniciar a hablar';
void onListen() async {
bool available = await _speech.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'));
if (!_isListening) {
if (available) {
setState(() {
_isListening = false;
_speech.listen(
onResult: (val) => setState(() {
_textSpeech = val.recognizedWords;
}),
);
});
}
} else {
setState(() {
_isListening = false;
_speech.stop();
});
}
}
void stopListen() {
_speech.stop();
setState(() {});
}
#override
void initState() {
super.initState();
_speech = stt.SpeechToText();
}
#override
Widget build(BuildContext context) {
_fondoApp() {
final gradiente = Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(0.0, 1.0),
colors: [Colors.black87, Colors.black])),
);
return Stack(
children: <Widget>[gradiente],
);
}
return Scaffold(
body: Stack(children: <Widget>[
_fondoApp(),
Container(
padding: EdgeInsets.all(30.0),
child: Text(_textSpeech,
style: TextStyle(
fontSize: 32,
color: Colors.white,
fontWeight: FontWeight.w500))),
]),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
onPressed: onListen,
child: Icon(Icons.mic),
backgroundColor: Colors.green,
),
SizedBox(
width: 40,
),
SizedBox(
child: _speech.isListening
? Text(
"Escuchando...",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
)
: Text(
'Sin escuchar',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
),
SizedBox(
width: 40,
),
FloatingActionButton(
child: Icon(Icons.stop),
heroTag: "btn2",
backgroundColor: Colors.redAccent,
onPressed: () => stopListen(),
),
],
),
));
}
}
Your help would really be amazing, thank you.
We can create a TextField with a TextEditingController:
class _SpeechScreenState extends State<SpeechScreen> {
TextEditingControlller _textEditingController = TextEditingControlller();
Widget _buildTextController() {
return TextField(controller: _textEditingController);
}
}
By doing so, after we translate the speech to text, we can update the _textEditingController text:
void onListen() async {
bool available = await _speech.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'));
if (!_isListening) {
if (available) {
setState(() {
_isListening = false;
_speech.listen(
onResult: (val) => setState(() {
_textSpeech = val.recognizedWords;
_textEditingController.text = val.recognizedWords;
}),
);
});
}
} else {
setState(() {
_isListening = false;
_speech.stop();
});
}
}

Tap on Android camera Flutter driver

Im doing an integration test in Flutter and in the application I open the camera, but I don't know how to tap on the button to do the photo, anyone know how can I search for this button?
Here is the code if the app where you can choose between pic a photo with the camera or choose one picture of your gallery
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import 'package:random_string/random_string.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:rosita/language/firebase_remote.dart';
import 'package:rosita/api/api_provider.dart';
import 'package:rosita/constants/common.dart';
import 'package:rosita/model/image_object.dart';
import 'package:rosita/model/senior_user.dart';
import 'package:rosita/modules/widgets/button_ui.dart';
import 'package:rosita/rosita.dart';
class AddProfileImageScreen extends StatefulWidget {
const AddProfileImageScreen({Key key, this.seniorUser}) : super(key: key);
final SeniorUser seniorUser;
#override
_AddProfileImageScreenState createState() => _AddProfileImageScreenState();
}
class _AddProfileImageScreenState extends State<AddProfileImageScreen> {
bool _isProcessing = false;
File _image;
bool _enableButton = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: ModalProgressHUD(
inAsyncCall: _isProcessing,
color: Colors.transparent,
progressIndicator: const CircularProgressIndicator(
strokeWidth: 2.0,
),
child: Container(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height,
minWidth: MediaQuery.of(context).size.width),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
darkSubtitleText('choose_profile_picture', context),
Expanded(
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: Card(
shape: RoundedRectangleBorder(
side: const BorderSide(
color: AppTheme.purpleColor,
width: 4,
),
borderRadius: BorderRadius.circular(60.0),
),
elevation: 0,
color: Theme.of(context).dividerColor,
child: _image == null
? (widget.seniorUser != null &&
widget.seniorUser.profileImage != null &&
widget.seniorUser.profileImage.imageUrl !=
'')
? CachedNetworkImage(
imageUrl:
widget.seniorUser.profileImage.imageUrl,
placeholder:
(BuildContext context, String url) =>
Image.asset(ConstantsData.appIcon),
errorWidget: (BuildContext context,
String url, error) =>
const Icon(Icons.error),
fit: BoxFit.cover,
)
: Image.asset(ConstantsData.appIcon)
: Image.file(_image),
),
),
),
),
ButtonUI(
buttonName: 'ProfilePhotoFromCameraButton',
key: const Key(Keys.cameraButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('take_a_photo_with_your_camera'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: false);
},
),
verticalSpacer(),
ButtonUI(
buttonName: 'ProfilePhotoFromGalleryButton',
key: const Key(Keys.galleryButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('choose_from_gallery'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: true);
},
),
verticalSpacer(),
if (_image != null || _enableButton)
ButtonUI(
buttonName: 'ProfilePhotoUploadButton',
key: const Key(Keys.uploadButton),
isTrack: true,
color: AppTheme.purpleColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('continue_txt'),
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
_uploadAllInformation();
},
),
],
),
),
),
),
);
}
Future<void> getImage({bool isGallery = true}) async {
await <Permission>[Permission.camera, Permission.storage].request();
if (await Permission.storage.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
if (!isGallery &&
await Permission.camera.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
final image = await ImagePicker.pickImage(
source: isGallery ? ImageSource.gallery : ImageSource.camera);
if (image == null) return;
final cropimage = await cropImage(image);
if (cropimage == null) return;
setState(() {
_image = cropimage;
});
}
Future<File> cropImage(File imageFile) async {
final croppedFile = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
statusBarColor: Theme.of(context).primaryColor,
toolbarColor: Theme.of(context).primaryColor,
toolbarWidgetColor: Theme.of(context).backgroundColor,
),
sourcePath: imageFile.path,
cropStyle: CropStyle.circle,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
maxWidth: 420,
maxHeight: 420,
);
return croppedFile;
}
Future<void> _uploadAllInformation() async {
setState(() {
_isProcessing = true;
});
widget.seniorUser.documentId =
(await FirebaseAuth.instance.currentUser()).uid;
widget.seniorUser.referralCode =
'RO-' + randomAlphaNumeric(8).toUpperCase();
widget.seniorUser.enterReferralCode = deepLinkReferralCode;
await ApiProvider().createSeniorUserProfile(widget.seniorUser);
endRegister = true;
if (!_enableButton) {
final imageData = await updateProfilePic(widget.seniorUser);
await ApiProvider()
.updateRositaProfileImage(imageData, widget.seniorUser.documentId);
}
setState(() {
_isProcessing = false;
});
Rosita.restartApp(context);
}
Future<ImageObject> updateProfilePic(SeniorUser user) async {
final imagename = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg';
final url = await ApiProvider()
.updateProfilePic('rositapics/${user.documentId}/' + imagename, _image);
final profileImage = ImageObject();
profileImage.imageUrl = url.toString();
profileImage.firebaseStoregPath =
'rositapics/${user.documentId}/' + imagename;
profileImage.imageName = imagename;
return profileImage;
}
}