Showing Snackbar using GetX Library - flutter

import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main(List args) {
runApp(GetMaterialApp(
title: 'My App',
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Get.snackbar(
'Hello',
'Hello World!',
snackPosition: SnackPosition.TOP,
);
},
child: Text('GetX Buttom')),
],
),
),
);
}
}

have you imported the get package? if not, you can add it in pubspec.yaml file, inside dev_dependencies.
example:
dev_dependencies:
flutter_test:
sdk: flutter
get: ^4.6.1
then save your pubspec.yaml file and type flutter pub get in your terminal
the result will be like this:
you can read more about getX in this documentation

Related

Flutter screen flickers with flutter 3.3.2

Even with a simple app, when I switch from one page to another, the screen flickers. Initially, I was testing this on flutter 3.0.2 and then moved to 3.3.2. On both versions I observe the flickering. Searching on google I see that others have observed this with ad_mob, but in my case I don't have ad_mob.
Here is main.dart
import 'package:flutter/material.dart';
import 'package:navigate3/page_1.dart';
import 'package:navigate3/page_2.dart';
import 'package:navigate3/page_3.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Main app',
initialRoute: '/Page1',
routes: {
'/Page1': (context) => Page_1(),
'/Page2': (context) => Page_2(),
'/Page3': (context) => Page_3(),
},
);
}
}
And here is page_1.dart. page_2.dart and page_3.dart are similar to page_1.dart
import 'package:flutter/material.dart';
class Page_1 extends StatelessWidget {
const Page_1({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Page 1'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/Page2');
},
child: const Text("Goto page 2"))
],
),
),
));
}
}

how to tweak the position of ListTile checkbox and title in flutter

I am write a simple GTD app using flutter(v3.0.4), now I facing a problem is that I did not know how to tweak the position of ListTile checkbox and title, this is the minimal reproduce example code of main.dart:
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'main_controller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
Map<int, String> getCategories() {
Map<int, String> categories = HashMap<int, String>();
categories.putIfAbsent(1, () => "已过期");
return categories;
}
#override
Widget build(BuildContext context) {
return GetBuilder<MainController>(
init: MainController(),
builder: (controller) {
return Scaffold(
//appBar: AppBar(title: Text("title")),
body: SingleChildScrollView(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: Card(
child: ExpansionTile(
title: Text(getCategories()[index + 1]!),
children: [
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
actions: <Widget>[
IconSlideAction(
caption: '删除',
color: Colors.blue,
icon: Icons.archive,
onTap: () async => {},
),
],
child: ListTile(
trailing: Text(
"scheduleTime",
style: new TextStyle(color: Colors.blue),
),
leading: Theme(
data: ThemeData(
primarySwatch: Colors.blue,
),
child: Checkbox(
value: false,
onChanged: (bool? value) {},
)),
title: Text("element.name", overflow: TextOverflow.ellipsis),
selected: false,
onTap: () {},
),
)
],
),
),
),
itemCount: getCategories().length),
),
);
});
}
}
this is the main_controller.dart:
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
class MainController extends GetxController {}
this is the dependencies:
name: untitled
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.16.1 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get: ^4.3.8
flutter_slidable: 0.6.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^1.0.0
flutter:
uses-material-design: true
what should I do to make the checkbox and title more closer? move the checkbox to left a littile. This is the result looks like right now:
the checkbox and title should be more closer.
ListTile has a property named horizontalTitleGap which can control the spacing.

Stack widget and Bloc Builder

I know Stack Widgets render their children from the ground up, however, I couldn't explain to myself why a BlocBuilder cannot efficiently rebuild them.
Here is an example:
#override
Widget build(BuildContext context) {
return Container(
child: BlocBuilder<TestCubit, int>(
builder: (context, state) {
return GestureDetector(
onTapDown: (tapDetails) {
context.read<TestCubit>().incrementCubit();
},
child: Stack(children: [Text('Counter: $state')]),
);
},
)
);
}
When TestCubit has its incrementCubit method called, the state changes - I tested it with a simple Container based UI, but once we are dealing with a Stack, nothing happens on the screen. Any ideas?
Thanks in advance!
I tested your code and it works with both Stack as well as Container. Please see my code below :
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(
const CounterApp(),
);
}
class CounterApp extends MaterialApp {
const CounterApp({Key key}) : super(key: key, home: const CounterPage());
}
class CounterPage extends StatelessWidget {
const CounterPage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => TestCubit(),
child: CounterView(),
);
}
}
class CounterView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(child: BlocBuilder<TestCubit, int>(
builder: (context, state) {
return GestureDetector(
onTapDown: (tapDetails) {
context.read<TestCubit>().incrementCubit();
},
child: Stack(children: [Text('Counter: $state')]),
//child: Text('Counter: $state'),
//child: Scaffold(
// appBar: AppBar(title: const Text("Cubit Demo")),
// body: Center(
// child: Stack(
// children: [
// Text('Counter: $state'),
// ],
// )),
//),
);
},
));
}
}
class TestCubit extends Cubit<int> {
TestCubit() : super(0);
void incrementCubit() => emit(state + 1);
void decrementCubit() => emit(state - 1);
}
pubspec.yaml
name: test_http
description: A new Flutter application.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_bloc:
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true

Leading on AppBar Incorrectly Persisting on Different Pages

I am working on a project in Flutter. The issue is that when I navigate to a different page, and then go back, there is an icon that I used a while ago while testing that appears on the home page's appbar. I went back into the code, and there wasn't leading within that page's appbar.
Here is a screenshot after a complete rebuild of the app.
After navigating to another page using Navigator.of(context).pushNamed('/streaks/edit/'):
And finally, navigating back to the home page using Navigator.of(context).pushNamed('/streaks/all/'):
main.dart code:
import 'package:flutter/material.dart';
import 'package:streaks/pages/all_streaks/all_streaks.dart';
import 'package:streaks/pages/edit_streak/edit_streak.dart';
void main() => runApp(StreaksApp());
class StreaksApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'streaks',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
initialRoute: '/streaks/all/',
routes: <String, WidgetBuilder>{
'/streaks/all/': (context) => AllStreaksPage(),
'/streaks/edit/': (context) => EditStreakPage(),
},
);
}
}
home page code (/streaks/all/):
import 'package:flutter/material.dart';
import 'streak_list.dart';
class AllStreaksPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('All Streaks'),
),
body: StreakList(),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed('/streaks/edit/');
},
child: Icon(Icons.add, size: 40),
),
);
}
}
and the Edit Streak page (/streaks/edit/):
import 'package:flutter/material.dart';
import 'package:streaks/pages/edit_streak/streak_form.dart';
class EditStreakPage extends StatefulWidget {
#override
_EditStreakPageState createState() => _EditStreakPageState();
}
class _EditStreakPageState extends State<EditStreakPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.close, color: Theme.of(context).buttonColor),
onPressed: () {
Navigator.pushNamed(context, '/streaks/all/');
}),
title: Text('Edit Streak'),
),
body: StreakForm()
);
}
}
pubspec.yaml:
name: streaks
description: An app to boost your productivity with event organization.
publish_to: "none"
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
sqflite:
path:
flutter_iconpicker: ^2.1.5
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
Note: there aren't any errors logged into the debug console at any time.
Another Note: even after deleting the app and running again, there error persisted.
Please help. I was thinking it might be (a) a caching error or (b) there is a problem with stateless widgets as pages.
1st way:
In your EditStreakPage class, instead of using Navigator.pushNamed(context, '/streaks/all/'); use Navigator.pop(context)
Complete class code:
import 'package:flutter/material.dart';
import 'package:streaks/pages/edit_streak/streak_form.dart';
class EditStreakPage extends StatefulWidget {
#override
_EditStreakPageState createState() => _EditStreakPageState();
}
class _EditStreakPageState extends State<EditStreakPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.close, color: Theme.of(context).buttonColor),
onPressed: () {
Navigator.pop(context); // <-- use this intead
}),
title: Text('Edit Streak'),
),
body: StreakForm()
);
}
}
2nd way:
In your AllStreaksPage class, pass the property automaticallyImplyLeading: false to the AppBar()
Complete class code:
import 'package:flutter/material.dart';
import 'streak_list.dart';
class AllStreaksPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false; // <--- add this
title: Text('All Streaks'),
),
body: StreakList(),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed('/streaks/edit/');
},
child: Icon(Icons.add, size: 40),
),
);
}
}
From what i understand you are saying that actions is appering when you Open YOur App -> EDitStreak Page->press the close button on top in editStreak page ..
The key reason for this is that instead of going back you are actually going to that page by navigating to it . in which the back button would lead you back to edit Streaks page .
Instead of Navigating You Should use
Navigator.of(context).pop()
and that should solve your issue , let me know in comments , if it helps

Set the image for switch button in flutter

How do I set the image for a switch button in flutter using the activeThumbImage property? I am a little confused on how to set the ImageProvider value for this property? Is there any example that I could look at that implements the activeThumbImage property of the Switch widget?
You can use an AssetImage or NetworkImage to get an ImageProvider that is suitable for use as an activeThumbImage. Learn more about asset images in the Adding Assets and Images in Flutter tutorial.
Here is some example code that draws the above Switch:
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
MyHomePageState createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
bool _enabled;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Switch(
value: _enabled,
onChanged: (bool value) {
setState(() {
_enabled = value;
});
},
activeThumbImage: new NetworkImage('https://lists.gnu.org/archive/html/emacs-devel/2015-10/pngR9b4lzUy39.png'),
inactiveThumbImage: new NetworkImage('http://wolfrosch.com/_img/works/goodies/icon/vim#2x'),
),
)
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.deepPurple,
),
home: new MyHomePage(),
));
}
Here is my code.
class ToggleButtonScreen extends StatefulWidget {
#override
_ToggleButtonScreenState createState() => _ToggleButtonScreenState();
}
class _ToggleButtonScreenState extends State<ToggleButtonScreen> {
bool _value = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _value ? AssetImage("images/cnw.png") : AssetImage("images/cnw.png"),
fit: BoxFit.cover,
),
),
child: Padding(
padding: EdgeInsets.all(AppDimens.EDGE_REGULAR),
child: Column(
children: [
_normalToggleButton(),
],
),
),
),
),
),
);
}
Widget _normalToggleButton () {
return Container(
child: Transform.scale(
scale: 2.0,
child: Switch(
activeColor : Colors.greenAccent,
inactiveThumbColor: Colors.redAccent,
value: _value,
activeThumbImage: AssetImage("images/cnw.png"),
inactiveThumbImage : AssetImage("images/simple_interest.png"),
onChanged: (bool value){
setState(() {
_value = value;
});
},
),
),
);
}
}
pubspec.yaml
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_inappwebview: ^5.3.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_launcher_icons: "^0.8.0"
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
assets:
- assets/icon/google.png
main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class MyChromeSafariBrowser extends ChromeSafariBrowser {
#override
void onOpened() {
print("ChromeSafari browser opened");
}
#override
void onCompletedInitialLoad() {
print("ChromeSafari browser initial load completed");
}
#override
void onClosed() {
print("ChromeSafari browser closed");
}
}
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
runApp(MaterialApp(home: MyApp(), theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFA7A5A5)),
debugShowCheckedModeBanner: false));
}
class MyApp extends StatefulWidget {
final ChromeSafariBrowser browser = new MyChromeSafariBrowser();
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Image Button"),
),
body:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child:
Column(children: <Widget>[
Container(
// padding: EdgeInsets.all(50),
alignment: Alignment.center,
child: IconButton(
icon: Image.asset('assets/icon/Amazon_icon.png'),
iconSize: 50,
color: Colors.green,
splashColor: Colors.purple,
onPressed: () async {
await widget.browser.open(
url: Uri.parse("https://www.amazon.in/?&_encoding=UTF8&tag=bappasaikh-21&linkCode=ur2&linkId=e3b009b026920c3cfdd6185fadfb7e67&camp=3638&creative=24630"),
options: ChromeSafariBrowserClassOptions(
android: AndroidChromeCustomTabsOptions(
addDefaultShareMenuItem: false,),
ios: IOSSafariOptions(barCollapsingEnabled: true)));
},
),
),
]),
),
);
}
}