I'm using easy Localization Package in 2 languages Application ,,And I Need To swith langauge using a Button . How could i Do That?
await EasyLocalization.ensureInitialized();
log(token);
runApp(
EasyLocalization(
supportedLocales: const [Locale('ar'), Locale('en')],
path: 'assets/translations',
startLocale: const Locale('ar'),
fallbackLocale: const Locale('en'),
saveLocale: true,
assetLoader: const CodegenLoader(),
child: ScreenUtilInit(
designSize: const Size(411.4, 683.4),
child: const MyApp(),
builder: (context, child) => child!,
),
),
);
There is lesson explain the right way to make it:
Source_code_in_github
Explain Localization with provider and shared preferences
There are some steps you should follow:
Add packages provider and shared_preferneces.
Create folder name it as l10n.
Add language json file in l10n folder as *.arb i.e app_ar.arb and app_en.arb.
Add Dart file in l10n folder name it: l10n.dart.
Write what you need in arb files like this: "youKey":"your_value first letter of key must be small letter camelCase, no _ nor -. i.e
{
"application": "application",
"setting": "settings",
"langAR": "Arabic",
"langEN": "English",
"blue": "blue",
"green": "green",
"purple": "purple"
}
add your list language to l10n.dart.
import 'package:flutter/cupertino.dart';
class L10n {
static final all = [const Locale('ar'), const Locale('en')];
}
Create l10n.yaml file in the root space of your project and write in it:
arb-dir: lib/l10n
template-arb-file: app_en.arb
out-localization-file: app_local.dart
Then in your terminal run flutter pub get that will generate the classes that contain all you properties of your languages.
Add new dart file name i.e app_local.dart with this code:
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class AppLocal {
static AppLocalizations? _loc;
static AppLocalizations get loc {
return AppLocal._loc!;
}
static void init(BuildContext context) {
_loc = AppLocalizations.of(context);
}
}
Add dart file name it i.e setting_provider.dart:
import 'package:flutter/cupertino.dart';
class SettingProvider extends ChangeNotifier {
String? local;
updateLocal(String? lang) {
local = lang;
notifyListeners();
}
}
Add dart file name it i.e shared_pref.dart:
import 'package:shared_preferences/shared_preferences.dart';
class SharedPref {
static String? lang;
static addLang(String lang) async {
SharedPreferences sp = await SharedPreferences.getInstance();
sp.setString('lang', lang);
}
static Future<String?> getLang() async {
SharedPreferences sp = await SharedPreferences.getInstance();
lang = sp.getString('lang');
return lang;
}
}
Write in your main function:
Future<void> main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
await SharedPref.getLang();
runApp(const MyApp());
}
and then in MyApp class return the provider like:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => SettingProvider())
],
child: Builder(
builder: (context) {
return MaterialApp(
supportedLocales: L10n.all,
locale: Locale(Provider.of<SettingProvider>(context).local ??
SharedPref.lang ??
'en'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
title: 'Localization',
home: const HomePage(),
);
},
),
);
}
}
Finally call the language in any class as in my example HomePage:
Widget build(BuildContext context) {
AppLocal.init(context);
SettingProvider prov = Provider.of(context);
return Scaffold(
appBar: AppBar(
title: Text(AppLocal.loc.application),
),
body: Column(
children: [
Wrap(
children: List.generate(L10n.all.length, (index) {
return RadioListTile(
title: Text(
L10n.all[index].languageCode == 'en'
? AppLocal.loc.langEN
: AppLocal.loc.langAR,
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w900,
),
),
value: L10n.all[index].languageCode,
groupValue: prov.local,
onChanged: (String? value) {
SharedPref.addLang(value!);
prov.updateLocal(value);
},
);
}),
),
Center(
child: Text(
AppLocal.loc.setting,
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w900,
),
),
),
],
),
);
}
}
you need to import easy localization package
import 'package:easy_localization/easy_localization.dart'
Then pass a parameter ('ar' or 'en')
ElevatedButton(
onPressed: () {
setState(() {context.setLocale(Locale('en')); //ar});
},
Related
I'm a student and I don't learn mobile development at my school. I really appreciate it if anyone could help me. I dunno how to fix the error and I tried countless times.
Error: Could not find the correct Provider above this Builder Widget. This happens because you used a 'BuildContext' that does not include the provider of your choice.
The relevant error-causing widget was
ConsumptionDialog. 2 files were involved in this error.
1st File: consumption_dialog.dart
class ConsumptionDialog extends StatefulWidget {
#override
_ConsumptionDialogState createState() => _ConsumptionDialogState();
}
class _ConsumptionDialogState extends State<ConsumptionDialog> {
final _form = GlobalKey<FormState>();
String? _text;
String? _validateText(String? value) {
if (value == null) {
return "2000 ml minimun";
}
final number = int.tryParse(value);
if (number != null && number >= 2000) {
return null;
}
return "2000 ml minimum";
}
#override
Widget build(BuildContext context) {
final bloc = context.watch<WaterBloc>();
return AlertDialog(
title: Text(
"Daily consumption",
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
content: Form(
key: _form,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Change your daily water consumption goal, in milliliters.",
textAlign: TextAlign.center,
),
SizedBox(height: 12),
TextFormField(
maxLength: 4,
initialValue: bloc.state.recommendedMilliliters.toString(),
keyboardType: TextInputType.number,
onSaved: (value) => _text = value,
validator: _validateText,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: InputDecoration(
hintText: "2000 ml",
counterText: "",
),
),
SizedBox(height: 24),
PrimaryButton(
onPressed: () {
if (_form.currentState?.validate() ?? false) {
_form.currentState?.save();
FocusScope.of(context).unfocus();
context.read<WaterBloc>().setRecommendedMilliliters(
int.parse(_text!),
);
Navigator.of(context).pop();
}
},
title: "Confirm",
),
SizedBox(height: 10),
SecondaryButton(
onPressed: () => Navigator.of(context).pop(),
title: "Cancel",
),
],
),
),
);
}
}
The error is shown inline:
Widget build(BuildContext context) {
final bloc = context.watch<WaterBloc>();
return AlertDialog(
2nd File: dialog.dart
import 'package:flutter/material.dart';
import 'package:animations/animations.dart';
import 'package:stayhydratedpal/widgets/confirmation_dialog.dart';
import 'package:stayhydratedpal/widgets/consumption_dialog.dart';
Future<bool> showConfirmationDialog(
BuildContext context, {
required String title,
required String content,
}) async {
final bool confirmed = await showModal(
context: context,
builder: (context) {
return ConfirmationDialog(
title: title,
content: content,
onConfirm: () => Navigator.of(context).pop(true),
onCancel: () => Navigator.of(context).pop(false),
);
},
) ??
false;
return confirmed;
}
Future<void> showConsumptionDialog(BuildContext context) {
return showModal(
context: context,
builder: (context) => ConsumptionDialog(),
);
}
The error is shown inline:
Future<void> showConsumptionDialog(BuildContext context) {
return showModal(
context: context,
builder: (context) => ConsumptionDialog(),
);
}
The way provider works is when you do Provider.of<T>(context)(The context must be a descendent of the widget where you injected T) it looks up the tree to find the T that you injected using Provider(create: (_)=> T())(can be ChangeNotifierProvider too doesn't matter). Also routes in the navigator stack aren't a parent of each other
they are
-> page1
-> page2
not
-> page1
-> page2
So this means when you use the Navigator to push a new page, Provider won't be able to find the injected provider you put on page1. And showModal uses Navigator push to open a dialog so basically just like any other route which means your ConfirmationDialog isn't finding the WaterBloc which you probably injected in the page you are opening it from.
One way to solve this is inject WaterBloc above the Navigator, MaterialApp contains the root navigator so inject the provider above Material App.
Another way is when opening the dialog you can do
Future<void> showConsumptionDialog(BuildContext context) {
return showModal(
context: context,
builder: (_) => Provider.value(
value: context.read<WaterBloc>(), // this context must be a descendent of the widget where you injected WaterBloc
child: ConsumptionDialog(),
),
);
}
A small tip, I would recommend you to learn Inherited Widgets a bit if you learn them well you can use Provider pretty easily, because Provider is just a wrapper over InheritedWidget
I am new to Flutter. I am building a quiz app and have the following three dart files:
main.dart
import 'package:flutter/material.dart';
import './answer.dart';
import './question.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
State<StatefulWidget> createState(){
return _MyAppState();
}
}
class _MyAppState extends State<MyApp>{
var _questionIndex = 0;
_answerQuestion(){
setState(() {
_questionIndex = _questionIndex + 1;
});
}
#override
Widget build(BuildContext context) {
var questions = [
{'questionText': 'What\'s your favourite color ?',
'answers': ['Red','Blue','White','Black']
},
{'questionText': 'What\'s your favourite Animal ?',
'answers': ['Dog','Rabbit','Tiger','Monkey']
},
{'questionText': 'What\'s your favourite Day ?',
'answers': ['Tuesday','Monday','Sunday','Friday','Wednesday','Saturday']
},
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(questions[_questionIndex]['questionText'] as String,
),
...(questions[_questionIndex]['answers'] as List).map((answer) {
return Answer(_answerQuestion(),answer);
}).toList()
],
)
),
);
}
}
question.dart
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questions;
Question(this.questions);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child:(
Text(
questions,
style: TextStyle(
fontSize: 25),
textAlign: TextAlign.center,)
),
);
}
}
answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function buttonHandler;
final String answer;
Answer(this.buttonHandler,this.answer);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answer),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
foregroundColor: MaterialStateProperty.all(Colors.white)
),
onPressed: () => buttonHandler,
),
);
}
}
when I run the application on my android in Android studio, I get this error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY╞═══════════════════════════════════════════
The following _TypeError was thrown building MyApp(dirty, state: _MyAppState#7f7de):
type 'Null' is not a subtype of type 'Function'
The relevant error-causing widget was:
MyApp file:///C:/src/first_app/lib/main.dart:7:10
This:
onPressed: () => buttonHandler,
needs to be either:
onPressed: buttonHandler,
or
onPressed: () => buttonHandler(),
depending on whether your handler matches the required signature exactly.
In addition, this:
return Answer(_answerQuestion(),answer);
needs to be
return Answer(_answerQuestion,answer);
Generally speaking, you have mixed up calling a method and passing a method as a parameter a few times, you may want to get more familiar with it.
First, you must pass a function structure instead returning value from the function by calling it.
You declared this function below:
_answerQuestion(){
setState(() {
_questionIndex = _questionIndex + 1;
});
}
and passed the return value instead of function structure like below:
return Answer(_answerQuestion(),answer);
As you can see the return value of _answerQuestion() is Null.
Change your code like this.
return Answer(_answerQuestion,answer);
And you need to call the funcion in the Answer component.
onPressed: buttonHandler
or
onPressed: () => buttonHandler()
Your code is working fine try flutter clean
I have a Switch on a screen and I need it to use the value that is in a Provider. I've tried to infer this value using the provider's value, but the Switch is immobile, it doesn't change visually(but the value is changed in the DB), it only works as it should when I remove the provider's inferences.
My Provider: (It is being called when I start the application)
class DailyDatabase with ChangeNotifier {
bool notificationActive = false;
void loadDailyData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
notificationActive = prefs.getBool('notificationActive') ?? false;}
Variable:
#override
Widget build(BuildContext context) {
final provider = Provider.of<DailyDatabase>(context);
_notificationActive = provider.notificationActive;
Switch:
Switch(
value: _notificationActive,
onChanged: (value) {
_notificationActive = value;
provider.setNotification(value);
},
),
Stateful Version - Provider only
Here's a very basic example of Provider with a Switch and using StatefulWidget and its setState to refresh the widget (instead of using ChangeNotifierProvider and Consumer to "listen" and "localize" the widget rebuild to just the Switch and the Text label, which is perhaps a more typical use):
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class SwitchProviderPage extends StatefulWidget {
#override
_SwitchProviderPageState createState() => _SwitchProviderPageState();
}
class Database {
bool active = false;
void setActive(bool value) {
active = value;
}
}
class _SwitchProviderPageState extends State<SwitchProviderPage> {
#override
Widget build(BuildContext context) {
return Provider(
create: (context) => Database(),
child: Builder(
builder: (context) {
Database db = Provider.of<Database>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: Text('Switch Field'),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Active? ${db.active}'),
Switch(
onChanged: (val) { // ← remember to use val (bool)
print('Switch value: $val');
setState(() {
db.setActive(val);
// this sets the Switch setting on/off
});
},
value: db.active,
)
],
),
),
),
);
},
),
);
}
}
Note:
The use of Builder in above is only to make Scaffold be a child of Provider.
Otherwise, Scaffold would be a sibling, not a child, and Provider will not work. Since you wrap your entire app in your ChangeNotifierProvider, you don't need to do this. I needed to do this to get a self-contained example.
Stateless Version - ChangeNotifierProvider + Consumer
Here's a complete app example (copy paste into main.dart, replacing everything on page) using a StatelessWidget and the typical/common ChangeNotifierProvider & Consumer.
This version uses a mocked long duration async call when flipping Switch.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(ChangeNotifierProvider<DatabaseListenable>(
create: (context) => DatabaseListenable(),
child: MyApp())
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Provider Demo App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: StatelessSwitchProviderPage(),
);
}
}
class DatabaseListenable with ChangeNotifier {
bool active = false;
Future<void> setActive(bool value) async {
// Mock slow database call ↓
await Future.delayed(Duration(milliseconds: 500), () {
active = value;
print('Async DB call DONE.');
});
notifyListeners(); // ← causes Consumer to rebuild
}
}
class StatelessSwitchProviderPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch Provider Stateless'),
),
body: SafeArea(
child: Center(
child: Consumer<DatabaseListenable>(
builder: (context, db, child) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Active? ${db.active}'),
Switch(
onChanged: (val) {
print('Switch value: $val');
db.setActive(val);
},
value: db.active,
)
],
),
),
),
),
);
}
}
You have to add setState((){}); which rebuild the screen and display changes on your screen
hope you doin' well
I'm a newbie to flutter and I'm working on a basic weather app as a starter. now, somehow everything is okay, except the city name. I don't know how to implement city search feature and get data from api based on the location. In my code, I defined city name manually.
here is my code:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:hava_chitor/Carousel.dart';
import 'package:hava_chitor/UnderCarousel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var temp;
var name;
var humidity;
var description;
var city = 'London';
CarouselController buttonCarouselController = CarouselController();
Future getWeather() async {
http.Response response = await http.get(
"http://api.openweathermap.org/data/2.5/weather?q=$city&units=metric&appid=apikey");
var results = jsonDecode(response.body);
setState(() {
this.temp = results['main']['temp'];
this.name = results['name'];
this.humidity = results['main']['humidity'];
this.description = results['weather'][0]['main'];
});
}
#override
void initState() {
super.initState();
this.getWeather();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hava Chitor?',
theme: ThemeData(
primaryColor: Color(0xff424242),
),
home: Scaffold(
drawer: Drawer(),
appBar: AppBar(
actions: [
Padding(
padding: const EdgeInsets.all(15),
child: GestureDetector(
onTap: () {
print('kir');
},
child: Icon(
Icons.add_circle_outline,
color: Color(0xff5d5f64),
),
),
)
],
backgroundColor: Colors.transparent,
elevation: 0,
iconTheme: IconThemeData(color: Color(0xff5d5f64)),
title: Text(
'Hava Chitor?',
style: TextStyle(
color: Color(0xff5d5f64),
fontFamily: 'Sans',
fontWeight: FontWeight.w700),
),
centerTitle: true,
),
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0),
child: Column(
children: [
Carousel(name),
UnderCarousel(temp, description, humidity),
],
),
),
),
);
}
}
you need to add a TextField and a TextFieldController and call the function getWeather when the user finish writing the city name, something like this
String city;
TextEditingController textEditingController = TextEditingController();
TextField(
controller: textEditingController,
onSubmitted: (value){
city = textEditingController.text;
getWeather();
},
),
what you need to do is add TextField for the user to input the city name.
the way you can do that is shown before. The next thing you have to do is write a function to fetch weather data with city name.
var url =
'http://api.openweathermap.org/data/2.5/weather?q=\$city&units=metric&appid=apikey';
class CityWeatherData {
final String city, temprateure, humidity; //...
CityWeatherData({
this.city,
this.temprateure,
this.humidity,
// ...
});
factory CityWeatherData.fromJson(Map<String, dynamic> json) {
return CityWeatherData(
city: json['city'],
humidity: json['city']['humidity'],
temprateure: json['city']['temp'],
// ...
);
}
}
Future<CityWeatherData> fetchWeatherDataBycity() async {
final response = await http.get(url);
if (response.statusCode == 200) {
return CityWeatherData.fromJson(jsonDecode(response.body));
} else {
throw Exception('failed to fetch data.');
}
}
I depending on the JSON data you get you have to edit the fromjson method.
I hope this was helpful!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm building a flutter application, and am having some trouble actually opening the app using the firebase_dynamic_links package. I basically took the example code found at https://pub.dev/packages/firebase_dynamic_links#-example-tab- in order to get started, but changed the information in their example to match my own firebase project (which has been setup in both android and iOS, but this testing has all been done with iOS).
I will include code and more useful information below, but I was really just hoping to get a simplified example of how this process should work. I have searched online quite a bit, following different tutorials, but none of them have done the trick for me. It could just be that I'm quite new to flutter, and am missing basic things. In my final application, I will be using dynamic links to allow users to invite other users to join the app (as well as groups within the app) via text, just to give context as to why it is needed.
Here is the code for what I have so far, but as I mentioned it is largely based off of the example from the link above.
main.dart
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:shopsync/helloworld.dart';
void main() async {
//Setup firebase connection
WidgetsFlutterBinding.ensureInitialized();
final FirebaseApp app = await FirebaseApp.configure(
name: 'shop-sync-d97d8',
options: Platform.isIOS
? const FirebaseOptions(
googleAppID: 'my_googleAppID',
gcmSenderID: 'my_senderID',
databaseURL: 'https://shop-sync-d97d8.firebaseio.com',
apiKey: 'AIzaSyC1TdwTs_KRXMGG2oIAGMX8v48HWqS62dc',
)
: const FirebaseOptions(
googleAppID: 'my_googleAppID',
apiKey: 'myApiKey',
databaseURL: 'my_url',
),
);
runApp(MaterialApp(
title: 'Dynamic Links Example',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _MainScreen(),
'/helloworld': (BuildContext context) => HelloWorldScreen(),
},
));
}
class _MainScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MainScreenState();
}
class _MainScreenState extends State<_MainScreen> {
String _linkMessage;
bool _isCreatingLink = false;
String _testString =
"To test: long press link and then copy and click from a non-browser "
"app. Make sure this isn't being tested on iOS simulator and iOS xcode "
"is properly setup. Look at firebase_dynamic_links/README.md for more "
"details.";
#override
void initState() {
super.initState();
initDynamicLinks();
}
void initDynamicLinks() async {
final PendingDynamicLinkData data =
await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
if (deepLink != null) {
Navigator.pushNamed(context, deepLink.path);
}
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null) {
Navigator.pushNamed(context, deepLink.path);
}
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
});
}
Future<void> _createDynamicLink(bool short) async {
setState(() {
_isCreatingLink = true;
});
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: "https://shopsync.page.link",
link: Uri.parse("https://shopsync.page.link/helloworld"),
androidParameters: AndroidParameters(
packageName: 'com.chrismcdonnell.shopsync',
minimumVersion: 0,
),
dynamicLinkParametersOptions: DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.short,
),
iosParameters: IosParameters(
bundleId: 'com.chrismcdonnell.shopsync',
minimumVersion: '0',
),
);
Uri url;
if (short) {
final ShortDynamicLink shortLink = await parameters.buildShortLink();
url = shortLink.shortUrl;
} else {
url = await parameters.buildUrl();
}
setState(() {
_linkMessage = url.toString();
_isCreatingLink = false;
});
}
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: const Text('Dynamic Links Example'),
),
body: Builder(builder: (BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: !_isCreatingLink
? () => _createDynamicLink(false)
: null,
child: const Text('Get Long Link'),
),
RaisedButton(
onPressed: !_isCreatingLink
? () => _createDynamicLink(true)
: null,
child: const Text('Get Short Link'),
),
],
),
InkWell(
child: Text(
_linkMessage ?? '',
style: const TextStyle(color: Colors.blue),
),
onTap: () async {
if (_linkMessage != null) {
await launch(_linkMessage);
}
},
onLongPress: () {
Clipboard.setData(ClipboardData(text: _linkMessage));
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('Copied Link!')),
);
},
),
Text(_linkMessage == null ? '' : _testString)
],
),
);
}),
),
);
}
}
class _DynamicLinkScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: const Text('Hello World DeepLink'),
),
body: const Center(
child: Text('Hello, World!'),
),
),
);
}
}
helloworld.dart
//IMPORT NEEDED PACKAGES
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
//CREATE STATEFUL WIDGET
class HelloWorldScreen extends StatefulWidget {
#override
_HelloWorldScreen createState() => _HelloWorldScreen();
}
//CREATE STATE WIDGET
class _HelloWorldScreen extends State<HelloWorldScreen> {
#override
Widget build(BuildContext context) {
//Since this class represents an entire screen, return a scaffold with elements inside it
return Scaffold(
backgroundColor: Colors.white,
//Create AppBar w/ title "My Account"
appBar: AppBar(
title: Text('Hello World'),
automaticallyImplyLeading: false,
),
//Most of the content of the screen will go here
body: SafeArea(
child: Text('Testing'),
),
);
}
}
And lastly, here is the dynamic link I created within the console for testing. Although the final version of the application will create them programatically.
If anything else is needed please let me know. Any help would be greatly appreciated.