How to implement multiple packages in main.dart in flutter? - android

I am developing one app in flutter-android, for that, I am using screenUtil package and also I am checking device connection status(internet). Now my main.dart code is below where I have initialized screenUtil
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: Size(360, 690),
allowFontScaling: false,
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
}
This is the code I need to use in my main.dart to get the connection status across my widgets:
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamProvider<ConnectivityStatus>(
builder: (context) => ConnectivityService().connectionStatusController,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
How can I use both the codes in my main.dart file?

Example : internet connection check programmatically in flutter.
You can sync with my code.
like these my source code below in details. just copy and past then modify with yours code
it is main.dart file:
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: Size(360, 690),
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
}
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var connectionStatus="";
#override
void initState() {
// TODO: implement initState
super.initState();
checkConnection();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(connectionStatus),
),
);
}
void checkConnection() async{
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
// write your code here;
connectionStatus="mobile data";
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
// write your code here
connectionStatus="wifi data";
} else {
// where your code here
connectionStatus="no internet connection";
}
}
}
and my pubspec.yaml file
name: flutter_app
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_screenutil: ^5.0.0
data_connection_checker: ^0.3.4
connectivity: ^3.0.2
connectivity_platform_interface: ^2.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
best of luck!

Related

Flutter local notifications doesn't grant permissions on Android

flutter_local_notifications doesn't show permissions dialog on Android API level 33. Tested with emulator. In AndroidManifest.xml file, I've defined the needed permission:
This is an example code:
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> setup() async {
final _localNotificationsPlugin = FlutterLocalNotificationsPlugin();
const androidSetting = AndroidInitializationSettings('#mipmap/ic_launcher');
const initSettings = InitializationSettings(android: androidSetting);
await _localNotificationsPlugin.initialize(initSettings).then((_) {
debugPrint('setupPlugin: setup success');
}).catchError((Object error) {
debugPrint('Error: $error');
});
bool? granted = await _localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.requestPermission() ?? false;
print('granted: $granted');
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
setup();
runApp(myApp());
}
class myApp extends StatelessWidget {
myApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Text('Notification test')
)
)
);
}
}

fix net::err_unknown_url_scheme whatsapp link on flutter webview

Please I want to know how to launch WhatsApp in the Flutter webview app or launch WhatsApp from the browser in Flutter, have used many codes with no errors but they do not work.Am using mac m1
and vscode
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/services/local_notification_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'homepage.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:colorful_safe_area/colorful_safe_area.dart';
/// Receive message when app is in background solution for on
message
Future<void> backgroundHandler(RemoteMessage message)async{
print(message.data.toString());
print(message.notification!.title);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
LocalNotificationServices.initialize();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ConnectivityProvider(),
child: HomePage(),
)
],
child:MaterialApp(
title: 'coinpaga',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: ColorfulSafeArea(
color: HexColor("#2e2a42"),
top: true,
bottom: false,
left: false,
right: false,
child: HomePage(),
)
),
);
}
}
Home.dart
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/no_internet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
// ignore: unused_field
final _flutterwebview = FlutterWebviewPlugin();
HomePage({ Key? key }) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
Provider.of<ConnectivityProvider>(context, listen:
false).startMonitoring();
}
#override
Widget build(BuildContext context) {
return pageUI();
}
#override
void dispose() {
_flutterwebview.dispose();
super.dispose();
}
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (context, model, child) {
return model.isOnline
? WebviewScaffold(
url: 'https://coinpaga.com',
withLocalStorage: true,
withJavascript: true,
scrollBar: false,
initialChild: Center(child: Text('Loading...')),
) : NoInternet();
},
);
}
// ignore: camel_case_types
class _flutterwebview {
static void dispose() {}
}
Please help me go through it.
String text = "Hello World !! Hey There";
String url = "https://wa.me/?text=${Uri.encodeFull(text)}";
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication);
}
First, add url_launcher, then I use this code to launch whatsapp on flutter webview and works.
WebView(
initialUrl: getUrl(_url),
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
if (request.url
.startsWith('https://api.whatsapp.com/send?phone')) {
print('blocking navigation to $request}');
List<String> urlSplitted = request.url.split("&text=");
String phone = "0123456789";
String message =
urlSplitted.last.toString().replaceAll("%20", " ");
await _launchURL(
"https://wa.me/$phone/?text=${Uri.parse(message)}");
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
)
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
You can use url_launcher to launch URLs.
You can give https://api.whatsapp.com/send/?phone=(phone_number) URL to launch.
For the launching the WhatsApp Website use launch('https://api.whatsapp.com/send/?phone=(phone_number)')
Make sure you give your country code without (+).

how create a RIVE animation with flutter

I want to create a RIVE animation with flutter. I followed a tutorial in YouTube. I wrote the same thing but when I execute two errors is displayed
(RiveFile.import (data);
file.mainArtboard;)
Here is the code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rive/rive.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Using Rive'),
),
body: RocketContainer());
}
}
class RocketContainer extends StatefulWidget {
#override
_RocketContainerState createState() => _RocketContainerState();
}
class _RocketContainerState extends State<RocketContainer> {
Artboard _artboard;
RiveAnimationController _rocketController;
#override
void initState() {
_loadRiveFile();
super.initState();
}
void _loadRiveFile() async {
final bytes = await rootBundle.load('assets/rocket.riv');
final file = RiveFile.import(bytes);
setState(() {
_artboard = file.mainArtboard;
});
}
void _launch() async {
_artboard.addController(
_rocketController = SimpleAnimation('launch'),
);
setState(() => _rocketController.isActive = true);
}
void _fall() async {
_artboard.addController(
_rocketController = SimpleAnimation('fall'),
);
setState(() => _rocketController.isActive = true);
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - 250,
child: _artboard != null
? Rive(
artboard: _artboard,
fit: BoxFit.cover,
)
: Container()),
TextButton(onPressed: () => _launch(), child: Text('launch')),
TextButton(onPressed: () => _fall(), child: Text('fall'))
],
);
}
}
errors:
The current Dart SDK version is 2.10.5.
Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.
pub get failed (1; Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.)
*error: Instance member 'import' can't be accessed using static access. (static_access_to_instance_member at [animation] lib\main.dart:47)
*error: The getter 'mainArtboard' isn't defined for the type 'bool'. (undefined_getter at [animation] lib\main.dart:50)
You could have a look at the example provided with the updated and latest documentation of Rive in their official Github repository.
Control playing and pausing a looping animation:
import 'package:flutter/material.dart';
import 'package:rive/rive.dart';
class PlayPauseAnimation extends StatefulWidget {
const PlayPauseAnimation({Key? key}) : super(key: key);
#override
_PlayPauseAnimationState createState() => _PlayPauseAnimationState();
}
class _PlayPauseAnimationState extends State<PlayPauseAnimation> {
// Controller for playback
late RiveAnimationController _controller;
// Toggles between play and pause animation states
void _togglePlay() =>
setState(() => _controller.isActive = !_controller.isActive);
/// Tracks if the animation is playing by whether controller is running
bool get isPlaying => _controller.isActive;
#override
void initState() {
super.initState();
_controller = SimpleAnimation('idle');
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RiveAnimation.network(
'https://cdn.rive.app/animations/vehicles.riv',
controllers: [_controller],
// Update the play state when the widget's initialized
onInit: () => setState(() {}),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _togglePlay,
tooltip: isPlaying ? 'Pause' : 'Play',
child: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
To play an animation from an asset bundle, use:
RiveAnimation.asset('assets/vehicles.riv'
in place of
RiveAnimation.network('https://cdn.rive.app/animations/vehicles.riv',
This line:
_controller = SimpleAnimation('idle');
attempts to play an animation called 'idle'. If your animation is named differently, try replacing the name here.

iOS implementing camera in flutter

I'm trying to implement the camera package in flutter for android and iOS devices,
On android I don't have any problem but in iOS i get this error:
The following StateError was thrown building Builder:
Bad state: No element
When the exception was thrown, this was the stack:
#0 List.first (dart:core-patch/growable_array.dart:332:5)
#1 _CameraState.initState (package:glass_case_flutter/controllers/camera_controller.dart:21:45)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4632:57)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4469:5)
... Normal element mounting (24 frames)
this is the code of main.dart:
List<CameraDescription> cameras;
Future<Null> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
await Firebase.initializeApp();
runApp(GlassCase());
}
class GlassCase extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(fontFamily: 'Nunito'),
initialRoute: WelcomeScreen.id,
routes: {
WelcomeScreen.id: (context) => WelcomeScreen(),
RegistrationScreen.id: (context) => RegistrationScreen(),
ResetPassword.id: (context) => ResetPassword(),
HomeScreen.id: (context) => HomeScreen(cameras),
ProfileScreen.id: (context) => ProfileScreen()
},
);
}
}
this is the code of my homepage.dart where I call camera.dart:
IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Camera(widget.cameras)));
},
color: Colors.black,
),
this is my camera.dart, that is very simple, just turn on the camera:
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class Camera extends StatefulWidget {
List<CameraDescription> cameras;
Camera(this.cameras);
#override
_CameraState createState() => _CameraState();
}
class _CameraState extends State<Camera> {
CameraController controller;
#override
void initState() {
super.initState();
controller =
new CameraController(widget.cameras.first, ResolutionPreset.high);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return new Container();
}
return new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
);
}
}
I added this in my Info.plist to access the camera and microphone:
<key>NSCameraUsageDescription</key>
<string>Enable to access your camera to capture your photo</string>
<key>NSMicrophoneUsageDescription</key>
<string>Enable to access mic to record your voice</string>
I don't understand why in Android it work but in iOS I get that error, somebody can help me ?
Thank so much !

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