Flutter Push to another page if a critical error occurs - android

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

Related

ThemeMode is null in debug console

I am implementing ThemeMode feature on my fluter app for example if user have saved ThemeMode (light, dark or system) saved in SharedPreferences then it should load on app startup otherwise bydefault it is light. so i am using Provider for state management.
Here is my approach:
on themes_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/themes.dart';
class ThemesProvider extends ChangeNotifier {
ThemeMode? _themeMode;
ThemeMode? get themeMode => _themeMode;
ThemeData get lightTheme => ThemeManager().lightTheme;
ThemeData get darkTheme => ThemeManager().darkTheme;
void initThemeMode() async {
final _prefs = await SharedPreferences.getInstance();
final _currentTheme = _prefs.getString('theme') ?? 'light';
if (_currentTheme == 'light') {
_themeMode = ThemeMode.light;
} else if (_currentTheme == 'dark') {
_themeMode = ThemeMode.dark;
} else {
_themeMode = ThemeMode.system;
}
notifyListeners();
}
void setThemeMode(int value) async {
final _prefs = await SharedPreferences.getInstance();
_prefs.setInt('theme', value);
notifyListeners();
}
}
and then on main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
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 MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => UserProvider()),
ChangeNotifierProvider(
create: (context) => ThemesProvider(),
)
],
builder: (context, snapshot) {
final _themeNotifier =
Provider.of<ThemesProvider>(context, listen: false);
_themeNotifier.initThemeMode();
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: _themeNotifier.lightTheme,
darkTheme: _themeNotifier.darkTheme,
themeMode: _themeNotifier.themeMode,
home: HomeScreen(),
onGenerateRoute: RouteGenerator.generateRoute,
initialRoute: RouteGenerator.loginRoute,
);
});
}
}
But in debug console i am getting null value on _themeNotifier.themeMode
please help.

how can I use flutter_phone_direct_caller packages for real

I run below code but it's not working for real
import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: _callNumber,
child: Text('Call Number'),
),
),
));
}
}
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
bool? res = await FlutterPhoneDirectCaller.callNumber(number);
}
how can i run for real???
Should I have to build apk and run in real phone..?
I think for call dialer or Direct navigate to the dialer, the best package will be url_launcher. At first please install the package & then try the below code ---
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: _callNumber,
child: Text('Call Number'),
),
),
));
}
}
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
if (!await launchUrl(Uri.parse("tel://$number"))) throw 'Could not launch ${Uri.parse("tel://$number")}';
}
Basically, I change the code inside the _callnumber method which is
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
if (!await launchUrl(Uri.parse("tel://$number"))) throw 'Could not launch ${Uri.parse("tel://$number")}';
}

My flutter code is erroring even though the code is right

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;

Firebase initializeApp before runApp in flutter takes a lot of time

My question is how to show a splash screen or alternatively show a loading screen if I execute the following code:
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
You can simply use Future Builder for that,
void main() async{
WidgetsFlutterBinding.ensureInitialized();
//remove this line from your code
//await Firebase.initializeApp();
runApp(MyApp());
}
this is code for MyApp()
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return LoginWrapper();
}
return SplashScreen();
},
),
);
}
}
it shows your SplashScreen while loading your firebase App ;)

Play a Custom Sound in Flutter

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

Categories

Resources