I have written my code properly and installed all packages yet it errors out for a variable.
please help me
I am using the speech to text module and have imported and installed it but it is erroring
and i am new to flutter so please help me
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Voice',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SpeechScreen(),
);
}
}
class SpeechScreen extends StatefulWidget {
#override
_SpeechScreenState createState() => _SpeechScreenState();
}
class _SpeechScreenState extends State<SpeechScreen> {
stt.SpeechToText _speech;
bool _isListening = false;
String _text = 'Press the button to start speaking';
double _confidence = 1.0;
#override
Widget build(BuildContext context) {
return Container();
}
}
thank you
stt.SpeechToText _speech;
You have to initialize this property or make it nullable as below
stt.SpeechToText? _speech;
Related
I have A Project. After i implement cubit to my project on real phone i cant tap anywhere. Like its frozen. But on emulator its works without a problem. When i dont use cubit its works. What is wrong with it ? Thanks for responses.
Code :
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
theme: ThemeData(
fontFamily: 'Inter', backgroundColor: const Color(0xffFBF8FF)),
home: DismissKeyboard(child: AuthController()),
);
}
}
class AuthController extends StatefulWidget {
const AuthController({Key? key}) : super(key: key);
#override
State<AuthController> createState() => _AuthControllerState();
}
class _AuthControllerState extends State<AuthController> {
_AuthControllerState();
#override
Widget build(BuildContext context) {
return BlocProvider<AuthCubit>(
create: (context) => AuthCubit(repository: AuthService()),
child: BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if (state is AuthUnAuthenticated) {
return LoginScreen();
} else if (state is AuthAuthenticated) {
return HomeScreen();
} else {
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
},
),
);
I Can see LoginScreen with that code. But cant click anywhere on real phone.
Cubit:
class AuthCubit extends Cubit<AuthState> {
AuthCubit({required this.repository}) : super(AuthLoaded()) {
checkToken();
}
final AuthService repository;
void checkToken() async {
final token = await UserSecureStorage.getField("token");
if (token == null)
emit(AuthUnAuthenticated());
else
emit(AuthAuthenticated());
}
Writing on the page can not be converted to the page display the error message
... .... flutter ... ... dart
.......... application restart ..................
my code...
main
Future<void> main() async {
runZonedGuarded(() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails errorDetails) {
print('This is an error on the Flutter SDK');
// print(errorDetails.exception);
print('-----');
// print(errorDetails.stack);
};
runApp(const MyApp());
}, (error, stackTrace) {
print('This is a pure Dart error');
// print(error);
print('-----');
// print(stackTrace);
});
}
myApp
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: (BuildContext context, Widget? widget) {
ErrorWidget.builder =
(FlutterErrorDetails errorDetails) => const ErrorPage();
return widget!;
},
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const MyApp());
}
}
As in the titel, I have a problem with ListView and I hope you can help me out.
I am using a basic ListView to build "Card Widgets" (with their own state). The ListView uses a List of Ids, which are used to build those "Card Widgets"
The problem:
Any time I remove a card from the list by deleting an Id the ListView always removes the top most Child Widget. My backend deletes the right things, becouse after I restart the app so that the page gets populated anew, the deleted card is actually deleted and the one the removed by the ListView is visible again. It seems like ListView does not redraw it's children. Any Idea what is going on?
I created basic DartPad code to illustrate the problem
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<String> dd = new List<String>();
#override
void initState() {
super.initState();
dd.add('A');
dd.add('B');
dd.add('C');
dd.add('D');
}
void _incrementCounter() {
setState(() {
_counter++;
dd.insert(1, 'Q');
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title + _counter.toString()),
),
body: ListView.builder(
addAutomaticKeepAlives: false,
itemBuilder: (context, index) {
print('calling: $index :' + _counter.toString() + ' -> ' + dd[index] );
return new CRD(title: dd[index]);
},
itemCount: dd.length
),
/*
ListView(
children: dd.map((str) {
return CRD(title: str);
}).toList()
),
*/
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class CRD extends StatefulWidget {
CRD({Key key, this.title}) : super(key: key);
final String title;
#override
_CRD createState() => _CRD();
}
class _CRD extends State<CRD> {
String _val;
#override
void initState() {
super.initState();
_val = widget.title + ' ' + widget.title;
}
#override
Widget build(BuildContext context) {
return Text(_val);
}
}
So after clicking once on the Add button the list content is [A,Q,B,C,D] but the app displays [A,B,C,D,D]. Whats going on here? Am i missing something?
Your CRD widget is a StatefulWidget and the state will be reused when rebuilding since the type of the widget is the same an you did not give it a key.
To solve your issue there are a few possibilities:
Add a key to all the items in the list
Implement the didUpdateWidget method in the state of your widget
Use a statelesswidget and do the string concatination in the build method
I was trying to learn Flutter SizeTransition. I used SizeTransition and provided sizeFactor as animation and provided tween from 0 to 1. I made a function execute in build that gets exectued after some seconds, What I expected was that the size of logo will increase and decrease when animation is forward and reverse respectively. But what I noticed that logo first moves down and then goes back up.(like a Slide Transition)
widget to test for SizeTransition
import 'dart:async';
import 'package:flutter/material.dart';
class LogoApp extends StatefulWidget {
_LogoAppState createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with TickerProviderStateMixin {
AnimationController _animationController;
Animation<double> _animation;
#override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: Duration(seconds: 4));
_animation = _animationController.drive(Tween(begin: 0, end: 1));
}
int ctr = 0;
#override
Widget build(BuildContext context) {
ctr += 1;
print("build$ctr");
execute(); //function that executes forward()/reverse() methods of animationController
return SizeTransition(
sizeFactor: _animation,
child: Center(
child: FlutterLogo(),
),
);
}
void execute() async {
Future.delayed(const Duration(seconds: 2), () {
_animationController.forward();
});
Future.delayed(const Duration(seconds: 4), () {
_animationController.reverse();
});
}
}
main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: LogoApp(),
);
}
}
I have tried a lot but no success. What else can I do?
I think what you actually meant to implement was a ScaleTransition() instead of a SizeTransition().
It's a pretty straightforward fix:
int ctr = 0;
#override
Widget build(BuildContext context) {
ctr += 1;
print("build$ctr");
execute(); //function that executes forward()/reverse() methods of animationController
return Center(
child: ScaleTransition(
scale: _animation,
child: FlutterLogo(),
),
);
}
You also need to move the Center() widget one level up (as shown in the code) to ensure that the entire animation is anchored to the center of the display - as you originally intended it to be.
I'm trying to Play a custom mp3 sound I've put in an asset folder into the app folder, like you would do for a font or an image file, but then I don't really know how to proceed. I think I might need to register the audio file into the pubspec.yaml, but how?
And how do I play it?
I've checked out this two answer:
How to play a custom sound in Flutter?
Flutter - Play custom sounds updated?
But the first one is too old and the second one uses URLs as the sound path: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; and the sound I like to play is in the app, not online. So... How can I do it?
This Is My Current Code, as You can see, there's only a Floating Button.
And I need To Start The Sound at the Point I stated it in the code.
But visual studio underlines in red Various Parts:
await: it says that await is unrecognized.
audioPlugin.play: is says It's also unrecognized
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
print("Button Pressed");
///
///
///
/// Here I Need To start Playing the Sound
///
///
///
///
audioPlugin.play(tempFile.uri.toString(), isLocal: true);
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
It's not pretty, but...
Add the mp3 file to the assets folder and add it to pubspec.yaml like this.
Load the asset as binary data with rootBundle.load(asset)
Use path_provider to get the app's temp folder location
Use regular dart:io to open a file in tempDir (maybe use the asset name) and write bytes to it.
Form a file URL from the temporary file name in the form file:///folderPath/fileName
Pass this to audioplayer, setting isLocal to true (needed on iOS).
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:audioplayer/audioplayer.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Audio Player Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AudioPlayer audioPlugin = AudioPlayer();
String mp3Uri;
#override
void initState() {
_load();
}
Future<Null> _load() async {
final ByteData data = await rootBundle.load('assets/demo.mp3');
Directory tempDir = await getTemporaryDirectory();
File tempFile = File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
mp3Uri = tempFile.uri.toString();
print('finished loading, uri=$mp3Uri');
}
void _playSound() {
if (mp3Uri != null) {
audioPlugin.play(mp3Uri, isLocal: true);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Audio Player Demo Home Page'),
),
body: Center(),
floatingActionButton: FloatingActionButton(
onPressed: _playSound,
tooltip: 'Play',
child: const Icon(Icons.play_arrow),
),
);
}
}
Use the audioplayers package => https://pub.dev/packages/audioplayers
Add the key to plist for iOS Support
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Add dependencies to pubspec.yaml file
audioplayers: ^0.13.2
Flutter code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
class AudioTest extends StatefulWidget {
#override
_AudioTestState createState() => _AudioTestState();
}
class _AudioTestState extends State<AudioTest> {
static AudioCache _player = AudioCache();
static const _audioPath = "count_down.mp3";
AudioPlayer _audioPlayer = AudioPlayer();
Future<AudioPlayer> playAudio() async {
return _player.play(_audioPath);
}
void _stop(){
if (_audioPlayer != null) {
_audioPlayer.stop();
}
#override
void initState() {
playAudio().then((player) {
_audioPlayer = player;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return homeScreen();
}
Widget homeScreen() {
return Scaffold();
//Enter your code here
}
}