├── Animations.dart ├── AudioPlayer.dart ├── CardStyle.dart ├── CircleAvatar.dart ├── ClipRect.dart ├── CutoutEffect.md ├── DateTime.dart ├── Elevated-button.dart ├── GridView.dart ├── Multiple-color-theme-app.dart ├── Quick accetions in flutter.md ├── RegEx to extract URLs from a String.dart ├── Stacked Images.dart ├── Survey.dart ├── TableInDart.dart ├── adding-svg-icons.dart ├── apiCalls.dart ├── apiCallswithMultipartRequest.dart ├── appbar-tricks.dart ├── bottom-nav-bar.dart ├── caraousel.dart ├── dark-mode.dart ├── datepicker.dart ├── divider.dart ├── draggableScrollableSheet.dart ├── drawer.dart ├── dropdown.dart ├── fb-google-social-login.dart ├── find # tag in a string.dart ├── firebaseAuth.dart ├── flex.dart ├── gesturedetector.dart ├── license ├── listTile.dart ├── listview.dart ├── multiple_floating_action_button.dart ├── neumorphism.dart ├── onGeneratedRoute.dart ├── paginatedDataTable.dart ├── password-toggle.dart ├── random-color-generator.dart ├── raw-material-button.dart ├── readMe.md ├── refresh_indicator.dart ├── responsive.dart ├── responsivenessCheck.dart ├── returnDataFromAScreen.dart ├── richText.dart ├── search-delegate.dart ├── search_bar_3d.dart ├── slider.dart ├── stepper.dart ├── tabbar.dart ├── test.dart ├── text-field.dart ├── textstyles.dart ├── themes.dart ├── timepicker.dart └── workManager.dart /Animations.dart: -------------------------------------------------------------------------------- 1 | animate_icons: ^2.0.0 2 | 3 | animations: ^2.0.0 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:flutter/scheduler.dart'; 7 | 8 | import 'container_transition.dart'; 9 | import 'fade_scale_transition.dart'; 10 | import 'fade_through_transition.dart'; 11 | import 'shared_axis_transition.dart'; 12 | 13 | 14 | void main() { 15 | runApp( 16 | MaterialApp( 17 | theme: ThemeData.from( 18 | colorScheme: const ColorScheme.light(), 19 | ).copyWith( 20 | pageTransitionsTheme: const PageTransitionsTheme( 21 | builders: { 22 | TargetPlatform.android: ZoomPageTransitionsBuilder(), 23 | }, 24 | ), 25 | ), 26 | home: _TransitionsHomePage(), 27 | ), 28 | ); 29 | } 30 | 31 | class _TransitionsHomePage extends StatefulWidget { 32 | @override 33 | _TransitionsHomePageState createState() => _TransitionsHomePageState(); 34 | } 35 | 36 | class _TransitionsHomePageState extends State<_TransitionsHomePage> { 37 | bool _slowAnimations = false; 38 | 39 | @override 40 | Widget build(BuildContext context) { 41 | return Scaffold( 42 | appBar: AppBar(title: const Text('Material Transitions')), 43 | body: Column( 44 | children: [ 45 | Expanded( 46 | child: ListView( 47 | children: [ 48 | _TransitionListTile( 49 | title: 'Container transform', 50 | subtitle: 'OpenContainer', 51 | onTap: () { 52 | Navigator.of(context).push( 53 | MaterialPageRoute( 54 | builder: (BuildContext context) { 55 | return OpenContainerTransformDemo(); 56 | }, 57 | ), 58 | ); 59 | }, 60 | ), 61 | _TransitionListTile( 62 | title: 'Shared axis', 63 | subtitle: 'SharedAxisTransition', 64 | onTap: () { 65 | Navigator.of(context).push( 66 | MaterialPageRoute( 67 | builder: (BuildContext context) { 68 | return SharedAxisTransitionDemo(); 69 | }, 70 | ), 71 | ); 72 | }, 73 | ), 74 | _TransitionListTile( 75 | title: 'Fade through', 76 | subtitle: 'FadeThroughTransition', 77 | onTap: () { 78 | Navigator.of(context).push( 79 | MaterialPageRoute( 80 | builder: (BuildContext context) { 81 | return FadeThroughTransitionDemo(); 82 | }, 83 | ), 84 | ); 85 | }, 86 | ), 87 | _TransitionListTile( 88 | title: 'Fade', 89 | subtitle: 'FadeScaleTransition', 90 | onTap: () { 91 | Navigator.of(context).push( 92 | MaterialPageRoute( 93 | builder: (BuildContext context) { 94 | return FadeScaleTransitionDemo(); 95 | }, 96 | ), 97 | ); 98 | }, 99 | ), 100 | ], 101 | ), 102 | ), 103 | const Divider(height: 0.0), 104 | SafeArea( 105 | child: SwitchListTile( 106 | value: _slowAnimations, 107 | onChanged: (bool value) async { 108 | setState(() { 109 | _slowAnimations = value; 110 | }); 111 | // Wait until the Switch is done animating before actually slowing 112 | // down time. 113 | if (_slowAnimations) { 114 | await Future.delayed(const Duration(milliseconds: 300)); 115 | } 116 | timeDilation = _slowAnimations ? 20.0 : 1.0; 117 | }, 118 | title: const Text('Slow animations'), 119 | ), 120 | ), 121 | ], 122 | ), 123 | ); 124 | } 125 | } 126 | 127 | class _TransitionListTile extends StatelessWidget { 128 | const _TransitionListTile({ 129 | this.onTap, 130 | required this.title, 131 | required this.subtitle, 132 | }); 133 | 134 | final GestureTapCallback? onTap; 135 | final String title; 136 | final String subtitle; 137 | 138 | @override 139 | Widget build(BuildContext context) { 140 | return ListTile( 141 | contentPadding: const EdgeInsets.symmetric( 142 | horizontal: 15.0, 143 | ), 144 | leading: Container( 145 | width: 40.0, 146 | height: 40.0, 147 | decoration: BoxDecoration( 148 | borderRadius: BorderRadius.circular(20.0), 149 | border: Border.all( 150 | color: Colors.black54, 151 | ), 152 | ), 153 | child: const Icon( 154 | Icons.play_arrow, 155 | size: 35, 156 | ), 157 | ), 158 | onTap: onTap, 159 | title: Text(title), 160 | subtitle: Text(subtitle), 161 | ); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /AudioPlayer.dart: -------------------------------------------------------------------------------- 1 | // Import the latest package of flutter audio player 2 | //audioplayers: ^0.19.1 (latest as of now) 3 | 4 | 5 | import 'dart:async'; 6 | import 'dart:io'; 7 | 8 | import 'package:audioplayers/audioplayers.dart'; 9 | import 'package:flutter/foundation.dart'; 10 | import 'package:flutter/material.dart'; 11 | import 'package:http/http.dart'; 12 | import 'package:path_provider/path_provider.dart'; 13 | import 'package:provider/provider.dart'; 14 | 15 | import 'player_widget.dart'; 16 | 17 | typedef OnError = void Function(Exception exception); 18 | 19 | const kUrl1 = 'https://luan.xyz/files/audio/ambient_c_motion.mp3'; 20 | const kUrl2 = 'https://luan.xyz/files/audio/nasa_on_a_mission.mp3'; 21 | const kUrl3 = 'http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio1xtra_mf_p'; 22 | 23 | void main() { 24 | runApp(MaterialApp(home: ExampleApp())); 25 | } 26 | 27 | class ExampleApp extends StatefulWidget { 28 | @override 29 | _ExampleAppState createState() => _ExampleAppState(); 30 | } 31 | 32 | class _ExampleAppState extends State { 33 | AudioCache audioCache = AudioCache(); 34 | AudioPlayer advancedPlayer = AudioPlayer(); 35 | String? localFilePath; 36 | String? localAudioCacheURI; 37 | 38 | @override 39 | void initState() { 40 | super.initState(); 41 | 42 | if (kIsWeb) { 43 | // Calls to Platform.isIOS fails on web 44 | return; 45 | } 46 | if (Platform.isIOS) { 47 | audioCache.fixedPlayer?.notificationService.startHeadlessService(); 48 | advancedPlayer.notificationService.startHeadlessService(); 49 | } 50 | } 51 | 52 | Future _loadFile() async { 53 | final bytes = await readBytes(Uri.parse(kUrl1)); 54 | final dir = await getApplicationDocumentsDirectory(); 55 | final file = File('${dir.path}/audio.mp3'); 56 | 57 | await file.writeAsBytes(bytes); 58 | if (file.existsSync()) { 59 | setState(() => localFilePath = file.path); 60 | } 61 | } 62 | 63 | Widget remoteUrl() { 64 | return const SingleChildScrollView( 65 | child: _Tab( 66 | children: [ 67 | Text( 68 | 'Sample 1 ($kUrl1)', 69 | key: Key('url1'), 70 | style: TextStyle(fontWeight: FontWeight.bold), 71 | ), 72 | PlayerWidget(url: kUrl1), 73 | Text( 74 | 'Sample 2 ($kUrl2)', 75 | style: TextStyle(fontWeight: FontWeight.bold), 76 | ), 77 | PlayerWidget(url: kUrl2), 78 | Text( 79 | 'Sample 3 ($kUrl3)', 80 | style: TextStyle(fontWeight: FontWeight.bold), 81 | ), 82 | PlayerWidget(url: kUrl3), 83 | Text( 84 | 'Sample 4 (Low Latency mode) ($kUrl1)', 85 | style: TextStyle(fontWeight: FontWeight.bold), 86 | ), 87 | PlayerWidget(url: kUrl1, mode: PlayerMode.LOW_LATENCY), 88 | ], 89 | ), 90 | ); 91 | } 92 | 93 | Widget localFile() { 94 | return _Tab(children: [ 95 | const Text(' -- manually load bytes (no web!) --'), 96 | const Text('File: $kUrl1'), 97 | _Btn(txt: 'Download File to your Device', onPressed: _loadFile), 98 | Text('Current local file path: $localFilePath'), 99 | if (localFilePath != null) PlayerWidget(url: localFilePath!), 100 | Container( 101 | constraints: const BoxConstraints.expand(width: 1.0, height: 20.0), 102 | ), 103 | const Text(' -- via AudioCache --'), 104 | const Text('File: $kUrl2'), 105 | _Btn(txt: 'Download File to your Device', onPressed: _loadFileAC), 106 | Text('Current AC loaded: $localAudioCacheURI'), 107 | if (localAudioCacheURI != null) PlayerWidget(url: localAudioCacheURI!), 108 | ]); 109 | } 110 | 111 | void _loadFileAC() async { 112 | final uri = await audioCache.load(kUrl2); 113 | setState(() => localAudioCacheURI = uri.toString()); 114 | } 115 | 116 | Widget localAsset() { 117 | return SingleChildScrollView( 118 | child: _Tab( 119 | children: [ 120 | const Text("Play Local Asset 'audio.mp3':"), 121 | _Btn(txt: 'Play', onPressed: () => audioCache.play('audio.mp3')), 122 | const Text("Play Local Asset (via byte source) 'audio.mp3':"), 123 | _Btn( 124 | txt: 'Play', 125 | onPressed: () async { 126 | final bytes = await (await audioCache.loadAsFile('audio.mp3')) 127 | .readAsBytes(); 128 | audioCache.playBytes(bytes); 129 | }, 130 | ), 131 | const Text("Loop Local Asset 'audio.mp3':"), 132 | _Btn(txt: 'Loop', onPressed: () => audioCache.loop('audio.mp3')), 133 | const Text("Loop Local Asset (via byte source) 'audio.mp3':"), 134 | _Btn( 135 | txt: 'Loop', 136 | onPressed: () async { 137 | final bytes = await (await audioCache.loadAsFile('audio.mp3')) 138 | .readAsBytes(); 139 | audioCache.playBytes(bytes, loop: true); 140 | }, 141 | ), 142 | const Text("Play Local Asset 'audio2.mp3':"), 143 | _Btn(txt: 'Play', onPressed: () => audioCache.play('audio2.mp3')), 144 | const Text("Play Local Asset In Low Latency 'audio.mp3':"), 145 | _Btn( 146 | txt: 'Play', 147 | onPressed: () { 148 | audioCache.play('audio.mp3', mode: PlayerMode.LOW_LATENCY); 149 | }, 150 | ), 151 | const Text( 152 | "Play Local Asset Concurrently In Low Latency 'audio.mp3':", 153 | ), 154 | _Btn( 155 | txt: 'Play', 156 | onPressed: () async { 157 | await audioCache.play( 158 | 'audio.mp3', 159 | mode: PlayerMode.LOW_LATENCY, 160 | ); 161 | await audioCache.play( 162 | 'audio2.mp3', 163 | mode: PlayerMode.LOW_LATENCY, 164 | ); 165 | }, 166 | ), 167 | const Text("Play Local Asset In Low Latency 'audio2.mp3':"), 168 | _Btn( 169 | txt: 'Play', 170 | onPressed: () { 171 | audioCache.play('audio2.mp3', mode: PlayerMode.LOW_LATENCY); 172 | }, 173 | ), 174 | getLocalFileDuration(), 175 | ], 176 | ), 177 | ); 178 | } 179 | 180 | Future _getDuration() async { 181 | final uri = await audioCache.load('audio2.mp3'); 182 | await advancedPlayer.setUrl(uri.toString()); 183 | return Future.delayed( 184 | const Duration(seconds: 2), 185 | () => advancedPlayer.getDuration(), 186 | ); 187 | } 188 | 189 | FutureBuilder getLocalFileDuration() { 190 | return FutureBuilder( 191 | future: _getDuration(), 192 | builder: (BuildContext context, AsyncSnapshot snapshot) { 193 | switch (snapshot.connectionState) { 194 | case ConnectionState.none: 195 | return const Text('No Connection...'); 196 | case ConnectionState.active: 197 | case ConnectionState.waiting: 198 | return const Text('Awaiting result...'); 199 | case ConnectionState.done: 200 | if (snapshot.hasError) { 201 | return Text('Error: ${snapshot.error}'); 202 | } 203 | return Text( 204 | 'audio2.mp3 duration is: ${Duration(milliseconds: snapshot.data!)}', 205 | ); 206 | default: 207 | return Container(); 208 | } 209 | }, 210 | ); 211 | } 212 | 213 | Widget notification() { 214 | return _Tab( 215 | children: [ 216 | const Text("Play notification sound: 'messenger.mp3':"), 217 | _Btn( 218 | txt: 'Play', 219 | onPressed: () => 220 | audioCache.play('messenger.mp3', isNotification: true), 221 | ), 222 | ], 223 | ); 224 | } 225 | 226 | @override 227 | Widget build(BuildContext context) { 228 | return MultiProvider( 229 | providers: [ 230 | StreamProvider.value( 231 | initialData: const Duration(), 232 | value: advancedPlayer.onAudioPositionChanged, 233 | ), 234 | ], 235 | child: DefaultTabController( 236 | length: 5, 237 | child: Scaffold( 238 | appBar: AppBar( 239 | bottom: const TabBar( 240 | tabs: [ 241 | Tab(text: 'Remote Url'), 242 | Tab(text: 'Local File'), 243 | Tab(text: 'Local Asset'), 244 | Tab(text: 'Notification'), 245 | Tab(text: 'Advanced'), 246 | ], 247 | ), 248 | title: const Text('audioplayers Example'), 249 | ), 250 | body: TabBarView( 251 | children: [ 252 | remoteUrl(), 253 | localFile(), 254 | localAsset(), 255 | notification(), 256 | Advanced(advancedPlayer: advancedPlayer), 257 | ], 258 | ), 259 | ), 260 | ), 261 | ); 262 | } 263 | } 264 | 265 | class Advanced extends StatefulWidget { 266 | final AudioPlayer advancedPlayer; 267 | 268 | const Advanced({Key? key, required this.advancedPlayer}) : super(key: key); 269 | 270 | @override 271 | _AdvancedState createState() => _AdvancedState(); 272 | } 273 | 274 | class _AdvancedState extends State { 275 | bool? seekDone; 276 | 277 | @override 278 | void initState() { 279 | widget.advancedPlayer.onSeekComplete 280 | .listen((event) => setState(() => seekDone = true)); 281 | super.initState(); 282 | } 283 | 284 | @override 285 | Widget build(BuildContext context) { 286 | final audioPosition = Provider.of(context); 287 | return SingleChildScrollView( 288 | child: _Tab( 289 | children: [ 290 | Column( 291 | children: [ 292 | const Text('Source Url'), 293 | Row( 294 | children: [ 295 | _Btn( 296 | txt: 'Audio 1', 297 | onPressed: () => widget.advancedPlayer.setUrl(kUrl1), 298 | ), 299 | _Btn( 300 | txt: 'Audio 2', 301 | onPressed: () => widget.advancedPlayer.setUrl(kUrl2), 302 | ), 303 | _Btn( 304 | txt: 'Stream', 305 | onPressed: () => widget.advancedPlayer.setUrl(kUrl3), 306 | ), 307 | ], 308 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 309 | ), 310 | ], 311 | ), 312 | Column( 313 | children: [ 314 | const Text('Release Mode'), 315 | Row( 316 | children: [ 317 | _Btn( 318 | txt: 'STOP', 319 | onPressed: () => 320 | widget.advancedPlayer.setReleaseMode(ReleaseMode.STOP), 321 | ), 322 | _Btn( 323 | txt: 'LOOP', 324 | onPressed: () => 325 | widget.advancedPlayer.setReleaseMode(ReleaseMode.LOOP), 326 | ), 327 | _Btn( 328 | txt: 'RELEASE', 329 | onPressed: () => widget.advancedPlayer 330 | .setReleaseMode(ReleaseMode.RELEASE), 331 | ), 332 | ], 333 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 334 | ), 335 | ], 336 | ), 337 | Column( 338 | children: [ 339 | const Text('Volume'), 340 | Row( 341 | children: [0.0, 0.3, 0.5, 1.0, 1.1, 2.0].map((e) { 342 | return _Btn( 343 | txt: e.toString(), 344 | onPressed: () => widget.advancedPlayer.setVolume(e), 345 | ); 346 | }).toList(), 347 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 348 | ), 349 | ], 350 | ), 351 | Column( 352 | children: [ 353 | const Text('Control'), 354 | Row( 355 | children: [ 356 | _Btn( 357 | txt: 'resume', 358 | onPressed: () => widget.advancedPlayer.resume(), 359 | ), 360 | _Btn( 361 | txt: 'pause', 362 | onPressed: () => widget.advancedPlayer.pause(), 363 | ), 364 | _Btn( 365 | txt: 'stop', 366 | onPressed: () => widget.advancedPlayer.stop(), 367 | ), 368 | _Btn( 369 | txt: 'release', 370 | onPressed: () => widget.advancedPlayer.release(), 371 | ), 372 | ], 373 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 374 | ), 375 | ], 376 | ), 377 | Column( 378 | children: [ 379 | const Text('Seek in milliseconds'), 380 | Row( 381 | children: [ 382 | _Btn( 383 | txt: '100ms', 384 | onPressed: () { 385 | widget.advancedPlayer.seek( 386 | Duration( 387 | milliseconds: audioPosition.inMilliseconds + 100, 388 | ), 389 | ); 390 | setState(() => seekDone = false); 391 | }, 392 | ), 393 | _Btn( 394 | txt: '500ms', 395 | onPressed: () { 396 | widget.advancedPlayer.seek( 397 | Duration( 398 | milliseconds: audioPosition.inMilliseconds + 500, 399 | ), 400 | ); 401 | setState(() => seekDone = false); 402 | }, 403 | ), 404 | _Btn( 405 | txt: '1s', 406 | onPressed: () { 407 | widget.advancedPlayer.seek( 408 | Duration(seconds: audioPosition.inSeconds + 1), 409 | ); 410 | setState(() => seekDone = false); 411 | }, 412 | ), 413 | _Btn( 414 | txt: '1.5s', 415 | onPressed: () { 416 | widget.advancedPlayer.seek( 417 | Duration( 418 | milliseconds: audioPosition.inMilliseconds + 1500, 419 | ), 420 | ); 421 | setState(() => seekDone = false); 422 | }, 423 | ), 424 | ], 425 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 426 | ), 427 | ], 428 | ), 429 | Column( 430 | children: [ 431 | const Text('Rate'), 432 | Row( 433 | children: [0.5, 1.0, 1.5, 2.0, 5.0].map((e) { 434 | return _Btn( 435 | txt: e.toString(), 436 | onPressed: () { 437 | widget.advancedPlayer.setPlaybackRate(playbackRate: e); 438 | }, 439 | ); 440 | }).toList(), 441 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 442 | ), 443 | ], 444 | ), 445 | Text('Audio Position: $audioPosition'), 446 | if (seekDone != null) Text(seekDone! ? 'Seek Done' : 'Seeking...'), 447 | ], 448 | ), 449 | ); 450 | } 451 | } 452 | 453 | class _Tab extends StatelessWidget { 454 | final List children; 455 | 456 | const _Tab({Key? key, required this.children}) : super(key: key); 457 | 458 | @override 459 | Widget build(BuildContext context) { 460 | return Center( 461 | child: Container( 462 | alignment: Alignment.topCenter, 463 | padding: const EdgeInsets.all(16.0), 464 | child: SingleChildScrollView( 465 | child: Column( 466 | children: children 467 | .map( 468 | (w) => Container( 469 | child: w, 470 | padding: const EdgeInsets.all(6.0), 471 | ), 472 | ) 473 | .toList(), 474 | ), 475 | ), 476 | ), 477 | ); 478 | } 479 | } 480 | 481 | class _Btn extends StatelessWidget { 482 | final String txt; 483 | final VoidCallback onPressed; 484 | 485 | const _Btn({Key? key, required this.txt, required this.onPressed}) 486 | : super(key: key); 487 | 488 | @override 489 | Widget build(BuildContext context) { 490 | return ButtonTheme( 491 | minWidth: 48.0, 492 | child: ElevatedButton(child: Text(txt), onPressed: onPressed), 493 | ); 494 | } 495 | } 496 | -------------------------------------------------------------------------------- /CardStyle.dart: -------------------------------------------------------------------------------- 1 | Card( 2 | color: Colors.grey[900], 3 | shape: RoundedRectangleBorder( 4 | side: BorderSide(color: Colors.white70, width: 1), 5 | borderRadius: BorderRadius.circular(10), 6 | ), 7 | margin: EdgeInsets.all(20.0), 8 | child: Container( 9 | child: Column( 10 | children: [ 11 | ListTile( 12 | title: Text( 13 | 'example', 14 | style: TextStyle(fontSize: 18, color: Colors.white), 15 | ), 16 | ), 17 | ], 18 | ), 19 | ), 20 | ), 21 | 22 | 23 | ////////////////More Card Shape////////////////// 24 | 25 | Card( 26 | shape: RoundedRectangleBorder( 27 | borderRadius: BorderRadius.circular(15.0), 28 | ), 29 | child: Text( 30 | 'Card with circular border', 31 | textScaleFactor: 1.2, 32 | ), 33 | ), 34 | Card( 35 | shape: BeveledRectangleBorder( 36 | borderRadius: BorderRadius.circular(10.0), 37 | ), 38 | child: Text( 39 | 'Card with Beveled border', 40 | textScaleFactor: 1.2, 41 | ), 42 | ), 43 | Card( 44 | shape: StadiumBorder( 45 | side: BorderSide( 46 | color: Colors.black, 47 | width: 2.0, 48 | ), 49 | ), 50 | child: Text( 51 | 'Card with Beveled border', 52 | textScaleFactor: 1.2, 53 | ), 54 | ), 55 | -------------------------------------------------------------------------------- /CircleAvatar.dart: -------------------------------------------------------------------------------- 1 | // Text Inside Circle Avatar ---- >>> 2 | body: Center( 3 | child: CircleAvatar( 4 | backgroundColor: Colors.pink[400], 5 | radius: 100, 6 | child: Text( 7 | 'Deepa Pandey', 8 | style: TextStyle(fontSize: 25, color: Colors.white), 9 | ), //Text 10 | ), //CirlceAvatar 11 | ), 12 | 13 | foregroundColor: Colors.white, // Or use foregroundColor for the default text color for text in the circle. 14 | 15 | 16 | ----------------------------------------------------------------------------------------------------------------------- 17 | 18 | // Code snippet for image inside the CircleAvatar 19 | ... 20 | body: Center( 21 | child: CircleAvatar( 22 | backgroundImage: NetworkImage( 23 | "https://abc.com//xyz.png"), 24 | radius: 100, 25 | ), //CircleAvatar 26 | ... 27 | 28 | 29 | ----------------------------------------------------------------------------------------------------------------------- 30 | // To add a colored border in the Circle Avatar : 31 | CircleAvatar( 32 | radius: 21, 33 | backgroundColor: Colors.pink, 34 | child: CircleAvatar( 35 | backgroundColor: Colors.amber, 36 | child: Text( 37 | active[index].name[0], // A model data 38 | style: TextStyle( 39 | fontSize: 16, 40 | fontWeight: FontWeight.bold, 41 | color: Colors.black), 42 | ), 43 | 44 | ----------------------------------------------------------------------------------------------------------------------- 45 | 46 | 47 | // To add a border and image/text with some space in between the circleAvatar -- 48 | 49 | Center( 50 | child: CircleAvatar( 51 | backgroundColor: Colors.pink, 52 | radius: 115, 53 | child: CircleAvatar( 54 | backgroundColor: Colors.grey[100], 55 | radius: 110, 56 | child: CircleAvatar( 57 | backgroundImage: NetworkImage( 58 | "https://xyz.jpg"), //NetworkImage 59 | radius: 100, 60 | ), //CircleAvatar 61 | ), //CircleAvatar 62 | ), //CircleAvatar 63 | ), 64 | -------------------------------------------------------------------------------- /ClipRect.dart: -------------------------------------------------------------------------------- 1 | 2 | import 'package:flutter/material.dart'; 3 | 4 | void main(){ 5 | runApp(MyApp()); 6 | } 7 | // App Widget:- 8 | class MyApp extends StatefulWidget { 9 | 10 | // Initialize app 11 | MyApp(); 12 | 13 | @override 14 | _MyAppState createState() => _MyAppState(); 15 | } 16 | 17 | class _MyAppState extends State { 18 | /// Widget 19 | @override 20 | Widget build(BuildContext context) { 21 | return MaterialApp( 22 | debugShowCheckedModeBanner: false, 23 | 24 | /// Home 25 | home: ClipperExamples(), 26 | ); 27 | } 28 | } 29 | 30 | class ClipperExamples extends StatefulWidget { 31 | @override 32 | _ClipperExamplesState createState() => _ClipperExamplesState(); 33 | } 34 | 35 | class _ClipperExamplesState extends State { 36 | @override 37 | Widget build(BuildContext context) { 38 | return Scaffold( 39 | appBar: AppBar( 40 | backgroundColor: Color(0XFF307777), 41 | title: Text("Clipper Example"), 42 | ), 43 | body: SingleChildScrollView( 44 | child: Container( 45 | width: double.infinity, 46 | margin: EdgeInsets.all(20.0), 47 | child: Column( 48 | crossAxisAlignment: CrossAxisAlignment.center, 49 | children: [ 50 | /// ClipRect 51 | Container( 52 | margin: EdgeInsets.only(top: 40.0,), 53 | child: Text( 54 | "ClipRect", 55 | style: Theme.of(context).textTheme.headline4, 56 | ), 57 | ), 58 | ClipRect( 59 | child: Container( 60 | child: Align( 61 | alignment: Alignment.center, 62 | widthFactor: 0.5, 63 | heightFactor: 0.8, 64 | child: Image.network( 65 | 'https://images.unsplash.com/photo-1595760780346-f972eb49709f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'), 66 | ), 67 | ), 68 | ), 69 | 70 | //ClipRRect 71 | Container( 72 | margin: EdgeInsets.only(top: 40.0,), 73 | child: Text( 74 | "ClipRRect", 75 | style: Theme.of(context).textTheme.headline4, 76 | ), 77 | ), 78 | ClipRRect( 79 | borderRadius: BorderRadius.circular(300.0), 80 | child: Image.network( 81 | "https://images.unsplash.com/photo-1595152772835-219674b2a8a6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"), 82 | ), 83 | 84 | /// ClipOval 85 | Container( 86 | margin: EdgeInsets.only(top: 40.0,), 87 | child: Text( 88 | "ClipOval", 89 | style: Theme.of(context).textTheme.headline4, 90 | ), 91 | ), 92 | ClipOval( 93 | child: Container( 94 | child: Image.network( 95 | 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'), 96 | ), 97 | ), 98 | 99 | /// ClipPath 100 | Container( 101 | margin: EdgeInsets.only(top: 40.0,), 102 | child: Text( 103 | "ClipPath", 104 | style: Theme.of(context).textTheme.headline4, 105 | ), 106 | ), 107 | ClipPath( 108 | clipper: TriangleClipper(), 109 | child: Image.network( 110 | "https://images.unsplash.com/photo-1519699047748-de8e457a634e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"), 111 | ) 112 | ], 113 | ), 114 | ), 115 | ), 116 | ); 117 | } 118 | } 119 | 120 | class TriangleClipper extends CustomClipper { 121 | @override 122 | Path getClip(Size size) { 123 | final path = Path(); 124 | path.moveTo(size.width / 2, 0.0); 125 | path.lineTo(size.width, size.height); 126 | path.lineTo(0.0, size.height); 127 | path.close(); 128 | return path; 129 | } 130 | 131 | @override 132 | bool shouldReclip(TriangleClipper oldClipper) => false; 133 | } 134 | 135 | 136 | -------------------------------------------------------------------------------- /CutoutEffect.md: -------------------------------------------------------------------------------- 1 | 2 | ![Ougi8](https://user-images.githubusercontent.com/64513385/123238956-8c8f9800-d4fc-11eb-9745-f5aa2c128431.jpg) 3 | 4 | 5 | ```import 'package:flutter/material.dart'; 6 | 7 | void main() => runApp(MyApp()); 8 | 9 | class MyApp extends StatelessWidget { 10 | @override 11 | Widget build(BuildContext context) { 12 | return MaterialApp( 13 | title: 'Flutter Playground', 14 | home: TestPage(), 15 | ); 16 | } 17 | } 18 | 19 | class TestPage extends StatelessWidget { 20 | @override 21 | Widget build(BuildContext context) { 22 | return Container( 23 | decoration: BoxDecoration( 24 | image: DecorationImage(image: AssetImage('assets/earth.jpg'), fit: BoxFit.cover), 25 | ), 26 | child: Center( 27 | child: CustomPaint( 28 | painter: CutOutTextPainter(text: 'YOUR NAME'), 29 | ), 30 | ), 31 | ); 32 | } 33 | } 34 | 35 | class CutOutTextPainter extends CustomPainter { 36 | CutOutTextPainter({this.text}) { 37 | _textPainter = TextPainter( 38 | text: TextSpan( 39 | text: text, 40 | style: TextStyle( 41 | fontSize: 40.0, 42 | fontWeight: FontWeight.w600, 43 | ), 44 | ), 45 | textDirection: TextDirection.ltr, 46 | ); 47 | _textPainter.layout(); 48 | } 49 | 50 | final String text; 51 | TextPainter _textPainter; 52 | 53 | @override 54 | void paint(Canvas canvas, Size size) { 55 | // Draw the text in the middle of the canvas 56 | final textOffset = size.center(Offset.zero) - _textPainter.size.center(Offset.zero); 57 | final textRect = textOffset & _textPainter.size; 58 | 59 | // The box surrounding the text should be 10 pixels larger, with 4 pixels corner radius 60 | final boxRect = RRect.fromRectAndRadius(textRect.inflate(10.0), Radius.circular(4.0)); 61 | final boxPaint = Paint()..color = Colors.white..blendMode=BlendMode.srcOut; 62 | 63 | canvas.saveLayer(boxRect.outerRect, Paint()); 64 | 65 | _textPainter.paint(canvas, textOffset); 66 | canvas.drawRRect(boxRect, boxPaint); 67 | 68 | canvas.restore(); 69 | } 70 | 71 | @override 72 | bool shouldRepaint(CutOutTextPainter oldDelegate) { 73 | return text != oldDelegate.text; 74 | } 75 | } 76 | ``` 77 | -------------------------------------------------------------------------------- /DateTime.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | //Date time field demo 4 | DateTimeFormField( 5 | mode: DateTimeFieldPickerMode.date, 6 | decoration: const InputDecoration( 7 | hintStyle: TextStyle(color: Colors.black45), 8 | errorStyle: TextStyle(color: Colors.redAccent), 9 | border: OutlineInputBorder(), 10 | suffixIcon: Icon(Icons.event_note,color: Colors.black,), 11 | labelStyle:TextStyle(fontSize: 20,color: Colors.grey,letterSpacing: 1.2), 12 | labelText: 'Date of birth', 13 | ), 14 | // autovalidateMode: AutovalidateMode.always, 15 | // validator: (e) => 16 | // (e?.day ?? 0) == 1 ? 'Please not the first day ' : null, 17 | onDateSelected: (DateTime value) { 18 | print(value); 19 | }, 20 | ), 21 | -------------------------------------------------------------------------------- /Elevated-button.dart: -------------------------------------------------------------------------------- 1 | 2 | Elevated Button: 3 | 4 | ElevatedButton( 5 | style: ElevatedButton.styleFrom( 6 | primary: Colors.blue, //button's fill color 7 | onPrimary: Colors.red, //specify the color of the button's text and icons as well as the overlay colors used to indicate the hover, focus, and pressed states 8 | onSurface: Colors.orange, //specify the button's disabled text, icon, and fill color 9 | shadowColor: Colors.black, //specify the button's elevation color 10 | elevation: 4.0, //buttons Material shadow 11 | textStyle: TextStyle(fontFamily: 'roboto'), //specify the button's text TextStyle 12 | padding: const EdgeInsets.only(top: 4.0, bottom: 4.0, right: 8.0, left: 8.0), //specify the button's Padding 13 | minimumSize: Size(20, 40), //specify the button's first: width and second: height 14 | side: BorderSide(color: Colors.yellow, width: 2.0, style: BorderStyle.solid), //set border for the button 15 | shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(35.0)), // set the buttons shape. Make its birders rounded etc 16 | enabledMouseCursor: MouseCursor.defer, //used to construct ButtonStyle.mouseCursor 17 | disabledMouseCursor: MouseCursor.uncontrolled, //used to construct ButtonStyle.mouseCursor 18 | visualDensity: VisualDensity(horizontal: 0.0, vertical: 0.0), //set the button's visual density 19 | tapTargetSize: MaterialTapTargetSize.padded, // set the MaterialTapTarget size. can set to: values, padded and shrinkWrap properties 20 | animationDuration: Duration(milliseconds: 100), //the buttons animations duration 21 | enableFeedback: true, //to set the feedback to true or false 22 | alignment: Alignment.bottomCenter, //set the button's child Alignment 23 | ), 24 | onPressed: () => {} , //set both onPressed and onLongPressed to null to see the disabled properties 25 | onLongPress: () => {}, //set both onPressed and onLongPressed to null to see the disabled properties 26 | child: Text('ElevatedButton') 27 | 28 | ), 29 | -------------------------------------------------------------------------------- /GridView.dart: -------------------------------------------------------------------------------- 1 | // When you want to display your items as a grid rather than a normal list of items that come one after the next then use the GridView widget. 2 | //Like story page in fb or a table 3 | 4 | import 'package:flutter/material.dart'; 5 | void main() { 6 | runApp(MyApp()); 7 | } 8 | class MyApp extends StatelessWidget { 9 | @override 10 | Widget build(BuildContext context) { 11 | final title = 'Grid List'; 12 | 13 | return MaterialApp( 14 | title: title, 15 | home: Scaffold( 16 | appBar: AppBar( 17 | title: Text(title), 18 | ), 19 | body: GridView.count( 20 | // Create a grid with 2 columns. If you change the scrollDirection to 21 | // horizontal, this produces 2 rows. 22 | crossAxisCount: 2, 23 | // Generate 100 widgets that display their index in the List. 24 | children: List.generate(100, (index) { 25 | return Center( 26 | child: Text( 27 | 'Item $index', 28 | style: Theme.of(context).textTheme.headline5, 29 | ), 30 | ); 31 | }), 32 | ), 33 | ), 34 | ); 35 | } 36 | } 37 | 38 | 39 | ------------------------------------------------------------/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\--------------------------------------------------------------------------- 40 | 41 | ----------------------------A GRIDVIEW TO MAKE KIND OF STORY GRID(IN FB) WITH PROFILE PIC + NAME + IMAGE + LIKE BUTTON EMBEDDED------------------------------------------- 42 | Widget build(BuildContext context) { 43 | var size = MediaQuery.of(context).size; 44 | final double itemHeight = (size.height - kToolbarHeight -150) / 2; 45 | final double itemWidth = size.width / 2; 46 | 47 | .... 48 | ..... 49 | 50 | 51 | GridView.count( 52 | crossAxisCount: 2, 53 | childAspectRatio: (itemWidth / itemHeight), 54 | children: List.generate(active.length, (index) { 55 | return Center( 56 | child: Container( 57 | width: MediaQuery.of(context).size.width*0.4, 58 | height: 240, 59 | decoration: BoxDecoration( 60 | border: Border.all(color: Colors.grey.shade200), 61 | shape: BoxShape.rectangle, 62 | borderRadius:BorderRadius.circular(10) 63 | ), 64 | child: Column( 65 | children: [ 66 | Stack(children: [ 67 | Padding( 68 | padding: EdgeInsets.only(top: 30), 69 | child: Image.asset(active[index].storyImage)), 70 | Positioned( 71 | top: 4, 72 | left: 6, 73 | child: CircleAvatar( 74 | radius: 21, 75 | backgroundColor: pPrimaryColor, 76 | child: CircleAvatar( 77 | backgroundColor: Colors.amber, 78 | child: Text( 79 | active[index].name[0], 80 | style: TextStyle( 81 | fontSize: 16, 82 | fontWeight: FontWeight.bold, 83 | color: Colors.black), 84 | ), 85 | radius: 18, 86 | ), 87 | ), 88 | ), 89 | Positioned( 90 | top: 4, 91 | right: 8, 92 | child: Text( 93 | active[index].name, 94 | style: TextStyle( 95 | color: Theme.of(context).textTheme.bodyText1!.color, 96 | fontWeight: FontWeight.bold))), 97 | Positioned( 98 | bottom: -10, 99 | right: -2, 100 | child:IconButton( 101 | icon: active[index].isFavorite 102 | ? Icon(Icons.thumb_up, color: Colors.red) 103 | : Icon(Icons.thumb_up_alt_outlined), 104 | onPressed: () { 105 | setState(() { 106 | active[index].isFavorite = 107 | !active[index].isFavorite; 108 | print("pressed"); 109 | }); } 110 | ) 111 | ), 112 | ]) 113 | ], 114 | ), 115 | ) 116 | ); 117 | } 118 | ), 119 | ), 120 | -------------------------------------------------------------------------------- /Multiple-color-theme-app.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | import 'package:flutter/material.dart'; 4 | 5 | Color pPrimaryColor = Color(0xFFba2d65); 6 | Color pMedColor = Color(0xFFf06292); 7 | Color pSecondaryColor = Color(0xFFff94c2); 8 | Color pContentColorLightTheme = Color(0xFF1D1D35); 9 | Color pContentColorDarkTheme = Color(0xFFF5FCF9); 10 | Color pWarninngColor = Color(0xFFF3BB1C); 11 | Color pErrorColor = Color(0xFFF03738); 12 | const pDefaultPadding = 20.0; 13 | 14 | class ColorChange extends StatefulWidget { 15 | ColorChange({Key? key}) : super(key: key); 16 | 17 | @override 18 | _ColorChangeState createState() => _ColorChangeState(); 19 | } 20 | 21 | class _ColorChangeState extends State { 22 | @override 23 | Widget build(BuildContext context) { 24 | 25 | return Container( 26 | child: Column( 27 | children: [ 28 | Text('Choose your theme',style: TextStyle(color: Theme.of(context).textTheme.bodyText1!.color,fontSize: 15,fontWeight: FontWeight.bold),), 29 | Row( 30 | mainAxisAlignment: MainAxisAlignment.center, 31 | crossAxisAlignment: CrossAxisAlignment.center, 32 | children: [ 33 | // Spacer(), 34 | Padding( 35 | padding: const EdgeInsets.only(top:12.0), 36 | child: RawMaterialButton( 37 | onPressed: (){ 38 | setState(() { 39 | pPrimaryColor = Color(0xFFba2d65); 40 | pMedColor = Color(0xFFf06292); 41 | pSecondaryColor = Color(0xFFff94c2); 42 | }); 43 | }, 44 | elevation: 3.0, 45 | // fillColor: Colors.white, 46 | fillColor: Theme.of(context).textTheme.bodyText1!.color, 47 | child: Icon( 48 | Icons.color_lens, 49 | size: 50.0, 50 | color: Colors.pink[900], 51 | ), 52 | padding: EdgeInsets.all(10.0), 53 | shape: CircleBorder(), 54 | ), 55 | ), 56 | Padding( 57 | padding: const EdgeInsets.only(top:12.0), 58 | child: RawMaterialButton( 59 | onPressed: (){ 60 | setState(() { 61 | pPrimaryColor = Color(0xFF1a746b); 62 | pMedColor = Color(0xFF26a69a); 63 | pSecondaryColor = Color(0xFF51b7ae); 64 | }); 65 | }, 66 | elevation: 3.0, 67 | // fillColor: Colors.white, 68 | fillColor: Theme.of(context).textTheme.bodyText1!.color, 69 | child: Icon( 70 | Icons.color_lens, 71 | size: 50.0, 72 | color: Colors.teal, 73 | ), 74 | padding: EdgeInsets.all(10.0), 75 | shape: CircleBorder(), 76 | ), 77 | ), 78 | Padding( 79 | padding: const EdgeInsets.only(top:12.0), 80 | child: RawMaterialButton( 81 | onPressed: (){ 82 | setState(() { 83 | pPrimaryColor = Color(0xFFc79100); 84 | pMedColor = Color(0xFFffc107); 85 | pSecondaryColor = Color(0xFFfff350); 86 | }); 87 | }, 88 | elevation: 3.0, 89 | // fillColor: Colors.white, 90 | fillColor: Theme.of(context).textTheme.bodyText1!.color, 91 | child: Icon( 92 | Icons.color_lens, 93 | size: 50.0, 94 | color: Colors.yellow, 95 | ), 96 | padding: EdgeInsets.all(10.0), 97 | shape: CircleBorder(), 98 | ), 99 | ), 100 | Padding( 101 | padding: const EdgeInsets.only(top:12.0), 102 | child: RawMaterialButton( 103 | onPressed: (){ 104 | setState(() { 105 | pPrimaryColor = Color(0xFF6a0080); 106 | pMedColor = Color(0xFF9c27b0); 107 | pSecondaryColor = Color(0xFFd05ce3); 108 | }); 109 | }, 110 | elevation: 3.0, 111 | // fillColor: Colors.white, 112 | fillColor: Theme.of(context).textTheme.bodyText1!.color, 113 | child: Icon( 114 | Icons.color_lens, 115 | size: 50.0, 116 | color: Colors.purple, 117 | ), 118 | padding: EdgeInsets.all(10.0), 119 | shape: CircleBorder(), 120 | ), 121 | ), 122 | ], 123 | ), 124 | ], 125 | )); 126 | } 127 | } 128 | 129 | -------------------------------------------------------------------------------- /Quick accetions in flutter.md: -------------------------------------------------------------------------------- 1 |

 


Add quick_actions: ^0.3.0+2 package in your .yaml file

import the quick_actions package and create a new instance of the QuickActions in the Manager's state class.


2 | 3 |
  
 4 | import 'package:quick_actions/quick_actions.dart';
 5 | 
 6 | class _QuickActionsManagerState extends State {
 7 |   final QuickActions quickActions = QuickActions();
 8 | 
 9 | }
10 | 
11 |

Setup Quick Actions.


12 |
  
13 | void _setupQuickActions() {
14 |     quickActions.setShortcutItems([
15 |       ShortcutItem(
16 |           type: 'action_main',
17 |           localizedTitle: 'Main view',
18 |           icon: icons.menu),
19 |       ShortcutItem(
20 |           type: 'action_help',
21 |           localizedTitle: 'Help',
22 |           icon: icons.help)
23 |     ]);
24 |   }
25 | 
26 | 27 |

Handle Selected Action.


28 |
  
29 | void _handleQuickActions() {
30 |   quickActions.initialize((shortcutType) {
31 |     if (shortcutType == 'action_main') {
32 |       Navigator.push(
33 |           context, MaterialPageRoute(builder: (context) => Login()));
34 |     } else if(shortcutType == 'action_help') {
35 |       print('Show the help dialog!');
36 |     }
37 |   });
38 | }
39 | 
40 | 41 |

Use it.


42 | 43 |
  
44 | @override
45 | void initState() {
46 |   super.initState();
47 |   _setupQuickActions();
48 |   _handleQuickActions();
49 | }
50 | 
51 | -------------------------------------------------------------------------------- /RegEx to extract URLs from a String.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | final text = """My website url: https://blasanka.github.io/ 3 | Google search using: www.google.com, social media is facebook.com, http://example.com/method?param=flutter 4 | stackoverflow.com is my greatest website. DartPad share: https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide see this example and edit it here https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00"""; 5 | 6 | RegExp exp = new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+'); 7 | Iterable matches = exp.allMatches(text); 8 | 9 | matches.forEach((match) { 10 | print(text.substring(match.start, match.end)); 11 | }); 12 | } 13 | -------------------------------------------------------------------------------- /Stacked Images.dart: -------------------------------------------------------------------------------- 1 | // Create stacked images 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:flutter/rendering.dart'; 5 | import 'package:image_stack/image_stack.dart'; 6 | 7 | void main() => runApp(MyApp()); 8 | 9 | class MyApp extends StatelessWidget { 10 | @override 11 | Widget build(BuildContext context) { 12 | List images = []; 13 | images.add('assets/blackwidow.jfif'); 14 | images.add('assets/captAmerica.jfif'); 15 | images.add('assets/iron.jpg'); 16 | images.add('assets/thor.jfif'); 17 | images.add('assets/hulk.jfif'); 18 | 19 | return MaterialApp( 20 | debugShowCheckedModeBanner: false, 21 | title: 'Image Stack', 22 | theme: ThemeData( 23 | primarySwatch: Colors.blue, 24 | ), 25 | home: Scaffold( 26 | body: Container( 27 | color: Colors.white, 28 | child: Center( 29 | child: Row( 30 | mainAxisAlignment: MainAxisAlignment.center, 31 | crossAxisAlignment: CrossAxisAlignment.center, 32 | children: [ 33 | ImageStack( 34 | imageList: images, 35 | imageRadius: 150, 36 | imageCount: 5, 37 | imageBorderWidth: 3, 38 | totalCount: 5, 39 | backgroundColor: Colors.amber, 40 | ), 41 | ], 42 | ), 43 | ), 44 | ), 45 | ), 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Survey.dart: -------------------------------------------------------------------------------- 1 | //Firstly add the dependency survey_kit: ^0.0.11 (latest one) 2 | // Run flutter pub get 3 | // Then find the code below(modify as per requirements.:)) 4 | 5 | 6 | import 'package:flutter/material.dart'; 7 | import 'package:survey_kit/survey_kit.dart'; 8 | class Surveys_custom extends StatefulWidget { 9 | Surveys_custom({Key key}) : super(key: key); 10 | 11 | @override 12 | _Surveys_customState createState() => _Surveys_customState(); 13 | } 14 | 15 | class _Surveys_customState extends State { 16 | @override 17 | Widget build(BuildContext context) { 18 | return Scaffold( 19 | body: Container( 20 | color: Colors.white, 21 | child: Align( 22 | alignment: Alignment.center, 23 | child: Container( 24 | height: double.infinity, 25 | width: 600, 26 | child: SurveyKit( 27 | onResult: (SurveyResult result) { 28 | print(result.finishReason); 29 | }, 30 | task: getSampleTask(), 31 | themeData: Theme.of(context).copyWith( 32 | colorScheme: ColorScheme.fromSwatch( 33 | primarySwatch: Colors.cyan, 34 | ).copyWith( 35 | onPrimary: Colors.white, 36 | ), 37 | primaryColor: Colors.purpleAccent, 38 | backgroundColor: Colors.white, 39 | appBarTheme: const AppBarTheme( 40 | color: Colors.white, 41 | iconTheme: IconThemeData( 42 | color: Colors.purpleAccent, 43 | ), 44 | textTheme: TextTheme( 45 | button: TextStyle( 46 | color: Colors.cyan, 47 | ), 48 | ), 49 | ), 50 | iconTheme: const IconThemeData( 51 | color: Colors.purpleAccent, 52 | ), 53 | outlinedButtonTheme: OutlinedButtonThemeData( 54 | style: ButtonStyle( 55 | minimumSize: MaterialStateProperty.all( 56 | Size(150.0, 60.0), 57 | ), 58 | side: MaterialStateProperty.resolveWith( 59 | (Set state) { 60 | if (state.contains(MaterialState.disabled)) { 61 | return BorderSide( 62 | color: Colors.grey, 63 | ); 64 | } 65 | return BorderSide( 66 | color: Colors.purpleAccent, 67 | ); 68 | }, 69 | ), 70 | shape: MaterialStateProperty.all( 71 | RoundedRectangleBorder( 72 | borderRadius: BorderRadius.circular(8.0), 73 | ), 74 | ), 75 | textStyle: MaterialStateProperty.resolveWith( 76 | (Set state) { 77 | if (state.contains(MaterialState.disabled)) { 78 | return Theme.of(context).textTheme.button?.copyWith( 79 | color: Colors.grey, 80 | ); 81 | } 82 | return Theme.of(context).textTheme.button?.copyWith( 83 | color: Colors.purpleAccent, 84 | ); 85 | }, 86 | ), 87 | ), 88 | ), 89 | textButtonTheme: TextButtonThemeData( 90 | style: ButtonStyle( 91 | textStyle: MaterialStateProperty.all( 92 | Theme.of(context).textTheme.button?.copyWith( 93 | color: Colors.cyan, 94 | ), 95 | ), 96 | ), 97 | ), 98 | ), 99 | ), 100 | ), 101 | ), 102 | ), 103 | ); 104 | } 105 | 106 | Task getSampleTask() { 107 | var task = NavigableTask( 108 | id: TaskIdentifier(), 109 | steps: [ 110 | InstructionStep( 111 | title: 'Welcome to the\nDeal Brand\nGoogle Survey', 112 | text: 'Get ready for a bunch of super interesting questions!', 113 | buttonText: 'Let\'s go!', 114 | ), 115 | QuestionStep( 116 | title: 'How old are you?', 117 | answerFormat: IntegerAnswerFormat( 118 | defaultValue: 25, 119 | hint: 'Please enter your age', 120 | 121 | ), 122 | ), 123 | QuestionStep( 124 | title: 'Shpping?', 125 | text: 'Do you prefer online shopping?', 126 | answerFormat: BooleanAnswerFormat( 127 | positiveAnswer: 'Yes', 128 | negativeAnswer: 'No', 129 | result: BooleanResult.POSITIVE, 130 | ), 131 | ), 132 | // QuestionStep( 133 | // title: 'Tell us about you', 134 | // text: 135 | // 'Tell us about yourself and why you want to improve your health.', 136 | // answerFormat: TextAnswerFormat( 137 | // maxLines: 5, 138 | // ), 139 | // ), 140 | QuestionStep( 141 | title: 'Rate the app', 142 | answerFormat: ScaleAnswerFormat( 143 | step: 3, 144 | minimumValue: 1, 145 | maximumValue: 5, 146 | defaultValue: 3, 147 | minimumValueDescription: '1', 148 | maximumValueDescription: '5', 149 | ), 150 | ), 151 | QuestionStep( 152 | title: 'Favourite Sport', 153 | text: 'Which of the following sports do you watch ?', 154 | answerFormat: MultipleChoiceAnswerFormat( 155 | textChoices: [ 156 | TextChoice(text: 'Football', value: 'Football'), 157 | TextChoice(text: 'Basket ball', value: 'Basket ball'), 158 | TextChoice(text: 'Gymnastics', value: 'Gymnastics'), 159 | TextChoice(text: 'Swimming', value: 'Swimming'), 160 | TextChoice(text: 'Auto Racing', value: 'autoracing'), 161 | TextChoice(text: 'Baseball', value: 'Baseball'), 162 | ], 163 | ), 164 | ), 165 | QuestionStep( 166 | title: 'Done?', 167 | text: 'We are done, do you mind to tell us more about yourself...?', 168 | answerFormat: SingleChoiceAnswerFormat( 169 | textChoices: [ 170 | TextChoice(text: 'Yes', value: 'Yes'), 171 | TextChoice(text: 'No', value: 'No'), 172 | ], 173 | ), 174 | ), 175 | QuestionStep( 176 | title: 'When are your office hours?', 177 | answerFormat: TimeAnswerFormat( 178 | defaultValue: TimeOfDay( 179 | hour: 12, 180 | minute: 0, 181 | ), 182 | ), 183 | ), 184 | QuestionStep( 185 | title: 'When was your last holiday?', 186 | answerFormat: DateAnswerFormat( 187 | minDate: DateTime.utc(1970), 188 | defaultDate: DateTime.now(), 189 | maxDate: DateTime.now(), 190 | ), 191 | ), 192 | CompletionStep( 193 | id: StepIdentifier(id: '321'), 194 | text: 'Thanks for taking the survey, we will contact you soon!', 195 | title: 'Done!', 196 | buttonText: 'Submit survey', 197 | ), 198 | ], 199 | ); 200 | task.addNavigationRule( 201 | forTriggerStepIdentifier: task.steps[6].id, 202 | navigationRule: ConditionalNavigationRule( 203 | resultToStepIdentifierMapper: (input) { 204 | switch (input) { 205 | case "Yes": 206 | return task.steps[0].id; 207 | case "No": 208 | return task.steps[7].id; 209 | default: 210 | return null; 211 | } 212 | }, 213 | ), 214 | ); 215 | return task; 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /TableInDart.dart: -------------------------------------------------------------------------------- 1 | Table( 2 | border: TableBorder.all(), // Allows to add a border decoration around your table 3 | children: [ 4 | TableRow(children :[ 5 | Text('Year'), 6 | Text('Lang'), 7 | Text('Author'), 8 | ]), 9 | TableRow(children :[ 10 | Text('2011',), 11 | Text('Dart'), 12 | Text('Lars Bak'), 13 | ]), 14 | TableRow(children :[ 15 | Text('1996'), 16 | Text('Java'), 17 | Text('James Gosling'), 18 | ]), 19 | ] 20 | ), 21 | -------------------------------------------------------------------------------- /adding-svg-icons.dart: -------------------------------------------------------------------------------- 1 | //firstly add the dependencies 2 | flutter_svg: ^0.22.0 //(whichever be the latest version) in your pubspec.yaml file 3 | 4 | // then import the package - 5 | import 'package:flutter_svg/svg.dart'; 6 | 7 | // then add the svg icon like : 8 | SvgPicture.asset( 9 | "assets/icons/chat.svg", 10 | // color: Theme.of(context).textTheme.bodyText1!.color, (for light/dark theme compatiblity ) 11 | color: Colors.red, 12 | height: 200, 13 | width: 200, 14 | ), 15 | 16 | //Preffered site for best svgs (Personal recommendation) - 17 | https://iconscout.com/icons/ 18 | -------------------------------------------------------------------------------- /apiCalls.dart: -------------------------------------------------------------------------------- 1 | //This file will contain all the rest api integrations code for create/post/patch/delete 2 | import 'dart:convert'; 3 | import 'package:dash_admin_dashboard/Dashboard/MenuItems/feature.dart'; 4 | import 'package:shared_preferences/shared_preferences.dart'; 5 | import 'package:http/http.dart' as http; 6 | 7 | class NetworkHandler { 8 | String baseurl = "http://dev-doas.codsgn.in/v1/"; 9 | Future post(String url, Map body) async { 10 | SharedPreferences prefs = await SharedPreferences.getInstance(); 11 | String token = prefs.getString("token"); 12 | url = formatter(url); 13 | print(url); 14 | var response = await http.post( 15 | Uri.parse(url), 16 | headers: { 17 | "Content-type": "application/json", 18 | 'Accept': 'application/json', 19 | 'Authorization': 'Bearer $token', 20 | }, 21 | body: json.encode(body), 22 | ); 23 | print(response.body); 24 | return response; 25 | } 26 | Future post1(String url, var body) async { 27 | SharedPreferences prefs = await SharedPreferences.getInstance(); 28 | String token = prefs.getString("token"); 29 | url = formatter(url); 30 | print(url); 31 | var response = await http.post( 32 | Uri.parse(url), 33 | headers: { 34 | "Content-type": "application/json", 35 | 'Accept': 'application/json', 36 | 'Authorization': 'Bearer $token', 37 | }, 38 | body: json.encode(body), 39 | ); 40 | print(response.body); 41 | return response; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /apiCallswithMultipartRequest.dart: -------------------------------------------------------------------------------- 1 | import 'package:path/path.dart'; 2 | import 'package:async/async.dart'; 3 | import 'dart:io'; 4 | import 'package:http/http.dart' as http; 5 | 6 | 7 | void uploadImage1(File _image) async { 8 | 9 | // open a byteStream 10 | var stream = new http.ByteStream(_image.openRead()); 11 | // get file length 12 | var length = await _image.length(); 13 | 14 | // string to uri 15 | var uri = Uri.parse("enter here upload URL"); 16 | 17 | // create multipart request 18 | var request = new http.MultipartRequest("POST", uri); 19 | 20 | // if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request 21 | request.fields["user_id"] = "text"; 22 | 23 | // multipart that takes file.. here this "image_file" is a key of the API request 24 | var multipartFile = new http.MultipartFile('image_file', stream, length, filename: basename(_image.path)); 25 | 26 | // add file to multipart 27 | request.files.add(multipartFile); 28 | 29 | // send request to upload image 30 | await request.send().then((response) async { 31 | // listen for response 32 | response.stream.transform(utf8.decoder).listen((value) { 33 | print(value); 34 | }); 35 | 36 | }).catchError((e) { 37 | print(e); 38 | }); 39 | } 40 | -------------------------------------------------------------------------------- /appbar-tricks.dart: -------------------------------------------------------------------------------- 1 | 2 | //Removing extra padding around appbar leading icon(use titlespacing) - 3 | 4 | appBar: AppBar( 5 | leading: Icon(Icons.android), 6 | titleSpacing: 0, //Just add a property called titleSpacing, 7 | title: Text(widget.title), 8 | ), 9 | 10 | // To increse the leading width of appbar - 11 | 12 | appBar: AppBar( 13 | leading: Icon(Icons.account_circle_rounded), 14 | leadingWidth: 100, // default is 56 15 | ), 16 | 17 | //To increase the default height & alter opacity of appbar - 18 | 19 | appBar: AppBar( 20 | toolbarHeight: 120, 21 | toolbarOpacity: 0.5, 22 | leadingWidth: 100, // default is 56 23 | ), 24 | 25 | // Image in title in appbar - 26 | 27 | AppBar( 28 | title: Container( 29 | width: 40, 30 | child: Image.network(url), 31 | ), 32 | centerTitle: true, 33 | ), 34 | 35 | -------------------------------------------------------------------------------- /bottom-nav-bar.dart: -------------------------------------------------------------------------------- 1 | //A demo to implement bottomnavigationbar in flutter 2 | 3 | class _ChatPageState extends State { 4 | int _selectedIndex = 0; 5 | final List _children = [Chats(),Calls(), People()]; 6 | @override 7 | Widget build(BuildContext context) { 8 | return Scaffold( 9 | body: _children[_selectedIndex], 10 | floatingActionButton: FloatingActionButton( 11 | onPressed: () {}, 12 | backgroundColor: pPrimaryColor, 13 | child: Icon( 14 | Icons.person_add_alt_1_rounded, 15 | color: Colors.white, 16 | ), 17 | ), 18 | bottomNavigationBar: BottomNavigationBar( 19 | type: BottomNavigationBarType.fixed, 20 | currentIndex: _selectedIndex, 21 | onTap: (value) { 22 | setState(() { 23 | _selectedIndex = value; 24 | }); 25 | }, 26 | items: [ 27 | BottomNavigationBarItem(icon: Icon(Icons.messenger), label: "Chats"), 28 | BottomNavigationBarItem(icon: Icon(Icons.people), label: "People"), 29 | BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), 30 | ], 31 | ), 32 | ); 33 | } 34 | } 35 | 36 | 37 | -----------------------------/\/\/\/\/\/\\/\/\/\/\/\/\/\\/\/\/\/\/\/\---------------------------------------------------------- 38 | 39 | //Bottom navbar with circle avartar + change of icons when moved from one page to another 40 | 41 | Scaffold( 42 | body: _children[_selectedIndex], 43 | bottomNavigationBar: BottomNavigationBar( 44 | type: BottomNavigationBarType.fixed, 45 | selectedIconTheme: IconThemeData(color: pPrimaryColor), 46 | currentIndex: _selectedIndex, 47 | backgroundColor: !isDark?Colors.white:Colors.black, 48 | selectedItemColor: isDark?Colors.grey:Colors.black, 49 | showSelectedLabels: false, 50 | showUnselectedLabels: false, 51 | elevation: 0, 52 | onTap: (value) { 53 | setState(() { 54 | _selectedIndex = value; 55 | }); 56 | }, 57 | items: [ 58 | BottomNavigationBarItem( 59 | icon: _selectedIndex==0?Icon(Icons.home,color: Colors.black,size: 28,): Icon(Icons.home_outlined,color: Colors.black,size: 28,),label: 'home'), 60 | BottomNavigationBarItem(icon: _selectedIndex==1?Icon(Icons.search,color: Colors.black,size: 28,): Icon(Icons.search_outlined,color: Colors.black,size: 28,),label: 'search'), 61 | BottomNavigationBarItem(icon: _selectedIndex==2?Icon(Icons.video_collection_sharp,color: Colors.black,size: 28,): Icon(Icons.video_collection_outlined,color: Colors.black,size: 28,),label: 'reels' ), 62 | BottomNavigationBarItem(icon: _selectedIndex==3?Icon(Icons.favorite,color: Colors.black,size: 28,):Icon(Icons.favorite_border_outlined,color: Colors.black,size: 28,),label: 'notif'), 63 | BottomNavigationBarItem(icon: _selectedIndex==4? 64 | CircleAvatar( 65 | radius: 14, 66 | backgroundColor: Colors.black, 67 | child: CircleAvatar( 68 | radius: 13, 69 | backgroundImage:AssetImage('assets/profilepic.jpg') ,), 70 | ): 71 | CircleAvatar( 72 | radius: 14, 73 | backgroundImage:AssetImage('assets/profilepic.jpg') ,), 74 | label: 'profile' 75 | ), 76 | 77 | ], 78 | 79 | ), 80 | ); 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /caraousel.dart: -------------------------------------------------------------------------------- 1 | // Firstly Import carousel slider 2 | 3 | class ImageSliderDemo extends StatefulWidget { 4 | @override 5 | _ImageSliderDemoState createState() => _ImageSliderDemoState(); 6 | } 7 | int _current = 0; 8 | final CarouselController _controller = CarouselController(); 9 | class _ImageSliderDemoState extends State { 10 | final List imgList = [ 11 | 'https://images.unsplash.com/photo-1610438235354-a6ae5528385c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=334&q=80', 12 | 'https://images.unsplash.com/photo-1517336714731-489689fd1ca8?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=626&q=80' 13 | 'https://images.unsplash.com/photo-1606220588913-b3aacb4d2f46?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=750&q=80', 14 | 'https://images.unsplash.com/photo-1585298723682-7115561c51b7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=400&q=80', 15 | 'https://images.unsplash.com/photo-1546868871-7041f2a55e12?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDEyfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60', 16 | 'https://images.unsplash.com/photo-1569429594806-192f16855a0e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDd8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=500&q=60', 17 | 'https://images.unsplash.com/photo-1548484352-ea579e5233a8?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80' 18 | 'https://images.unsplash.com/photo-1517336714731-489689fd1ca8?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=626&q=80' 19 | ]; 20 | 21 | 22 | @override 23 | Widget build(BuildContext context) { 24 | 25 | return Column( 26 | children: [ 27 | Container( 28 | child: CarouselSlider( 29 | options: CarouselOptions( 30 | enlargeCenterPage: true, 31 | enableInfiniteScroll: true, 32 | onPageChanged: (index, reason) { 33 | setState(() { 34 | _current = index; 35 | }); 36 | } 37 | ), 38 | items: imgList 39 | .map((item) => Container( 40 | child: Center( 41 | child: Stack( 42 | children: [ 43 | Container( 44 | width: 1200, 45 | decoration:BoxDecoration( 46 | borderRadius: BorderRadius.circular(30), 47 | image: DecorationImage( 48 | image: NetworkImage(item), 49 | fit: BoxFit.cover,)), 50 | ), 51 | //: Image.network(item, fit: BoxFit.cover, width: 1200)), 52 | Align( 53 | alignment: Alignment.bottomRight, 54 | child: Padding( 55 | padding: const EdgeInsets.only(right: 10,bottom: 6), 56 | child: ClipRect( 57 | 58 | child: BackdropFilter( 59 | filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), 60 | child: Container( 61 | width: 120, 62 | height: 30, 63 | decoration: BoxDecoration( 64 | borderRadius: BorderRadius.circular(20), 65 | color: Colors.grey.withOpacity(0.5), 66 | ), 67 | child: Row( 68 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, 69 | children: [ 70 | Text('Shop Now',style: TextStyle(color: Colors.white,fontFamily: 'Ubuntu',letterSpacing: 2,fontWeight: FontWeight.w600),), 71 | Icon(Icons.arrow_forward_ios,color: Colors.white,size: 15,), 72 | ], 73 | ), 74 | ), 75 | 76 | ), 77 | ), 78 | ), 79 | ) 80 | ], 81 | )), 82 | )) 83 | .toList(), 84 | )), 85 | Row( 86 | mainAxisAlignment: MainAxisAlignment.center, 87 | children: imgList.asMap().entries.map((entry) { 88 | return GestureDetector( 89 | onTap: () => _controller.animateToPage(entry.key), 90 | child: Container( 91 | width: 6.0, 92 | height: 6.0, 93 | margin: EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0), 94 | decoration: BoxDecoration( 95 | shape: BoxShape.circle, 96 | color: (Theme.of(context).brightness == Brightness.dark 97 | ? Colors.white 98 | : Colors.black) 99 | .withOpacity(_current == entry.key ? 0.9 : 0.4)), 100 | ), 101 | ); 102 | }).toList(), 103 | ), 104 | ], 105 | 106 | ); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /dark-mode.dart: -------------------------------------------------------------------------------- 1 | final Brightness brightnessValue = 2 | MediaQuery.of(context).platformBrightness; 3 | bool isDark = brightnessValue == Brightness.dark; 4 | 5 | 6 | //set the color to - 7 | color: Theme.of(context).textTheme.bodyText1!.color 8 | 9 | 10 | //checking if the system is in dark mode or light mode - 11 | Image.asset( 12 | MediaQuery.of(context).platformBrightness == Brightness.light 13 | ? "assets/lightmode2.png" 14 | :"assets/darkmode.png", 15 | height: 256, 16 | ) 17 | 18 | 19 | //Check system mode - 20 | Widget build(BuildContext context) { 21 | final Brightness brightnessValue = MediaQuery.of(context).platformBrightness; 22 | bool isDark = brightnessValue == Brightness.dark; 23 | . . . . . 24 | . . . . . 25 | . . . . . 26 | Text( 27 | 'Choose your theme', 28 | style: isDark == true ? TextStyle( 29 | color: Colors.black, 30 | fontSize: 16, 31 | letterSpacing: 4, 32 | fontWeight: FontWeight.w500 33 | ): 34 | TextStyle( 35 | color: Colors.white, 36 | fontSize: 16, 37 | letterSpacing: 4, 38 | fontWeight: FontWeight.w500 39 | ), 40 | ), 41 | -------------------------------------------------------------------------------- /datepicker.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flutter/material.dart'; 4 | 5 | void main() => runApp(MyApp()); 6 | class MyApp extends StatelessWidget { 7 | @override 8 | Widget build(BuildContext context) { 9 | return MaterialApp( 10 | title: 'Flutter Demo', 11 | home: MyHomePage(), 12 | ); 13 | } 14 | } 15 | class MyHomePage extends StatefulWidget { 16 | 17 | @override 18 | _MyHomePageState createState() => _MyHomePageState(); 19 | } 20 | 21 | class _MyHomePageState extends State { 22 | DateTime selectedDate = DateTime.now(); 23 | 24 | Future _selectDate(BuildContext context) async { 25 | final DateTime picked = await showDatePicker( 26 | context: context, 27 | initialDate: selectedDate, 28 | firstDate: DateTime(2015, 8), 29 | lastDate: DateTime(2101)); 30 | if (picked != null && picked != selectedDate) 31 | setState(() { 32 | selectedDate = picked; 33 | }); 34 | } 35 | 36 | @override 37 | Widget build(BuildContext context) { 38 | return Scaffold( 39 | appBar: AppBar( 40 | title: Text('date picker'), 41 | ), 42 | body: Center( 43 | child: Column( 44 | mainAxisSize: MainAxisSize.min, 45 | children: [ 46 | Text("${selectedDate.toLocal()}".split(' ')[0]), 47 | SizedBox(height: 20.0,), 48 | RaisedButton( 49 | onPressed: () => _selectDate(context), 50 | child: Text('Select date'), 51 | ), 52 | ], 53 | ), 54 | ), 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /divider.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | Divider( 4 | color: Colors.grey[300], 5 | //height:50, 6 | thickness: 1, 7 | indent: 65, 8 | endIndent: 5, 9 | ), 10 | 11 | -------------------------------------------------------------------------------- /draggableScrollableSheet.dart: -------------------------------------------------------------------------------- 1 | class HomePage extends StatelessWidget { 2 | const HomePage({Key? key}) : super(key: key); 3 | 4 | @override 5 | Widget build(BuildContext context) { 6 | return Scaffold( 7 | appBar: AppBar( 8 | title: const Text('DraggableScrollableSheet'), 9 | ), 10 | body: SizedBox.expand( 11 | child: DraggableScrollableSheet( 12 | builder: (BuildContext context, ScrollController scrollController) { 13 | return Container( 14 | color: Colors.blue[100], 15 | child: ListView.builder( 16 | controller: scrollController, 17 | itemCount: 25, 18 | itemBuilder: (BuildContext context, int index) { 19 | return ListTile(title: Text('Item $index')); 20 | }, 21 | ), 22 | ); 23 | }, 24 | ), 25 | ), 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /drawer.dart: -------------------------------------------------------------------------------- 1 | //It will navigate to the page and have the focused color in the tab where it is present......for flutter web... 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:practise_widgets/drawerItems/Dart.dart'; 5 | import 'package:practise_widgets/drawerItems/flutter.dart'; 6 | import 'package:practise_widgets/drawerItems/ios.dart'; 7 | class CustomDrawer extends StatefulWidget { 8 | static final List _listViewData = [ 9 | "Flutter", 10 | "Ios", 11 | "Dart", 12 | "Android", 13 | "Laravel", 14 | "Php", 15 | "Html", 16 | ]; 17 | final List _children = [ 18 | Flutter(), 19 | IOS(), 20 | Dart(), 21 | ]; 22 | static int _currentSelected = 0; 23 | @override 24 | _CustomDrawerState createState() => _CustomDrawerState(); 25 | } 26 | 27 | class _CustomDrawerState extends State { 28 | 29 | @override 30 | Widget build(BuildContext context) { 31 | return Drawer( 32 | child: Container( 33 | child: ListView.builder( 34 | padding: EdgeInsets.all(10.0), 35 | itemCount: CustomDrawer._listViewData.length, 36 | itemBuilder: (context, index) { 37 | return Container( 38 | color: CustomDrawer._currentSelected == index 39 | ? Colors.deepPurple 40 | : Colors.white, 41 | child: ListTile( 42 | title: Text(CustomDrawer._listViewData[index]), 43 | onTap: () { 44 | setState(() { 45 | CustomDrawer._currentSelected = index; 46 | }); 47 | Navigator.push( 48 | context, 49 | MaterialPageRoute( 50 | builder: (context) => widget._children[index])); 51 | }, 52 | ), 53 | ); 54 | }, 55 | ), 56 | ), 57 | ); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /dropdown.dart: -------------------------------------------------------------------------------- 1 | //demo dropdown -> 2 | 3 | List _items = [ 4 | 'Accounts', 5 | 'Management', 6 | 'Tech', 7 | 'Product', 8 | 'Design', 9 | 'Operations' 10 | ]; 11 | Widget drop() { 12 | return DropdownButtonHideUnderline( 13 | child: new DropdownButton( 14 | isExpanded: true, 15 | hint: Text('Department'), 16 | value: value, 17 | style: TextStyle(fontSize: 18, color: Colors.black), 18 | items: _items.map((value) { 19 | return new DropdownMenuItem( 20 | value: value, 21 | child: new Text(value), 22 | ); 23 | }).toList(), 24 | onChanged: (newValue) { 25 | setState(() { 26 | value = newValue; 27 | }); 28 | print(value); 29 | }, 30 | ), 31 | ); 32 | } 33 | -------------------------------------------------------------------------------- /fb-google-social-login.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | // A demo social login UI (have to include the svg files in the assets...) 5 | Row( 6 | mainAxisAlignment: MainAxisAlignment.center, 7 | children: [ 8 | SocalIcon( 9 | iconSrc: "assets/icons/facebook.svg", 10 | press: () {}, 11 | ), 12 | SocalIcon( 13 | iconSrc: "assets/icons/twitter.svg", 14 | press: () {}, 15 | ), 16 | SocalIcon( 17 | iconSrc: "assets/icons/google-plus.svg", 18 | press: () {}, 19 | ), 20 | ], 21 | ) 22 | 23 | 24 | 25 | class SocalIcon extends StatelessWidget { 26 | final String iconSrc; 27 | final Function press; 28 | const SocalIcon({ 29 | Key? key, 30 | required this.iconSrc, 31 | required this.press, 32 | }) : super(key: key); 33 | 34 | @override 35 | Widget build(BuildContext context) { 36 | return GestureDetector( 37 | onTap: (){}, 38 | child: Container( 39 | margin: EdgeInsets.symmetric(horizontal: 10), 40 | padding: EdgeInsets.all(12), 41 | decoration: BoxDecoration( 42 | border: Border.all( 43 | width: 2, 44 | color: pPrimaryColor, 45 | ), 46 | shape: BoxShape.circle, 47 | ), 48 | child: SvgPicture.asset( 49 | iconSrc, 50 | color: Theme.of(context).textTheme.bodyText1!.color, 51 | height: 25, 52 | width: 25, 53 | ), 54 | ), 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /find # tag in a string.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | String strWithNum = """ 3 | Hubble is hiring! 4 | 5 | Hubble is looking for a Community Manager to join their talented team. 6 | 7 | 💻 Community Manager 8 | 🌍 Remote 9 | 🕒 Contract, Full-Time, Part-Time 10 | 11 | Apply now 👇cryptocurrencyjobs.co/customer-suppo... #blockchainjobs #cryptojobs 12 | """; 13 | List a = strWithNum.split(' '); 14 | for(var x in a){ 15 | if(x[0].startsWith(RegExp(r'#'))){ 16 | print(x); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /firebaseAuth.dart: -------------------------------------------------------------------------------- 1 | //here will be the code snippets of firebase auth 2 | import 'package:book_store/Screens/Home/mainPage.dart'; 3 | import 'package:book_store/Screens/Registration/login.dart'; 4 | import 'package:book_store/Screens/Registration/verifyEmail.dart'; 5 | import 'package:firebase_auth/firebase_auth.dart'; 6 | import 'package:flutter/material.dart'; 7 | import 'package:flutter/widgets.dart'; 8 | import 'package:flutter_secure_storage/flutter_secure_storage.dart'; 9 | import 'package:google_sign_in/google_sign_in.dart'; 10 | 11 | class AuthClass { 12 | final FirebaseAuth _auth = FirebaseAuth.instance; 13 | final GoogleSignIn _googleSignIn = GoogleSignIn(); 14 | 15 | final storage = new FlutterSecureStorage(); 16 | 17 | //Sign in with email 18 | Future? signInWithEmail( 19 | {required String email, 20 | required String password, 21 | required BuildContext context}) async { 22 | try { 23 | UserCredential userCredential = await FirebaseAuth.instance 24 | .signInWithEmailAndPassword(email: email, password: password); 25 | User? user = _auth.currentUser; 26 | if (user != null && !user.emailVerified) { 27 | showSnackBar(context, 'Email was not verified'); 28 | await user.sendEmailVerification(); 29 | 30 | Navigator.pushNamed(context, VerifyEmail.routeName, 31 | arguments: VerifyEmailArguments(email)); 32 | } else { 33 | Navigator.pushNamedAndRemoveUntil( 34 | context, MainPage.routeName, (route) => false); 35 | } 36 | } on FirebaseAuthException catch (e) { 37 | if (e.code == 'user-not-found') { 38 | showSnackBar(context, 'No user found for that email.'); 39 | } else if (e.code == 'wrong-password') { 40 | showSnackBar(context, 'Wrong password provided for that user.'); 41 | } 42 | } catch (e) { 43 | showSnackBar(context, e.toString()); 44 | } 45 | } 46 | 47 | //Sign up with Email 48 | Future? signUpWithEmail( 49 | {required String email, 50 | required String password, 51 | required String confirmPassword, 52 | required BuildContext context}) async { 53 | if (password == confirmPassword) { 54 | try { 55 | UserCredential userCredential = await _auth 56 | .createUserWithEmailAndPassword(email: email, password: password); 57 | print(userCredential.user!.uid); 58 | User? user = _auth.currentUser; 59 | var uid = _auth.currentUser!.uid; 60 | 61 | if (user != null && !user.emailVerified) { 62 | await user.sendEmailVerification(); 63 | } 64 | 65 | // storeTokenAndData(userCredential); 66 | 67 | Navigator.pushNamed(context, VerifyEmail.routeName, 68 | arguments: VerifyEmailArguments(email)); 69 | } on FirebaseAuthException catch (e) { 70 | if (e.code == 'weak-password') { 71 | showSnackBar(context, 'Password should atleast be of 6 characters'); 72 | } else if (e.code == 'email-already-in-use') { 73 | User? user = _auth.currentUser; 74 | if (user != null && !user.emailVerified) { 75 | showSnackBar(context, 76 | 'This email is already taken please login, (Email verification required)'); 77 | } else { 78 | showSnackBar(context, 'This email is already taken'); 79 | } 80 | } 81 | } catch (e) { 82 | showSnackBar(context, e.toString()); 83 | } 84 | } else { 85 | showSnackBar(context, "Passwords didn't matched"); 86 | } 87 | } 88 | 89 | // Reset Password 90 | Future resetPassword( 91 | {required String email, required BuildContext context}) async { 92 | try { 93 | await _auth.sendPasswordResetEmail( 94 | email: email, 95 | ); 96 | showModalSheet(context, 97 | 'A password reset link has been sent to your mail. Please reset your password there and login back again'); 98 | } on FirebaseAuthException catch (e) { 99 | if (e.code == 'invalid-email') { 100 | showSnackBar(context, 'Invalid email address'); 101 | } else if (e.code == 'user-not-found') { 102 | showSnackBar(context, 'No user found with this email address'); 103 | } 104 | } 105 | } 106 | 107 | //Google sign In 108 | Future googleSignIn(BuildContext context) async { 109 | try { 110 | GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn(); 111 | GoogleSignInAuthentication googleSignInAuthentication = 112 | await googleSignInAccount!.authentication; 113 | AuthCredential credential = GoogleAuthProvider.credential( 114 | accessToken: googleSignInAuthentication.accessToken, 115 | idToken: googleSignInAuthentication.idToken, 116 | ); 117 | UserCredential userCredential = 118 | await _auth.signInWithCredential(credential); 119 | storeTokenAndData(userCredential); 120 | Navigator.pushNamedAndRemoveUntil( 121 | context, MainPage.routeName, (route) => false); 122 | } catch (e) { 123 | showSnackBar(context, e.toString()); 124 | } 125 | } 126 | 127 | Future googleSignIn1(BuildContext context) async { 128 | try { 129 | final GoogleSignInAccount? googleSignInAccount = 130 | await _googleSignIn.signIn(); 131 | final GoogleSignInAuthentication googleSignInAuthentication = 132 | await googleSignInAccount!.authentication; 133 | final AuthCredential credential = GoogleAuthProvider.credential( 134 | accessToken: googleSignInAuthentication.accessToken, 135 | idToken: googleSignInAuthentication.idToken, 136 | ); 137 | await _auth.signInWithCredential(credential); 138 | Navigator.pushNamedAndRemoveUntil( 139 | context, MainPage.routeName, (route) => false); 140 | } on FirebaseAuthException catch (e) { 141 | showSnackBar(context, e.toString()); 142 | print(e.message); 143 | throw e; 144 | } 145 | } 146 | 147 | //Sign Out 148 | Future signOut({required BuildContext context}) async { 149 | try { 150 | await _googleSignIn.signOut(); 151 | await _auth.signOut(); 152 | await storage.delete(key: "token"); 153 | Navigator.pushNamedAndRemoveUntil( 154 | context, LoginScreen.routeName, (route) => false); 155 | } catch (e) { 156 | showSnackBar(context, e.toString()); 157 | } 158 | } 159 | 160 | void storeTokenAndData(UserCredential userCredential) async { 161 | print("storing token and data"); 162 | await storage.write( 163 | key: "token", value: userCredential.credential!.token.toString()); 164 | await storage.write( 165 | key: "usercredential", value: userCredential.toString()); 166 | } 167 | 168 | Future getToken() async { 169 | return await storage.read(key: "token"); 170 | } 171 | 172 | void showSnackBar(BuildContext context, String text) { 173 | final snackBar = SnackBar(content: Text(text)); 174 | ScaffoldMessenger.of(context).showSnackBar(snackBar); 175 | } 176 | } 177 | 178 | void showModalSheet(BuildContext context, String text) { 179 | showModalBottomSheet( 180 | context: context, 181 | builder: (BuildContext context) { 182 | return Container( 183 | height: 200, 184 | color: Colors.white, 185 | child: Padding( 186 | padding: const EdgeInsets.symmetric(horizontal: 20), 187 | child: Column( 188 | mainAxisAlignment: MainAxisAlignment.center, 189 | children: [ 190 | Text( 191 | text, 192 | style: TextStyle(fontSize: 16, color: Colors.black), 193 | ), 194 | SizedBox( 195 | height: 20, 196 | ), 197 | ElevatedButton( 198 | child: const Text('Ok'), 199 | onPressed: () => Navigator.pop(context), 200 | ) 201 | ], 202 | ), 203 | ), 204 | ); 205 | }, 206 | ); 207 | } 208 | -------------------------------------------------------------------------------- /flex.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | import 'package:flutter/material.dart'; 5 | 6 | void main() { 7 | runApp( 8 | MaterialApp( 9 | home: Scaffold( 10 | appBar: AppBar( 11 | title: Text('Responsive app '), 12 | backgroundColor: Colors.greenAccent[400], 13 | leading: IconButton( 14 | icon: Icon(Icons.menu), 15 | onPressed: () {}, 16 | tooltip: 'Menu', 17 | ) //IconButton 18 | ), //AppBar 19 | body: Center( 20 | child: Container( 21 | child: Padding( 22 | padding: const EdgeInsets.all(14.0), 23 | child: Column( 24 | children: [ 25 | Row( 26 | children: [ 27 | Flexible( 28 | flex: 1, 29 | fit: FlexFit.tight, 30 | child: Container( 31 | height: 175, 32 | decoration: BoxDecoration( 33 | borderRadius: BorderRadius.circular(10), 34 | color: Colors.red, 35 | ), //BoxDecoration 36 | ), //Container 37 | ), //Flexible 38 | SizedBox( 39 | width: 20, 40 | ), //SizedBox 41 | Flexible( 42 | flex: 1, 43 | fit: FlexFit.loose, 44 | child: Container( 45 | height: 175, 46 | decoration: BoxDecoration( 47 | borderRadius: BorderRadius.circular(10), 48 | color: Colors.red, 49 | ) //BoxDecoration 50 | ), //Container 51 | ) //Flexible 52 | ], //[] 53 | mainAxisAlignment: MainAxisAlignment.center, 54 | ), //Row 55 | Flexible( 56 | flex: 1, 57 | fit: FlexFit.loose, 58 | child: Container( 59 | width: 380, 60 | height: 200, 61 | decoration: BoxDecoration( 62 | borderRadius: BorderRadius.circular(10), 63 | color: Colors.blue), //BoxDecoration 64 | ), //Container 65 | ), //Flexible 66 | Row( 67 | children: [ 68 | Flexible( 69 | flex: 2, 70 | fit: FlexFit.tight, 71 | child: Container( 72 | width: 180, 73 | height: 300, 74 | decoration: BoxDecoration( 75 | borderRadius: BorderRadius.circular(10), 76 | color: Colors.cyan, 77 | ), //BoxDecoration 78 | ), //Container 79 | ), //Flexible 80 | SizedBox( 81 | width: 20, 82 | ), //SixedBox 83 | Flexible( 84 | flex: 2, 85 | fit: FlexFit.tight, 86 | child: Container( 87 | width: 180, 88 | height: 300, 89 | decoration: BoxDecoration( 90 | borderRadius: BorderRadius.circular(10), 91 | color: Colors.cyan, 92 | ) //BoxDecoration 93 | ) //Conatiner, 94 | ) //Flexible 95 | ], //[] 96 | mainAxisAlignment: MainAxisAlignment.center, 97 | ), //Row 98 | ], //[] 99 | mainAxisAlignment: MainAxisAlignment.spaceBetween, 100 | crossAxisAlignment: CrossAxisAlignment.center, 101 | ), //Column 102 | ) //Padding 103 | ), //Container 104 | ) //Center 105 | ), //Scaffold 106 | debugShowCheckedModeBanner: false, 107 | )); //MaterialApp 108 | } 109 | 110 | -------------------------------------------------------------------------------- /gesturedetector.dart: -------------------------------------------------------------------------------- 1 | //Gesture Detector - 2 | GestureDetector( 3 | 4 | onTap: () { 5 | Navigator.push(context, 6 | MaterialPageRoute(builder: (context) => Profile())); 7 | }, 8 | child: CircleAvatar( 9 | backgroundImage: AssetImage('assets/deepa.jpg')) 10 | ), 11 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Deepa Pandey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /listTile.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | Expanded( 4 | child: ListView( 5 | children: [ 6 | Card( 7 | elevation: 0, 8 | child: ListTile( 9 | leading: Icon(Icons.person,color: pPrimaryColor,), 10 | title: Text('Name'), 11 | subtitle: Text( 12 | 'Deepa Pandey ' 13 | ), 14 | trailing: Icon(Icons.edit), 15 | ), 16 | ), 17 | Divider( 18 | color: Colors.grey[300], 19 | thickness: 1, 20 | indent: 65, 21 | endIndent: 5, 22 | ), 23 | Card( 24 | elevation: 0, 25 | child: ListTile( 26 | leading: Icon(Icons.person,color: pPrimaryColor,), 27 | title: Text('About'), 28 | subtitle: Text( 29 | 'habituated🤕wid coding👨‍💻 & covid🦠 ' 30 | ), 31 | trailing: Icon(Icons.edit), 32 | isThreeLine: true, 33 | ), 34 | ), 35 | Divider( 36 | color: Colors.grey[300], 37 | thickness: 1, 38 | indent: 65, 39 | endIndent: 5, 40 | ), 41 | Card( 42 | elevation: 0, 43 | child: ListTile( 44 | leading: Icon(Icons.phone,color: pPrimaryColor,), 45 | title: Text('Phone'), 46 | subtitle: Text( 47 | '+91 12345 67890 ' 48 | ), 49 | trailing: Icon(Icons.edit), 50 | //isThreeLine: true, 51 | ), 52 | ), 53 | ], 54 | ), 55 | ) 56 | -------------------------------------------------------------------------------- /listview.dart: -------------------------------------------------------------------------------- 1 | 2 | // To create a list of items using listview --- 3 | ListView.builder( 4 | itemCount: 20, 5 | itemBuilder: (context, position) { 6 | return Card( 7 | child: Padding( 8 | padding: const EdgeInsets.all(20.0), 9 | child: Text( 10 | 'Your data', 11 | style: TextStyle(fontSize: 22.0), 12 | ), 13 | ), 14 | ); 15 | }, 16 | ), 17 | 18 | -------------------------------------------------------------------------------- /multiple_floating_action_button.dart: -------------------------------------------------------------------------------- 1 | //By using column in floatingActionButton - 2 | 3 | floatingActionButton: Column( 4 | mainAxisAlignment: MainAxisAlignment.end, 5 | children: [ 6 | FloatingActionButton( 7 | onPressed: () {}, 8 | backgroundColor: pPrimaryColor, 9 | child: Icon( 10 | Icons.video_call, 11 | color: Colors.white, 12 | ), 13 | ), 14 | SizedBox(height: 8,), 15 | FloatingActionButton( 16 | onPressed: () {}, 17 | backgroundColor: pPrimaryColor, 18 | child: Icon( 19 | Icons.phone_forwarded, 20 | color: Colors.white, 21 | ), 22 | ), 23 | ], 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------\/\/\/\/\/\/\/\/\/--------------------------------------------------------- 30 | 31 | 32 | 33 | 34 | 35 | // OR You can use the flutter_speed_dial package: https://pub.dartlang.org/packages/flutter_speed_dial 36 | Example using it: 37 | Widget _getFAB() { 38 | return SpeedDial( 39 | animatedIcon: AnimatedIcons.menu_close, 40 | animatedIconTheme: IconThemeData(size: 22), 41 | backgroundColor: Color(0xFF801E48), 42 | visible: true, 43 | curve: Curves.bounceIn, 44 | children: [ 45 | // FAB 1 46 | SpeedDialChild( 47 | child: Icon(Icons.assignment_turned_in), 48 | backgroundColor: Color(0xFF801E48), 49 | onTap: () { /* do anything */ }, 50 | label: 'Button 1', 51 | labelStyle: TextStyle( 52 | fontWeight: FontWeight.w500, 53 | color: Colors.white, 54 | fontSize: 16.0), 55 | labelBackgroundColor: Color(0xFF801E48)), 56 | // FAB 2 57 | SpeedDialChild( 58 | child: Icon(Icons.assignment_turned_in), 59 | backgroundColor: Color(0xFF801E48), 60 | onTap: () { 61 | setState(() { 62 | _counter = 0; 63 | }); 64 | }, 65 | label: 'Button 2', 66 | labelStyle: TextStyle( 67 | fontWeight: FontWeight.w500, 68 | color: Colors.white, 69 | fontSize: 16.0), 70 | labelBackgroundColor: Color(0xFF801E48)) 71 | ], 72 | ); 73 | } 74 | -------------------------------------------------------------------------------- /neumorphism.dart: -------------------------------------------------------------------------------- 1 | //This extension has been made by abuanwar072 2 | // The code has been taken from there 3 | //It helps in creating a 3D effect to the widgets. 4 | 5 | import 'package:flutter/material.dart'; 6 | 7 | extension Neumorphism on Widget { 8 | addNeumorphism({ 9 | double borderRadius = 10.0, 10 | Offset offset = const Offset(5, 5), 11 | double blurRadius = 10, 12 | Color topShadowColor = Colors.white60, 13 | Color bottomShadowColor = const Color(0x26234395), 14 | }) { 15 | return Container( 16 | decoration: BoxDecoration( 17 | borderRadius: BorderRadius.all(Radius.circular(borderRadius)), 18 | boxShadow: [ 19 | BoxShadow( 20 | offset: offset, 21 | blurRadius: blurRadius, 22 | color: bottomShadowColor, 23 | ), 24 | BoxShadow( 25 | offset: Offset(-offset.dx, -offset.dx), 26 | blurRadius: blurRadius, 27 | color: topShadowColor, 28 | ), 29 | ], 30 | ), 31 | child: this, 32 | ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /onGeneratedRoute.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter_bloc_concepts/presentation/screens/home_screen.dart'; 3 | import 'package:flutter_bloc_concepts/presentation/screens/second_screen.dart'; 4 | import 'package:flutter_bloc_concepts/presentation/screens/third_screen.dart'; 5 | import 'package:flutter_bloc/flutter_bloc.dart'; 6 | import 'package:flutter_bloc_concepts/logic/cubit/counter_cubit.dart'; 7 | import 'package:flutter_bloc_concepts/presentation/router/app_router.dart'; 8 | 9 | 10 | 11 | void main() { 12 | runApp(MyApp()); 13 | } 14 | 15 | class MyApp extends StatelessWidget { 16 | final AppRouter _appRouter = AppRouter(); 17 | 18 | @override 19 | Widget build(BuildContext context) { 20 | return BlocProvider( 21 | create: (context) => CounterCubit(), 22 | child: MaterialApp( 23 | title: 'Flutter Demo', 24 | theme: ThemeData( 25 | primarySwatch: Colors.blue, 26 | visualDensity: VisualDensity.adaptivePlatformDensity, 27 | ), 28 | onGenerateRoute: _appRouter.onGenerateRoute, 29 | ), 30 | ); 31 | } 32 | } 33 | 34 | 35 | class AppRouter { 36 | Route onGenerateRoute(RouteSettings settings) { 37 | final GlobalKey key = settings.arguments; 38 | switch (settings.name) { 39 | case '/': 40 | return MaterialPageRoute( 41 | builder: (_) => HomeScreen( 42 | title: "Home Screen", 43 | color: Colors.blueAccent, 44 | ), 45 | ); 46 | case '/second': 47 | return MaterialPageRoute( 48 | builder: (_) => SecondScreen( 49 | title: "Second Screen", 50 | color: Colors.redAccent, 51 | homeScreenKey: key, 52 | ), 53 | ); 54 | case '/third': 55 | return MaterialPageRoute( 56 | builder: (_) => ThirdScreen( 57 | title: "Thirst Screen", 58 | color: Colors.greenAccent, 59 | ), 60 | ); 61 | default: 62 | return null; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /paginatedDataTable.dart: -------------------------------------------------------------------------------- 1 | // Sample Taken From One Of My Code// 2 | import 'package:dash_admin_dashboard/Dashboard/MenuItems/addFeature.dart'; 3 | import 'package:dash_admin_dashboard/Dashboard/MenuItems/components/headingTextWidget.dart'; 4 | import 'package:dash_admin_dashboard/Dashboard/MenuItems/components/tableHeader.dart'; 5 | import 'package:dash_admin_dashboard/Dashboard/MenuItems/drawer.dart'; 6 | import 'package:dash_admin_dashboard/SignUp/Components/appbar.dart'; 7 | import 'package:dash_admin_dashboard/models/AdminModel/adminResponseModel.dart'; 8 | import 'package:dash_admin_dashboard/models/featureModel.dart'; 9 | import 'package:dash_admin_dashboard/service/networkHandler2.dart'; 10 | import 'package:flutter/material.dart'; 11 | 12 | class FeaturesTable extends StatefulWidget { 13 | const FeaturesTable({Key key}) : super(key: key); 14 | 15 | @override 16 | _FeaturesTableState createState() => _FeaturesTableState(); 17 | } 18 | 19 | class _FeaturesTableState extends State { 20 | Map resp; 21 | bool circular = true; 22 | NetworkHandler networkHandler = NetworkHandler(); 23 | FeatureModel featuremodel = FeatureModel(); 24 | AdminResponseModel adminResponse = AdminResponseModel(); 25 | String text; 26 | @override 27 | void initState() { 28 | super.initState(); 29 | fetchData(); 30 | } 31 | 32 | void fetchData() async { 33 | var response = await networkHandler.get('feature?limit=100&page=1'); 34 | setState(() { 35 | featuremodel = FeatureModel.fromJson(response); 36 | circular = false; 37 | }); 38 | } 39 | 40 | @override 41 | Widget build(BuildContext context) { 42 | return Scaffold( 43 | appBar: BuildAppbar( 44 | isloggedIn: true, 45 | ), 46 | body: Container( 47 | height: MediaQuery.of(context).size.height, 48 | width: MediaQuery.of(context).size.width, 49 | child: Row( 50 | children: [ 51 | SingleChildScrollView( 52 | child: Container( 53 | height: MediaQuery.of(context).size.height , 54 | child: BuildDrawer()), 55 | ), 56 | SizedBox(width: 10,), 57 | Expanded( 58 | child: circular 59 | ? Center( 60 | child: CircularProgressIndicator(), 61 | ) 62 | : ListView( 63 | padding: const EdgeInsets.all(16), 64 | children: [ 65 | PaginatedDataTable( 66 | header: TableHeader( 67 | headerText: 'Features Details', 68 | page: AddFeature(), 69 | header: 'Feature'), 70 | rowsPerPage: 10, 71 | columns: [ 72 | DataColumn(label: HeadingTextWidget(text: 'Name')), 73 | DataColumn(label: HeadingTextWidget(text: 'Active')), 74 | DataColumn(label: HeadingTextWidget(text: 'Key')), 75 | DataColumn(label: HeadingTextWidget(text: 'Actions')), 76 | ], 77 | source: _DataSource(context, featuremodel), 78 | ), 79 | ], 80 | ), 81 | ), 82 | ], 83 | ), 84 | ), 85 | ); 86 | } 87 | } 88 | 89 | 90 | class _DataSource extends DataTableSource { 91 | _DataSource(this.context, this.featuremodel); 92 | final BuildContext context; 93 | FeatureModel featuremodel; 94 | @override 95 | DataRow getRow(int index) { 96 | return DataRow.byIndex( 97 | index: index, 98 | cells: [ 99 | DataCell(Text(featuremodel.results[index].name.toString(),)), 100 | DataCell(Text(featuremodel.results[index].active.toString(),)), 101 | DataCell(Text(featuremodel.results[index].key.toString(),)), 102 | DataCell(Row( 103 | children: [ 104 | IconButton(onPressed: () {}, icon: Icon(Icons.edit)), 105 | SizedBox(width: 8,), 106 | IconButton(onPressed: () {}, icon: Icon(Icons.delete)), 107 | ], 108 | )), 109 | ], 110 | ); 111 | } 112 | 113 | @override 114 | int get rowCount => featuremodel.totalResults; 115 | 116 | @override 117 | bool get isRowCountApproximate => false; 118 | 119 | @override 120 | int get selectedRowCount => 0; 121 | } 122 | -------------------------------------------------------------------------------- /password-toggle.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | class LoginForm extends StatefulWidget { 3 | @override 4 | _LoginFormState createState() => _LoginFormState(); 5 | } 6 | class _LoginFormState extends State { 7 | bool _isHidden = true; 8 | @override 9 | Widget build(BuildContext context) { 10 | return Scaffold( 11 | backgroundColor: Theme.of(context).secondaryHeaderColor, 12 | body: Center( 13 | child: TextField( 14 | obscureText: _isHidden, 15 | decoration: InputDecoration( 16 | hintText: 'Password', 17 | suffix: InkWell( 18 | onTap: _togglePasswordView, 19 | child: Icon( 20 | _isHidden 21 | ? Icons.visibility 22 | : Icons.visibility_off, 23 | ), 24 | ), 25 | ), 26 | ), 27 | ), 28 | ); 29 | } 30 | void _togglePasswordView() { 31 | setState(() { 32 | _isHidden = !_isHidden; 33 | }); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /random-color-generator.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | Color generateRandomColor() { 4 | Random random = Random(); 5 | return Color.fromARGB( 6 | 255, random.nextInt(256), random.nextInt(256), random.nextInt(256)); 7 | } 8 | 9 | 10 | //Sample usage ---- 11 | ListView.builder( 12 | itemCount: active.length, 13 | itemBuilder: (BuildContext context, int index) { 14 | return CircleAvatar( 15 | radius: 25, 16 | backgroundColor: generateRandomColor(), 17 | child: Text(active[index].name[0],style:TextStyle(fontSize: 25,fontWeight: FontWeight.bold,color: Colors.white),), 18 | ), 19 | } 20 | ) 21 | -------------------------------------------------------------------------------- /raw-material-button.dart: -------------------------------------------------------------------------------- 1 | 2 | RawMaterialButton( 3 | onPressed: () {}, 4 | elevation: 2.0, 5 | fillColor: Colors.white, 6 | child: Icon( 7 | Icons.chat_rounded, 8 | size: 35.0, 9 | color: pPrimaryColor, 10 | ), 11 | padding: EdgeInsets.all(15.0), 12 | shape: RoundedRectangleBorder( 13 | borderRadius: BorderRadius.circular(120.0), 14 | side: BorderSide( 15 | color: Colors.black, 16 | width: 2 17 | ), 18 | ), 19 | ), 20 | 21 | 22 | ===================================================================================================== 23 | ===================================================================================================== 24 | ===================================================================================================== 25 | 26 | RawMaterialButton( 27 | onPressed: () {}, 28 | elevation: 25.0, 29 | fillColor: Colors.white, 30 | child: Icon( 31 | Icons.facebook_outlined, 32 | size: 50.0, 33 | color: Colors.blue, 34 | ), 35 | padding: EdgeInsets.all(10.0), 36 | shape:CircleBorder(), 37 | ), 38 | ===================================================================================================== 39 | ===================================================================================================== 40 | ===================================================================================================== 41 | MaterialButton( 42 | color: Colors.white, 43 | elevation: 25, 44 | shape: CircleBorder(), 45 | onPressed: () {}, 46 | child: Padding( 47 | padding: const EdgeInsets.all(10), 48 | child: Icon( 49 | Icons.mail, 50 | size: 50.0, 51 | color: Colors.red, 52 | ), 53 | ), 54 | ) 55 | ===================================================================================================== 56 | ===================================================================================================== 57 | ===================================================================================================== 58 | 59 | RawMaterialButton( 60 | onPressed: () {}, 61 | elevation: 2.0, 62 | fillColor: Colors.white, 63 | child: Icon( 64 | Icons.chat_rounded, 65 | size: 35.0, 66 | color: pPrimaryColor, 67 | ), 68 | padding: EdgeInsets.all(15.0), 69 | shape: RoundedRectangleBorder( 70 | borderRadius: BorderRadius.circular(120.0), 71 | side: isDark == true ? BorderSide( 72 | color: Colors.white, 73 | width: 2 74 | ): 75 | BorderSide( 76 | color: Colors.black, 77 | width: 2 78 | ), 79 | ), 80 | ), 81 | -------------------------------------------------------------------------------- /readMe.md: -------------------------------------------------------------------------------- 1 | 2 | # Flutter quick code snippets 3 | 4 | 5 | * Please do not forget to **star the repo** if you liked it! And please, follow me on >>>

flutter_girlz_

6 | *** 7 | 8 | > #### Points to be noted 9 | > 10 | > - Here you can add your own quick flutter code snippets which can be referred while coding 11 | > - Please make a PR so that I can add them here too 12 | > - Also, credits to some stackoverflow answers whose code snippet has been used directly. 13 | > 14 | > The codes snippets given are taken from my own projects on basis of their usage, you can customize it to fulfill your requirements. 15 | > 16 | 17 | *** 18 | 19 | ### Code snippets covered till now - 20 |
    21 |
  1. Api calls
  2. 22 |
  3. Animations in flutter
  4. 23 |
  5. Adding SVG icons
  6. 24 |
  7. Appbar Tricks
  8. 25 |
  9. Bottom Nav-bar
  10. 26 |
  11. 3D Seach Bar
  12. 27 |
  13. Stacked images
  14. 28 |
  15. Color codes & multiple color theme in apps
  16. 29 |
  17. Dark Mode
  18. 30 |
  19. Custom Drawer with navigation & tilecolor
  20. 31 |
  21. Random Color generator
  22. 32 |
  23. Stepper - an incement decement counter
  24. 33 |
  25. Password toggler
  26. 34 |
  27. Buttons 35 |
      36 |
    1. Raw Material button
    2. 37 |
    3. Elevated button
    4. 38 |
    39 |
  28. 40 |
  29. App Theme
  30. 41 |
  31. Search functionality using search delegate
  32. 42 |
  33. Text Fields
  34. 43 |
  35. Rich Text
  36. 44 |
  37. List Tile
  38. 45 |
  39. Tabbar + Tabbar in center of page
  40. 46 |
  41. Divider
  42. 47 |
  43. TextStyles
  44. 48 |
  45. Multiple Floating Action Button
  46. 49 |
  47. Social Login UI (Login with fb/google/twitter/etc.)
  48. 50 |
  49. GridView + Example for FB Story like Grid
  50. 51 |
  51. Neuromorphic - Create 3D effect of your widgets
  52. 52 |
  53. On Generated Routes [PR by Lokesh Jangid]
  54. 53 |
  55. Card Styles [PR by Lokesh Jangid]
  56. 54 |
  57. Paginated Data Table
  58. 55 |
  59. Cut Out Effect Styles [PR by Lokesh Jangid]
  60. 56 |
  61. Draggable Scrollable Sheet
  62. 57 |
  63. Firebase Authentication
  64. 58 |
  65. ClipRect
  66. 59 |
  67. Refresh Indicator flutter
  68. 60 |
61 | 62 | *** 63 | 64 | -------------------------------------------------------------------------------- /refresh_indicator.dart: -------------------------------------------------------------------------------- 1 | //Flutter Custom Refresh Indicator 2 | // This package provides CustomRefreshIndicator widget that make it easy to implement your own custom refresh indicator. 3 | //It listens for scroll events from scroll widget passed to child argument and parsing it to data easy for custom refresh indicator implementation. 4 | //Indicator data is provided by IndicatorController (third argument of builder method). Long story short... thats it! 5 | 6 | 7 | import 'package:example/screens/presentation_screen.dart'; 8 | import 'package:flutter/material.dart'; 9 | 10 | import 'indicators/simple_indicator.dart'; 11 | import 'screens/example_indicator_screen.dart'; 12 | import 'screens/ice_cream_indicator_screen.dart'; 13 | import 'screens/plane_indicator_screen.dart'; 14 | import 'screens/check_mark_indicator_screen.dart'; 15 | import 'screens/warp_indicator_screen.dart'; 16 | 17 | void main() => runApp(MyApp()); 18 | 19 | class MyApp extends StatelessWidget { 20 | @override 21 | Widget build(BuildContext context) { 22 | return MaterialApp( 23 | title: 'CustomRefreshIndicator demo', 24 | theme: ThemeData( 25 | primarySwatch: Colors.blue, 26 | ), 27 | home: MainScreen(), 28 | routes: { 29 | '/example': (context) => ExampleIndicatorScreen(), 30 | '/plane': (context) => PlaneIndicatorScreen(), 31 | '/ice_cream': (context) => IceCreamIndicatorScreen(), 32 | '/presentation': (context) => PresentationScreen(), 33 | '/check-mark': (context) => CheckMarkIndicatorScreen(), 34 | '/warp': (context) => WarpIndicatorScreen(), 35 | }, 36 | ); 37 | } 38 | } 39 | 40 | class MainScreen extends StatelessWidget { 41 | @override 42 | Widget build(BuildContext context) { 43 | return Scaffold( 44 | appBar: AppBar( 45 | title: Text("Examples"), 46 | ), 47 | body: SafeArea( 48 | child: ListView( 49 | padding: const EdgeInsets.all(15), 50 | children: [ 51 | ElevatedButton( 52 | child: Container( 53 | height: 50, 54 | alignment: Alignment.center, 55 | child: Text("Presentation"), 56 | ), 57 | onPressed: () => Navigator.pushNamed( 58 | context, 59 | '/presentation', 60 | ), 61 | ), 62 | const SizedBox(height: 15), 63 | ElevatedButton( 64 | child: Container( 65 | height: 50, 66 | alignment: Alignment.center, 67 | child: Text("Simple"), 68 | ), 69 | onPressed: () => Navigator.pushNamed( 70 | context, 71 | '/example', 72 | arguments: simpleIndicator, 73 | ), 74 | ), 75 | const SizedBox(height: 15), 76 | ElevatedButton( 77 | child: Container( 78 | height: 50, 79 | alignment: Alignment.center, 80 | child: Text("Simple with list opacity"), 81 | ), 82 | onPressed: () => Navigator.pushNamed( 83 | context, 84 | '/example', 85 | arguments: simpleIndicatorWithOpacity, 86 | ), 87 | ), 88 | const SizedBox(height: 15), 89 | ElevatedButton( 90 | child: Container( 91 | height: 50, 92 | alignment: Alignment.center, 93 | child: Text("Plane"), 94 | ), 95 | onPressed: () => Navigator.pushNamed( 96 | context, 97 | '/plane', 98 | ), 99 | ), 100 | const SizedBox(height: 15), 101 | ElevatedButton( 102 | child: Container( 103 | height: 50, 104 | alignment: Alignment.center, 105 | child: Text("Ice cream"), 106 | ), 107 | onPressed: () => Navigator.pushNamed( 108 | context, 109 | '/ice_cream', 110 | ), 111 | ), 112 | const SizedBox(height: 15), 113 | ElevatedButton( 114 | child: Container( 115 | height: 50, 116 | alignment: Alignment.center, 117 | child: Text("Check mark"), 118 | ), 119 | onPressed: () => Navigator.pushNamed( 120 | context, 121 | '/check-mark', 122 | ), 123 | ), 124 | const SizedBox(height: 15), 125 | ElevatedButton( 126 | child: Container( 127 | height: 50, 128 | alignment: Alignment.center, 129 | child: Text("Warp indicator"), 130 | ), 131 | onPressed: () => Navigator.pushNamed( 132 | context, 133 | '/warp', 134 | arguments: simpleIndicator, 135 | ), 136 | ), 137 | ], 138 | ), 139 | ), 140 | ); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /responsive.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | class Responsive extends StatelessWidget { 4 | final Widget mobile; 5 | final Widget tablet; 6 | final Widget desktop; 7 | 8 | 9 | const Responsive({ 10 | Key key, 11 | @required this.mobile, 12 | @required this.tablet, 13 | @required this.desktop, 14 | }) : super(key: key); 15 | 16 | // This size work fine on my design, maybe you need some customization depends on your design 17 | 18 | // This isMobile, isTablet, isDesktop helep us later 19 | static bool isMobile(BuildContext context) => 20 | MediaQuery.of(context).size.width < 650; 21 | 22 | static bool isTablet(BuildContext context) => 23 | MediaQuery.of(context).size.width < 1100 && 24 | MediaQuery.of(context).size.width >= 650; 25 | 26 | static bool isDesktop(BuildContext context) => 27 | MediaQuery.of(context).size.width >= 1100; 28 | 29 | @override 30 | Widget build(BuildContext context) { 31 | return LayoutBuilder( 32 | // If our width is more than 1100 then we consider it a desktop 33 | builder: (context, constraints) { 34 | if (constraints.maxWidth >= 1100) { 35 | return desktop; 36 | } 37 | // If width it less then 1100 and more then 650 we consider it as tablet 38 | else if (constraints.maxWidth >= 650) { 39 | return tablet; 40 | } 41 | // Or less then that we called it mobile 42 | else { 43 | return mobile; 44 | } 45 | }, 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /responsivenessCheck.dart: -------------------------------------------------------------------------------- 1 | Add this dependency-->> 2 | device_preview: ^0.7.4 3 | 4 | import 'dart:io'; 5 | import 'package:device_preview/device_preview.dart'; 6 | import 'package:device_preview/plugins.dart'; 7 | import 'package:flutter/cupertino.dart'; 8 | import 'package:flutter/foundation.dart'; 9 | import 'package:flutter/material.dart'; 10 | import 'package:path_provider/path_provider.dart'; 11 | import 'package:path/path.dart' as path; 12 | 13 | import 'basic.dart'; 14 | 15 | void main() { 16 | debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; 17 | 18 | WidgetsFlutterBinding.ensureInitialized(); 19 | 20 | _createFakeData(); 21 | 22 | runApp(Row( 23 | textDirection: TextDirection.ltr, 24 | crossAxisAlignment: CrossAxisAlignment.stretch, 25 | children: [ 26 | /*Expanded( 27 | child: Container(color: Colors.red), 28 | ),*/ 29 | Expanded( 30 | child: DevicePreview( 31 | enabled: true, 32 | plugins: [ 33 | const ScreenshotPlugin(), 34 | const FileExplorerPlugin(), 35 | const SharedPreferencesExplorerPlugin(), 36 | ], 37 | builder: (context) => BasicApp(), 38 | ), 39 | ), 40 | ], 41 | )); 42 | } 43 | 44 | Future _createFakeData() async { 45 | final directory = (await getApplicationDocumentsDirectory()).path; 46 | 47 | final file1 = File(path.join(directory, 'example.json')); 48 | await file1.writeAsString('{ "example": true}'); 49 | 50 | final directoryWithFile = Directory(path.join(directory, 'subdir')); 51 | await directoryWithFile.create(); 52 | 53 | final emptyDirectory = Directory(path.join(directory, 'emptyDir')); 54 | await emptyDirectory.create(); 55 | 56 | final file2 = File(path.join(directoryWithFile.path, 'example2.json')); 57 | await file2.writeAsString('{ "example2": true}'); 58 | 59 | final file3 = File(path.join(directoryWithFile.path, 'example2.bin')); 60 | await file3.writeAsString('kjh8bhb'); 61 | } 62 | -------------------------------------------------------------------------------- /returnDataFromAScreen.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | void main() { 4 | runApp( 5 | MaterialApp( 6 | title: 'Returning Data', 7 | home: HomeScreen(), 8 | ), 9 | ); 10 | } 11 | 12 | class HomeScreen extends StatelessWidget { 13 | @override 14 | Widget build(BuildContext context) { 15 | return Scaffold( 16 | appBar: AppBar( 17 | title: Text('Returning Data Demo'), 18 | ), 19 | body: Center(child: SelectionButton()), 20 | ); 21 | } 22 | } 23 | 24 | class SelectionButton extends StatelessWidget { 25 | @override 26 | Widget build(BuildContext context) { 27 | return ElevatedButton( 28 | onPressed: () { 29 | _navigateAndDisplaySelection(context); 30 | }, 31 | child: Text('Pick an option, any option!'), 32 | ); 33 | } 34 | 35 | // A method that launches the SelectionScreen and awaits the result from 36 | // Navigator.pop. 37 | void _navigateAndDisplaySelection(BuildContext context) async { 38 | // Navigator.push returns a Future that completes after calling 39 | // Navigator.pop on the Selection Screen. 40 | final result = await Navigator.push( 41 | context, 42 | MaterialPageRoute(builder: (context) => SelectionScreen()), 43 | ); 44 | 45 | // After the Selection Screen returns a result, hide any previous snackbars 46 | // and show the new result. 47 | ScaffoldMessenger.of(context) 48 | ..removeCurrentSnackBar() 49 | ..showSnackBar(SnackBar(content: Text('$result'))); 50 | } 51 | } 52 | 53 | class SelectionScreen extends StatelessWidget { 54 | @override 55 | Widget build(BuildContext context) { 56 | return Scaffold( 57 | appBar: AppBar( 58 | title: Text('Pick an option'), 59 | ), 60 | body: Center( 61 | child: Column( 62 | mainAxisAlignment: MainAxisAlignment.center, 63 | children: [ 64 | Padding( 65 | padding: const EdgeInsets.all(8.0), 66 | child: ElevatedButton( 67 | onPressed: () { 68 | // Close the screen and return "Yep!" as the result. 69 | Navigator.pop(context, 'Yep!'); 70 | }, 71 | child: Text('Yep!'), 72 | ), 73 | ), 74 | Padding( 75 | padding: const EdgeInsets.all(8.0), 76 | child: ElevatedButton( 77 | onPressed: () { 78 | // Close the screen and return "Nope." as the result. 79 | Navigator.pop(context, 'Nope.'); 80 | }, 81 | child: Text('Nope.'), 82 | ), 83 | ) 84 | ], 85 | ), 86 | ), 87 | ); 88 | } 89 | } 90 | 91 | 92 | -------------------------------------------------------------------------------- /richText.dart: -------------------------------------------------------------------------------- 1 | // Rich Text is used when we want to edit some parts of the text and not to others 2 | 3 | RichText( 4 | text: TextSpan( 5 | text: 6 | 'Follow flutter_girlz❤️\n TCS\'er 😜 🤪 🤨\nFlutter Developer💛 ', 7 | style: TextStyle( 8 | color: Theme.of(context).textTheme.bodyText1.color), 9 | children: [ 10 | TextSpan( 11 | text: '...more\n', 12 | style: TextStyle( 13 | color: Colors.grey[500], 14 | ), 15 | ), 16 | TextSpan( 17 | text: 'deepapandey.herokuapp.com/', 18 | style: TextStyle(color: Colors.blue[400])), 19 | ], 20 | ), 21 | ), 22 | -------------------------------------------------------------------------------- /search-delegate.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | //Implementing search functionality using search delegate in flutter. 4 | class TextBox extends StatelessWidget { 5 | @override 6 | Widget build(BuildContext context) { 7 | return Container( 8 | child: TextField( 9 | cursorHeight: 20, 10 | decoration: InputDecoration( 11 | hintText: 'Search in mail', 12 | border: InputBorder.none, 13 | ), 14 | onTap: () { 15 | showSearch(context: context, delegate: Datasearch()); 16 | }, 17 | ), 18 | ); 19 | } 20 | } 21 | class Datasearch extends SearchDelegate { 22 | final names = [ 23 | 'deepa', 24 | 'deepak', 25 | 'sugarcosmetics', 26 | 'balram', 27 | 'linkedln', 28 | 'banglore', 29 | 'balram0698@gmail.com', 30 | 'pandey.deepa@tcs.com', 31 | 'sugarcosmetics@gmail.com', 32 | 'pandeydeepak821@gmail.com', 33 | 'balram.rathore@tcs.com', 34 | ]; 35 | final recentSearches = [ 36 | 'pandey.deepa@tcs.com', 37 | 'sugarcosmetics@gmail.com', 38 | 'pandeydeepak821@gmail.com', 39 | 'balram0698@gmail.com' 40 | ]; 41 | @override 42 | List buildActions(BuildContext context) { 43 | return [ 44 | 45 | IconButton( 46 | icon: Icon(Icons.mic), 47 | onPressed: () {}, 48 | ) 49 | ]; 50 | } 51 | 52 | @override 53 | Widget buildLeading(BuildContext context) { 54 | return IconButton( 55 | icon: AnimatedIcon( 56 | icon: AnimatedIcons.menu_arrow, 57 | progress: transitionAnimation, 58 | ), 59 | onPressed: () { 60 | close(context, null); 61 | }, 62 | ); 63 | } 64 | 65 | @override 66 | Widget buildResults(BuildContext context) { 67 | throw UnimplementedError(); 68 | } 69 | 70 | @override 71 | Widget buildSuggestions(BuildContext context) { 72 | final suggestionList = query.isEmpty 73 | ? recentSearches 74 | : names.where((element) => element.startsWith(query)).toList(); 75 | return ListView.builder( 76 | itemBuilder: (context, index) => ListTile( 77 | leading: Icon(Icons.person_search), 78 | title: RichText( 79 | text: TextSpan( 80 | text: suggestionList[index].substring(0, query.length), 81 | style: 82 | TextStyle(color: Colors.black, fontWeight: FontWeight.bold), 83 | children: [ 84 | TextSpan( 85 | text: suggestionList[index].substring(query.length), 86 | style: TextStyle(color: Colors.grey)) 87 | ])), 88 | ), 89 | itemCount: suggestionList.length, 90 | ); 91 | } 92 | } 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /search_bar_3d.dart: -------------------------------------------------------------------------------- 1 | Center searchBox(Size size) { 2 | return Center( 3 | child: Card( 4 | elevation: 15, 5 | shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), 6 | child: Container( 7 | width: size.width*0.85, 8 | height: 50, 9 | child: TextFormField( 10 | cursorHeight: 25, 11 | 12 | decoration: InputDecoration( 13 | labelText: "Search by book name", 14 | labelStyle: TextStyle(color: kTextColor.withOpacity(0.9)), 15 | border: InputBorder.none, 16 | floatingLabelBehavior: FloatingLabelBehavior.never, 17 | contentPadding: EdgeInsets.only(bottom: 20), 18 | prefixIcon: IconButton( 19 | icon: Icon(Icons.search), 20 | color: Colors.grey, 21 | onPressed: () {}, 22 | ), 23 | suffixIcon: IconButton( 24 | icon: Icon(Icons.sort_sharp), 25 | onPressed: () {}, 26 | ), 27 | ), 28 | ) 29 | ) 30 | ), 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /slider.dart: -------------------------------------------------------------------------------- 1 | class MyApp extends StatelessWidget { 2 | const MyApp({Key? key}) : super(key: key); 3 | 4 | static const String _title = 'Flutter Code Sample'; 5 | 6 | @override 7 | Widget build(BuildContext context) { 8 | return MaterialApp( 9 | title: _title, 10 | home: Scaffold( 11 | appBar: AppBar(title: const Text(_title)), 12 | body: const MyStatefulWidget(), 13 | ), 14 | ); 15 | } 16 | } 17 | 18 | /// This is the stateful widget that the main application instantiates. 19 | class MyStatefulWidget extends StatefulWidget { 20 | const MyStatefulWidget({Key? key}) : super(key: key); 21 | 22 | @override 23 | State createState() => _MyStatefulWidgetState(); 24 | } 25 | 26 | /// This is the private State class that goes with MyStatefulWidget. 27 | class _MyStatefulWidgetState extends State { 28 | double _currentSliderValue = 20; 29 | 30 | @override 31 | Widget build(BuildContext context) { 32 | return Slider( 33 | value: _currentSliderValue, 34 | min: 0, 35 | max: 100, 36 | divisions: 5, 37 | label: _currentSliderValue.round().toString(), 38 | onChanged: (double value) { 39 | setState(() { 40 | _currentSliderValue = value; 41 | }); 42 | }, 43 | ); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /stepper.dart: -------------------------------------------------------------------------------- 1 | 2 | // Post has been taken from Ranga Reddy- https://dev.to/irangareddy/custom-stepper-in-flutter-40o8 3 | //this is stepper.dart 4 | What is a Stepper? 5 | A stepper is a two-buttons used to increase or decrease an incremental value. 6 | By default, one button of a stepper displays a plus symbol, and the other displays a minus symbol. 7 | These symbols can be replaced with custom images if desired. 8 | 9 | class StepperScreen extends StatelessWidget { 10 | @override 11 | Widget build(BuildContext context) { 12 | return Scaffold( 13 | appBar: AppBar( 14 | backgroundColor: kPrimaryColor, 15 | title: Text("Custom Stepper"), 16 | centerTitle: false, 17 | ), 18 | body: SafeArea( 19 | child: Center( 20 | child: Container( 21 | height: 300, 22 | width: 200, 23 | decoration: BoxDecoration( 24 | color: Colors.white, 25 | borderRadius: BorderRadius.circular(8.0), 26 | boxShadow: [ 27 | BoxShadow( 28 | color: kShadowColor, 29 | offset: Offset(0, 20), 30 | blurRadius: 30.0), 31 | ] 32 | ), 33 | child: Column( 34 | mainAxisAlignment: MainAxisAlignment.center, 35 | crossAxisAlignment: CrossAxisAlignment.start, 36 | children: [ 37 | Padding( 38 | padding: const EdgeInsets.all(8.0), 39 | child: Container( 40 | decoration: BoxDecoration( 41 | color: Colors.black.withOpacity(0.04), 42 | borderRadius: BorderRadius.circular(8.0), 43 | ), 44 | child: Padding( 45 | padding: const EdgeInsets.all(8.0), 46 | child: Image.asset('assets/images/fruit.png',fit: BoxFit.fitWidth,), 47 | ), 48 | ), 49 | ), 50 | Padding( 51 | padding: const EdgeInsets.only(top: 8.0,left: 8.0), 52 | child: Text('Juicy Strawberry',style: TextStyle( 53 | color: Colors.black, 54 | fontSize: 18.0, 55 | ),), 56 | ), 57 | Padding( 58 | padding: const EdgeInsets.only(top: 8.0,left: 8.0), 59 | child: Row( 60 | children: [ 61 | Text('\$20.40',style: TextStyle( 62 | color: Colors.black, 63 | fontSize: 15.0, 64 | fontWeight: FontWeight.bold, 65 | ),), 66 | Spacer(), 67 | CustomStepper() 68 | ], 69 | ), 70 | ), 71 | 72 | ], 73 | ), 74 | )), 75 | ), 76 | ); 77 | } 78 | } 79 | 80 | 81 | 82 | class CustomStepper extends StatefulWidget { 83 | CustomStepper({ 84 | @required this.lowerLimit, 85 | @required this.upperLimit, 86 | @required this.stepValue, 87 | @required this.iconSize, 88 | @required this.value, 89 | }); 90 | 91 | final int lowerLimit; 92 | final int upperLimit; 93 | final int stepValue; 94 | final double iconSize; 95 | int value; 96 | 97 | @override 98 | _CustomStepperState createState() => _CustomStepperState(); 99 | } 100 | 101 | class _CustomStepperState extends State { 102 | 103 | @override 104 | Widget build(BuildContext context) { 105 | return Row( 106 | mainAxisAlignment: MainAxisAlignment.center, 107 | children: [ 108 | RoundedIconButton( 109 | icon: Icons.remove, 110 | iconSize: widget.iconSize, 111 | onPress: () { 112 | setState(() { 113 | widget.value = 114 | widget.value == widget.lowerLimit ? widget.lowerLimit : widget.value -= widget.stepValue; 115 | }); 116 | }, 117 | ), 118 | Container( 119 | width: widget.iconSize, 120 | child: Text( 121 | '${widget.value}', 122 | style: TextStyle( 123 | fontSize: widget.iconSize * 0.8, 124 | ), 125 | textAlign: TextAlign.center, 126 | ), 127 | ), 128 | RoundedIconButton( 129 | icon: Icons.add, 130 | iconSize: widget.iconSize, 131 | onPress: () { 132 | setState(() { 133 | widget.value = 134 | widget.value == widget.upperLimit ? widget.upperLimit : widget.value += widget.stepValue; 135 | }); 136 | }, 137 | ), 138 | ], 139 | ); 140 | } 141 | } 142 | 143 | 144 | 145 | class RoundedIconButton extends StatelessWidget { 146 | RoundedIconButton({@required this.icon, @required this.onPress, @required this.iconSize}); 147 | 148 | final IconData icon; 149 | final Function onPress; 150 | final double iconSize; 151 | 152 | @override 153 | Widget build(BuildContext context) { 154 | return RawMaterialButton( 155 | constraints: BoxConstraints.tightFor(width: iconSize, height: iconSize), 156 | elevation: 6.0, 157 | onPressed: onPress, 158 | shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(iconSize*0.2)), 159 | fillColor: Color(0xFF65A34A), 160 | child: Icon( 161 | icon, 162 | color: Colors.white, 163 | size: iconSize * 0.8, 164 | ), 165 | ); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /tabbar.dart: -------------------------------------------------------------------------------- 1 | //Simple Tabbar 2 | class TabBarDemo extends StatelessWidget { 3 | @override 4 | Widget build(BuildContext context) { 5 | return MaterialApp( 6 | home: DefaultTabController( 7 | length: 3, 8 | child: Scaffold( 9 | appBar: AppBar( 10 | bottom: TabBar( 11 | tabs: [ 12 | Tab(icon: Icon(Icons.directions_car)), 13 | Tab(icon: Icon(Icons.directions_transit)), 14 | Tab(icon: Icon(Icons.directions_bike)), 15 | ], 16 | ), 17 | title: Text('Tabs Demo'), 18 | ), 19 | body: TabBarView( 20 | children: [ 21 | Icon(Icons.directions_car), 22 | Icon(Icons.directions_transit), 23 | Icon(Icons.directions_bike), 24 | ], 25 | ), 26 | ), 27 | ), 28 | ); 29 | } 30 | } 31 | 32 | 33 | ----------------------------------------------------/\/\/\/\/\/\/\/\/\/\/\/\/\/\----------------------------------------------------------------- 34 | //Tab with some space in between(not attached with the appbar) 35 | 36 | 37 | class profilePage extends StatefulWidget { 38 | @override 39 | profilePageState createState() => profilePageState(); 40 | } 41 | 42 | class profilePageState extends State { 43 | 44 | @override 45 | Widget build(BuildContext context) { 46 | return DefaultTabController( 47 | length: 2, 48 | child: Scaffold( 49 | appBar: AppBar( 50 | title: Text( 51 | 'My Profile', 52 | ), 53 | centerTitle: true, 54 | backgroundColor: Colors.grey[700].withOpacity(0.4), 55 | elevation: 0, 56 | // give the app bar rounded corners 57 | shape: RoundedRectangleBorder( 58 | borderRadius: BorderRadius.only( 59 | bottomLeft: Radius.circular(20.0), 60 | bottomRight: Radius.circular(20.0), 61 | ), 62 | ), 63 | leading: Icon( 64 | Icons.menu, 65 | ), 66 | ), 67 | body: Column( 68 | children: [ 69 | // construct the profile details widget here 70 | SizedBox( 71 | height: 180, 72 | child: Center( 73 | child: Text( 74 | 'You other stuffs', 75 | ), 76 | ), 77 | ), 78 | 79 | // the tab bar with two items 80 | SizedBox( 81 | height: 50, 82 | child: AppBar( 83 | bottom: TabBar( 84 | tabs: [ 85 | Tab( 86 | icon: Icon(Icons.directions_bike), 87 | ), 88 | Tab( 89 | icon: Icon( 90 | Icons.directions_car, 91 | ), 92 | ), 93 | ], 94 | ), 95 | ), 96 | ), 97 | 98 | // create widgets for each tab bar here 99 | Expanded( 100 | child: TabBarView( 101 | children: [ 102 | // first tab bar view widget 103 | Container( 104 | color: Colors.red, 105 | child: Center( 106 | child: Text( 107 | 'Bike', 108 | ), 109 | ), 110 | ), 111 | 112 | // second tab bar viiew widget 113 | Container( 114 | color: Colors.pink, 115 | child: Center( 116 | child: Text( 117 | 'Car', 118 | ), 119 | ), 120 | ), 121 | ], 122 | ), 123 | ), 124 | ], 125 | ), 126 | ), 127 | ); 128 | } 129 | } 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /test.dart: -------------------------------------------------------------------------------- 1 | 2 | Container( 3 | height: 120.0, 4 | width: 120.0, 5 | decoration: BoxDecoration( 6 | image: DecorationImage( 7 | image: AssetImage( 8 | 'assets/assets/alucard.jpg'), 9 | fit: BoxFit.fill, 10 | ), 11 | shape: BoxShape.circle, 12 | ), 13 | ) 14 | -------------------------------------------------------------------------------- /text-field.dart: -------------------------------------------------------------------------------- 1 | 2 | //Demo text field (for email/name/etc.) 3 | TextFieldContainer( 4 | child: TextField( 5 | onChanged: (value) {}, 6 | cursorColor: Colors.black, 7 | decoration: InputDecoration( 8 | icon: Icon( 9 | Icons.email, 10 | color: Colors.black, 11 | ), 12 | hintText: 'Enter your Email', 13 | border: InputBorder.none, 14 | ), 15 | ), 16 | ), 17 | 18 | class TextFieldContainer extends StatelessWidget { 19 | final Widget child; 20 | const TextFieldContainer({ 21 | Key? key, 22 | required this.child, 23 | }) : super(key: key); 24 | 25 | @override 26 | Widget build(BuildContext context) { 27 | Size size = MediaQuery.of(context).size; 28 | return Container( 29 | margin: EdgeInsets.symmetric(vertical: 10), 30 | padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5), 31 | width: size.width * 0.9, 32 | decoration: BoxDecoration( 33 | color: pSecondaryColor.withOpacity(0.2), 34 | borderRadius: BorderRadius.circular(29), 35 | ), 36 | child: child, 37 | ); 38 | } 39 | } 40 | 41 | 42 | ----------------------------------------/\/\/\/\/\/\/\/\/\/\/\/\------------------------------------------------------ 43 | 44 | //Dummy Password text-field : 45 | bool _isHidden = true; 46 | TextFieldContainer( 47 | child: TextField( 48 | obscureText: _isHidden, 49 | onChanged: (value) {}, 50 | cursorColor: Colors.black, 51 | decoration: InputDecoration( 52 | hintText: "Password", 53 | icon: Icon( 54 | Icons.lock, 55 | color: Colors.black, 56 | ), 57 | suffixIcon: InkWell( 58 | onTap: _togglePasswordView, 59 | child: Icon( 60 | _isHidden 61 | ? Icons.visibility 62 | : Icons.visibility_off, 63 | color: Colors.black, 64 | ), 65 | ), 66 | border: InputBorder.none, 67 | ), 68 | ), 69 | ), 70 | 71 | class TextFieldContainer extends StatelessWidget { 72 | final Widget child; 73 | const TextFieldContainer({ 74 | Key? key, 75 | required this.child, 76 | }) : super(key: key); 77 | 78 | @override 79 | Widget build(BuildContext context) { 80 | Size size = MediaQuery.of(context).size; 81 | return Container( 82 | margin: EdgeInsets.symmetric(vertical: 10), 83 | padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5), 84 | width: size.width * 0.9, 85 | decoration: BoxDecoration( 86 | color: pSecondaryColor.withOpacity(0.2), 87 | borderRadius: BorderRadius.circular(29), 88 | ), 89 | child: child, 90 | ); 91 | } 92 | } 93 | void _togglePasswordView() { 94 | setState(() { 95 | _isHidden = !_isHidden; 96 | }); 97 | } 98 | 99 | ----------------------------------------/\/\/\/\/\/\/\/\/\/\/\/\---------------------------------------------------- 100 | 101 | //Multi-line Textfield in flutter 102 | TextField( 103 | keyboardType: TextInputType.multiline, 104 | minLines: 1,//Normal textInputField will be displayed 105 | maxLines: 5,// when user presses enter it will adapt to it 106 | ); 107 | 108 | ----------------------------------------/\/\/\//\/\/\/\/\/\/\/\/\---------------------------------------------------- 109 | 110 | //TextField with validator 111 | -------------------------------------------------------------------------------- /textstyles.dart: -------------------------------------------------------------------------------- 1 | // Underlining Text- 2 | //When underlining everything you can set a TextStyle on the Text widget. 3 | Text( 4 | 'Hello world', 5 | style: TextStyle( 6 | decoration: TextDecoration.underline, 7 | ), 8 | ) 9 | //If you only want to underline part of the text then you need to use Text.rich() (or a RichText widget) and break the string into TextSpans that you can add a style to. 10 | 11 | Text.rich( 12 | TextSpan( 13 | text: 'Hello ', 14 | style: TextStyle(fontSize: 50), 15 | children: [ 16 | TextSpan( 17 | text: 'world', 18 | style: TextStyle( 19 | decoration: TextDecoration.underline, 20 | )), 21 | // can add more TextSpans here... 22 | ], 23 | ), 24 | ) 25 | 26 | 27 | // other underlining themes --- 28 | decorationStyle: TextDecorationStyle.dashed/ TextDecorationStyle.dotted / TextDecorationStyle.double / TextDecorationStyle.wavy 29 | 30 | 31 | 32 | 33 | //To add space between underline FOR APPS WITH LIGHT & DARK THEME BOTH (create a dummy shadow and make the original text transparent) 34 | final Brightness brightnessValue = MediaQuery.of(context).platformBrightness; //to check 35 | bool isDark = brightnessValue == Brightness.dark; 36 | 37 | Text(' Select the theme of app ',style: TextStyle( 38 | shadows: [ isDark? 39 | Shadow( 40 | color: Colors.white, 41 | offset: Offset(0, -5)): 42 | Shadow( 43 | color: Colors.black, 44 | offset: Offset(0, -5)) 45 | ], 46 | color: Colors.transparent, 47 | decoration:TextDecoration.underline, 48 | decorationColor: isDark?Colors.white:Colors.black, 49 | fontSize: 16,letterSpacing: 2, 50 | fontWeight: FontWeight.bold), 51 | ), 52 | -------------------------------------------------------------------------------- /themes.dart: -------------------------------------------------------------------------------- 1 | //Applying dark & light themes in flutter 2 | //code snippet taken from abuanwar072 (applied some of my own changes too) 3 | 4 | import 'package:colorCode.dart'; 5 | import 'package:flutter/material.dart'; 6 | import 'package:google_fonts/google_fonts.dart'; 7 | 8 | 9 | // let's add light theme on our app 10 | 11 | ThemeData lightThemeData(BuildContext context) { 12 | return ThemeData.light().copyWith( 13 | primaryColor: kPrimaryColor, 14 | scaffoldBackgroundColor: Colors.white, 15 | appBarTheme: appBarTheme, 16 | iconTheme: IconThemeData(color: kContentColorLightTheme), 17 | textTheme: GoogleFonts.interTextTheme(Theme.of(context).textTheme) 18 | .apply(bodyColor: kContentColorLightTheme), 19 | colorScheme: ColorScheme.light( 20 | primary: kPrimaryColor, 21 | secondary: kSecondaryColor, 22 | error: kErrorColor, 23 | ), 24 | bottomNavigationBarTheme: BottomNavigationBarThemeData( 25 | backgroundColor: Colors.white, 26 | selectedItemColor: kContentColorLightTheme.withOpacity(0.7), 27 | unselectedItemColor: kContentColorLightTheme.withOpacity(0.32), 28 | selectedIconTheme: IconThemeData(color: kPrimaryColor), 29 | showUnselectedLabels: true, 30 | ), 31 | ); 32 | } 33 | 34 | // Let's apply dark theme on our app 35 | ThemeData darkThemeData(BuildContext context) { 36 | // Bydefault flutter provie us light and dark theme 37 | // we just modify it as our need 38 | return ThemeData.dark().copyWith( 39 | primaryColor: kPrimaryColor, 40 | scaffoldBackgroundColor: kContentColorLightTheme, 41 | appBarTheme: appBarTheme, 42 | iconTheme: IconThemeData(color: kContentColorDarkTheme), 43 | textTheme: GoogleFonts.interTextTheme(Theme.of(context).textTheme) 44 | .apply(bodyColor: kContentColorDarkTheme), 45 | colorScheme: ColorScheme.dark().copyWith( 46 | primary: kPrimaryColor, 47 | secondary: kSecondaryColor, 48 | error: kErrorColor, 49 | ), 50 | bottomNavigationBarTheme: BottomNavigationBarThemeData( 51 | backgroundColor: kContentColorLightTheme, 52 | selectedItemColor: Colors.white70, 53 | unselectedItemColor: kContentColorDarkTheme.withOpacity(0.32), 54 | selectedIconTheme: IconThemeData(color: kPrimaryColor), 55 | showUnselectedLabels: true, 56 | ), 57 | ); 58 | } 59 | 60 | final appBarTheme = AppBarTheme(centerTitle: false, elevation: 0); 61 | -------------------------------------------------------------------------------- /timepicker.dart: -------------------------------------------------------------------------------- 1 | //Time picker 2 | 3 | TimeOfDay selectedTime = TimeOfDay.now(); 4 | 5 | Future _selectTime(BuildContext context) async { 6 | final TimeOfDay picked_s = await showTimePicker( 7 | context: context, 8 | initialTime: selectedTime, builder: (BuildContext context, Widget child) { 9 | return MediaQuery( 10 | data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false), 11 | child: child, 12 | );}); 13 | 14 | if (picked_s != null && picked_s != selectedTime ) 15 | setState(() { 16 | selectedTime = picked_s; 17 | }); 18 | } 19 | -------------------------------------------------------------------------------- /workManager.dart: -------------------------------------------------------------------------------- 1 | workmanager: ^0.4.1 2 | //This is especially useful to run periodic tasks, such as fetching remote data on a regular basis. 3 | import 'dart:async'; 4 | import 'dart:io'; 5 | import 'dart:math'; 6 | 7 | import 'package:flutter/material.dart'; 8 | import 'package:path_provider/path_provider.dart'; 9 | import 'package:shared_preferences/shared_preferences.dart'; 10 | import 'package:workmanager/workmanager.dart'; 11 | 12 | void main() => runApp(MyApp()); 13 | 14 | const simpleTaskKey = "simpleTask"; 15 | const rescheduledTaskKey = "rescheduledTask"; 16 | const failedTaskKey = "failedTask"; 17 | const simpleDelayedTask = "simpleDelayedTask"; 18 | const simplePeriodicTask = "simplePeriodicTask"; 19 | const simplePeriodic1HourTask = "simplePeriodic1HourTask"; 20 | 21 | void callbackDispatcher() { 22 | Workmanager().executeTask((task, inputData) async { 23 | switch (task) { 24 | case simpleTaskKey: 25 | print("$simpleTaskKey was executed. inputData = $inputData"); 26 | final prefs = await SharedPreferences.getInstance(); 27 | prefs.setBool("test", true); 28 | print("Bool from prefs: ${prefs.getBool("test")}"); 29 | break; 30 | case rescheduledTaskKey: 31 | final key = inputData!['key']!; 32 | final prefs = await SharedPreferences.getInstance(); 33 | if (prefs.containsKey('unique-$key')) { 34 | print('has been running before, task is successful'); 35 | return true; 36 | } else { 37 | await prefs.setBool('unique-$key', true); 38 | print('reschedule task'); 39 | return false; 40 | } 41 | case failedTaskKey: 42 | print('failed task'); 43 | return Future.error('failed'); 44 | case simpleDelayedTask: 45 | print("$simpleDelayedTask was executed"); 46 | break; 47 | case simplePeriodicTask: 48 | print("$simplePeriodicTask was executed"); 49 | break; 50 | case simplePeriodic1HourTask: 51 | print("$simplePeriodic1HourTask was executed"); 52 | break; 53 | case Workmanager.iOSBackgroundTask: 54 | print("The iOS background fetch was triggered"); 55 | Directory? tempDir = await getTemporaryDirectory(); 56 | String? tempPath = tempDir.path; 57 | print( 58 | "You can access other plugins in the background, for example Directory.getTemporaryDirectory(): $tempPath"); 59 | break; 60 | } 61 | 62 | return Future.value(true); 63 | }); 64 | } 65 | 66 | class MyApp extends StatefulWidget { 67 | @override 68 | _MyAppState createState() => _MyAppState(); 69 | } 70 | 71 | enum _Platform { android, ios } 72 | 73 | class PlatformEnabledButton extends RaisedButton { 74 | final _Platform platform; 75 | 76 | PlatformEnabledButton({ 77 | required this.platform, 78 | required Widget child, 79 | required VoidCallback onPressed, 80 | }) : super( 81 | child: child, 82 | onPressed: (Platform.isAndroid && platform == _Platform.android || 83 | Platform.isIOS && platform == _Platform.ios) 84 | ? onPressed 85 | : null); 86 | } 87 | 88 | class _MyAppState extends State { 89 | @override 90 | Widget build(BuildContext context) { 91 | return MaterialApp( 92 | home: Scaffold( 93 | appBar: AppBar( 94 | title: Text("Flutter WorkManager Example"), 95 | ), 96 | body: Padding( 97 | padding: const EdgeInsets.all(8.0), 98 | child: Column( 99 | crossAxisAlignment: CrossAxisAlignment.stretch, 100 | children: [ 101 | Text("Plugin initialization", 102 | style: Theme.of(context).textTheme.headline), 103 | RaisedButton( 104 | child: Text("Start the Flutter background service"), 105 | onPressed: () { 106 | Workmanager().initialize( 107 | callbackDispatcher, 108 | isInDebugMode: true, 109 | ); 110 | }), 111 | SizedBox(height: 16), 112 | Text("One Off Tasks (Android only)", 113 | style: Theme.of(context).textTheme.headline), 114 | //This task runs once. 115 | //Most likely this will trigger immediately 116 | PlatformEnabledButton( 117 | platform: _Platform.android, 118 | child: Text("Register OneOff Task"), 119 | onPressed: () { 120 | Workmanager().registerOneOffTask( 121 | "1", 122 | simpleTaskKey, 123 | inputData: { 124 | 'int': 1, 125 | 'bool': true, 126 | 'double': 1.0, 127 | 'string': 'string', 128 | 'array': [1, 2, 3], 129 | }, 130 | ); 131 | }, 132 | ), 133 | PlatformEnabledButton( 134 | platform: _Platform.android, 135 | child: Text("Register rescheduled Task"), 136 | onPressed: () { 137 | Workmanager().registerOneOffTask( 138 | "1-rescheduled", 139 | rescheduledTaskKey, 140 | inputData: { 141 | 'key': Random().nextInt(64000), 142 | }, 143 | ); 144 | }, 145 | ), 146 | PlatformEnabledButton( 147 | platform: _Platform.android, 148 | child: Text("Register failed Task"), 149 | onPressed: () { 150 | Workmanager().registerOneOffTask( 151 | "1-failed", 152 | failedTaskKey, 153 | ); 154 | }, 155 | ), 156 | //This task runs once 157 | //This wait at least 10 seconds before running 158 | PlatformEnabledButton( 159 | platform: _Platform.android, 160 | child: Text("Register Delayed OneOff Task"), 161 | onPressed: () { 162 | Workmanager().registerOneOffTask( 163 | "2", 164 | simpleDelayedTask, 165 | initialDelay: Duration(seconds: 10), 166 | ); 167 | }), 168 | SizedBox(height: 8), 169 | Text("Periodic Tasks (Android only)", 170 | style: Theme.of(context).textTheme.headline), 171 | //This task runs periodically 172 | //It will wait at least 10 seconds before its first launch 173 | //Since we have not provided a frequency it will be the default 15 minutes 174 | PlatformEnabledButton( 175 | platform: _Platform.android, 176 | child: Text("Register Periodic Task"), 177 | onPressed: () { 178 | Workmanager().registerPeriodicTask( 179 | "3", 180 | simplePeriodicTask, 181 | initialDelay: Duration(seconds: 10), 182 | ); 183 | }), 184 | //This task runs periodically 185 | //It will run about every hour 186 | PlatformEnabledButton( 187 | platform: _Platform.android, 188 | child: Text("Register 1 hour Periodic Task"), 189 | onPressed: () { 190 | Workmanager().registerPeriodicTask( 191 | "5", 192 | simplePeriodic1HourTask, 193 | frequency: Duration(hours: 1), 194 | ); 195 | }), 196 | PlatformEnabledButton( 197 | platform: _Platform.android, 198 | child: Text("Cancel All"), 199 | onPressed: () async { 200 | await Workmanager().cancelAll(); 201 | print('Cancel all tasks completed'); 202 | }, 203 | ), 204 | ], 205 | ), 206 | ), 207 | ), 208 | ); 209 | } 210 | } 211 | --------------------------------------------------------------------------------