mirror of
https://github.com/nisrulz/flutter-examples.git
synced 2026-08-24 16:50:47 +00:00
refactor: split app wrapper from focused example code (single-file apps)
Convert 20 more single-file apps to the validated pattern: lib/main.dart holds only the runApp + MaterialApp bootstrap, while a new lib/example.dart holds the full screen (Scaffold, AppBar) and the focused example code. Apps: enabling_splash_screen, getx_counter_app, image_from_network, infinite_list, load_local_image, load_local_json, persist_key_value, push_notifications, sliver_app_bar_example, stateless_widgets, tic_tac_toe, tip_calculator, using_alert_dialog, using_edittext, using_expansionpanel, using_http_get, using_interactiveviewer, using_snackbar, using_stepper, using_theme
This commit is contained in:
18
enabling_splash_screen/lib/example.dart
Normal file
18
enabling_splash_screen/lib/example.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: how to enable a splash screen and show a simple message.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Splash Screen Example"),
|
||||
),
|
||||
body: Center(
|
||||
child: Text("Hello World"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() => runApp(const MyApp());
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -10,14 +12,7 @@ class MyApp extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Flutter Demo',
|
||||
home: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Splash Screen Example"),
|
||||
),
|
||||
body: Center(
|
||||
child: Text("Hello World"),
|
||||
),
|
||||
),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
41
getx_counter_app/lib/example.dart
Normal file
41
getx_counter_app/lib/example.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
|
||||
// Example: a reactive counter using GetX state management.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// create variable that hold out number with .obs parameter (.obs comes from getx state management)
|
||||
var counter = 0.obs;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Counter app with Getx (Get) state management"),
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text(
|
||||
'You have pushed the button this many times:',
|
||||
),
|
||||
|
||||
// in get (getx) we must ue Obx for the widget that we want to change like setState in statefull widget\
|
||||
Obx(() => Text(
|
||||
// we can show our variable by call .value method
|
||||
'${counter.value}',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
// we can plus or everything that we want by add .value method to our obs variable
|
||||
onPressed: () => counter.value++,
|
||||
tooltip: 'Increment',
|
||||
child: const Icon(Icons.add),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
@@ -16,44 +16,7 @@ class MyApp extends StatelessWidget {
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.blue,
|
||||
),
|
||||
home: const MyHomePage(),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyHomePage extends StatelessWidget {
|
||||
const MyHomePage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// create variable that hold out number with .obs parameter (.obs comes from getx state management)
|
||||
var counter = 0.obs;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Counter app with Getx (Get) state management"),
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const Text(
|
||||
'You have pushed the button this many times:',
|
||||
),
|
||||
|
||||
// in get (getx) we must ue Obx for the widget that we want to change like setState in statefull widget\
|
||||
Obx(() => Text(
|
||||
// we can show our variable by call .value method
|
||||
'${counter.value}',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
// we can plus or everything that we want by add .value method to our obs variable
|
||||
onPressed: () => counter.value++,
|
||||
tooltip: 'Increment',
|
||||
child: const Icon(Icons.add),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
27
image_from_network/lib/example.dart
Normal file
27
image_from_network/lib/example.dart
Normal file
@@ -0,0 +1,27 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: load images (including animated GIFs) from a network URL.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Image from Network"),
|
||||
),
|
||||
body: Container(
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
// Load image from network
|
||||
Image.network(
|
||||
'https://github.com/nisrulz/flutter-examples/raw/develop/image_from_network/img/flutter_logo.png'),
|
||||
// even loads gifs
|
||||
// Gif image from Giphy, all copyrights are owned by Giphy
|
||||
Image.network(
|
||||
'https://github.com/nisrulz/flutter-examples/raw/develop/image_from_network/img/loop_anim.gif'),
|
||||
],
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -8,23 +12,8 @@ class MyApp extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Image from Network"),
|
||||
),
|
||||
body: Container(
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
// Load image from network
|
||||
Image.network(
|
||||
'https://github.com/nisrulz/flutter-examples/raw/develop/image_from_network/img/flutter_logo.png'),
|
||||
// even loads gifs
|
||||
// Gif image from Giphy, all copyrights are owned by Giphy
|
||||
Image.network(
|
||||
'https://github.com/nisrulz/flutter-examples/raw/develop/image_from_network/img/loop_anim.gif'),
|
||||
],
|
||||
)),
|
||||
),
|
||||
title: "Image from Network",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
110
infinite_list/lib/example.dart
Normal file
110
infinite_list/lib/example.dart
Normal file
@@ -0,0 +1,110 @@
|
||||
import 'package:english_words/english_words.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: an infinitely scrolling list that generates new word pairs on demand.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
final _suggestions = <WordPair>[];
|
||||
final _saved = <WordPair>{};
|
||||
final _biggerFont = const TextStyle(fontSize: 18.0);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Infinite List'),
|
||||
centerTitle: true,
|
||||
actions: <Widget>[
|
||||
IconButton(icon: const Icon(Icons.list), onPressed: _pushSaved),
|
||||
],
|
||||
),
|
||||
body: _buildSuggestions(),
|
||||
);
|
||||
}
|
||||
|
||||
void _pushSaved() {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) {
|
||||
final tiles = _saved.map(
|
||||
(pair) {
|
||||
return ListTile(
|
||||
title: Text(
|
||||
pair.asPascalCase,
|
||||
style: _biggerFont,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
final divided = ListTile.divideTiles(
|
||||
context: context,
|
||||
tiles: tiles,
|
||||
).toList();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Saved lists'),
|
||||
),
|
||||
body: ListView(children: divided),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRow(WordPair pair) {
|
||||
final alreadySaved = _saved.contains(pair);
|
||||
return ListTile(
|
||||
title: Text(
|
||||
pair.asPascalCase,
|
||||
style: _biggerFont,
|
||||
),
|
||||
trailing: Icon(
|
||||
alreadySaved ? Icons.favorite : Icons.favorite_border,
|
||||
color: alreadySaved ? Colors.red : null,
|
||||
),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
if (alreadySaved) {
|
||||
_saved.remove(pair);
|
||||
} else {
|
||||
_saved.add(pair);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSuggestions() {
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
// The itemBuilder callback is called once per suggested word pairing,
|
||||
// and places each suggestion into a ListTile row.
|
||||
// For even rows, the function adds a ListTile row for the word pairing.
|
||||
// For odd rows, the function adds a Divider widget to visually
|
||||
// separate the entries. Note that the divider may be difficult
|
||||
// to see on smaller devices.
|
||||
itemBuilder: (context, i) {
|
||||
// Add a one-pixel-high divider widget before each row in theListView.
|
||||
if (i.isOdd) return const Divider();
|
||||
|
||||
// The syntax "i ~/ 2" divides i by 2 and returns an integer result.
|
||||
// For example: 1, 2, 3, 4, 5 becomes 0, 1, 1, 2, 2.
|
||||
// This calculates the actual number of word pairings in the ListView,
|
||||
// minus the divider widgets.
|
||||
final index = i ~/ 2;
|
||||
// If you've reached the end of the available word pairings...
|
||||
if (index >= _suggestions.length) {
|
||||
// ...then generate 10 more and add them to the suggestions list.
|
||||
_suggestions.addAll(generateWordPairs().take(10));
|
||||
}
|
||||
return _buildRow(_suggestions[index]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'package:english_words/english_words.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -13,114 +16,7 @@ class MyApp extends StatelessWidget {
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue)
|
||||
.copyWith(secondary: Colors.lightBlue)),
|
||||
home: RandomWords(),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RandomWords extends StatefulWidget {
|
||||
const RandomWords({super.key});
|
||||
|
||||
@override
|
||||
createState() => RandomWordsState();
|
||||
}
|
||||
|
||||
class RandomWordsState extends State<RandomWords> {
|
||||
final _suggestions = <WordPair>[];
|
||||
final _saved = <WordPair>{};
|
||||
final _biggerFont = const TextStyle(fontSize: 18.0);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Infinite List'),
|
||||
centerTitle: true,
|
||||
actions: <Widget>[
|
||||
IconButton(icon: Icon(Icons.list), onPressed: _pushSaved),
|
||||
],
|
||||
),
|
||||
body: _buildSuggestions(),
|
||||
);
|
||||
}
|
||||
|
||||
void _pushSaved() {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) {
|
||||
final tiles = _saved.map(
|
||||
(pair) {
|
||||
return ListTile(
|
||||
title: Text(
|
||||
pair.asPascalCase,
|
||||
style: _biggerFont,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
final divided = ListTile.divideTiles(
|
||||
context: context,
|
||||
tiles: tiles,
|
||||
).toList();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Saved lists'),
|
||||
),
|
||||
body: ListView(children: divided),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRow(WordPair pair) {
|
||||
final alreadySaved = _saved.contains(pair);
|
||||
return ListTile(
|
||||
title: Text(
|
||||
pair.asPascalCase,
|
||||
style: _biggerFont,
|
||||
),
|
||||
trailing: Icon(
|
||||
alreadySaved ? Icons.favorite : Icons.favorite_border,
|
||||
color: alreadySaved ? Colors.red : null,
|
||||
),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
if (alreadySaved) {
|
||||
_saved.remove(pair);
|
||||
} else {
|
||||
_saved.add(pair);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSuggestions() {
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
// The itemBuilder callback is called once per suggested word pairing,
|
||||
// and places each suggestion into a ListTile row.
|
||||
// For even rows, the function adds a ListTile row for the word pairing.
|
||||
// For odd rows, the function adds a Divider widget to visually
|
||||
// separate the entries. Note that the divider may be difficult
|
||||
// to see on smaller devices.
|
||||
itemBuilder: (context, i) {
|
||||
// Add a one-pixel-high divider widget before each row in theListView.
|
||||
if (i.isOdd) return Divider();
|
||||
|
||||
// The syntax "i ~/ 2" divides i by 2 and returns an integer result.
|
||||
// For example: 1, 2, 3, 4, 5 becomes 0, 1, 1, 2, 2.
|
||||
// This calculates the actual number of word pairings in the ListView,
|
||||
// minus the divider widgets.
|
||||
final index = i ~/ 2;
|
||||
// If you've reached the end of the available word pairings...
|
||||
if (index >= _suggestions.length) {
|
||||
// ...then generate 10 more and add them to the suggestions list.
|
||||
_suggestions.addAll(generateWordPairs().take(10));
|
||||
}
|
||||
return _buildRow(_suggestions[index]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
28
load_local_image/lib/example.dart
Normal file
28
load_local_image/lib/example.dart
Normal file
@@ -0,0 +1,28 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: load an image from the app's assets and use it as a background.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Load local image"),
|
||||
),
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
image: DecorationImage(
|
||||
// Load image from assets
|
||||
image: AssetImage('data_repo/img/bg1.jpg'),
|
||||
// Make the image cover the whole area
|
||||
fit: BoxFit.cover)),
|
||||
child: const Center(
|
||||
child: Text(
|
||||
"Hello World!",
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyApp(),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
@@ -11,23 +11,9 @@ class MyApp extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Load local image"),
|
||||
),
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
// Load image from assets
|
||||
image: AssetImage('data_repo/img/bg1.jpg'),
|
||||
// Make the image cover the whole area
|
||||
fit: BoxFit.cover)),
|
||||
child: Center(
|
||||
child: Text(
|
||||
"Hello World!",
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
));
|
||||
return MaterialApp(
|
||||
title: "Load local image",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
57
load_local_json/lib/example.dart
Normal file
57
load_local_json/lib/example.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: load and decode a local JSON asset, then list its rows.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
late List data;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Load local JSON file"),
|
||||
),
|
||||
body: Container(
|
||||
child: Center(
|
||||
// Use future builder and DefaultAssetBundle to load the local JSON file
|
||||
child: FutureBuilder(
|
||||
future: DefaultAssetBundle.of(context)
|
||||
.loadString('data_repo/starwars_data.json'),
|
||||
builder: (context, snapshot) {
|
||||
// Decode the JSON
|
||||
var newData = json.decode(snapshot.data.toString());
|
||||
|
||||
return ListView.builder(
|
||||
// Build the ListView
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Text("Name: ${newData[index]['name']}"),
|
||||
Text("Height: ${newData[index]['height']}"),
|
||||
Text("Mass: ${newData[index]['mass']}"),
|
||||
Text("Hair Color: ${newData[index]['hair_color']}"),
|
||||
Text("Skin Color: ${newData[index]['skin_color']}"),
|
||||
Text("Eye Color: ${newData[index]['eye_color']}"),
|
||||
Text("Birth Year: ${newData[index]['birth_year']}"),
|
||||
Text("Gender: ${newData[index]['gender']}")
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
itemCount: newData == null ? 0 : newData.length,
|
||||
);
|
||||
}),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,62 +1,19 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyApp(),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatefulWidget {
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
MyAppState createState() => MyAppState();
|
||||
}
|
||||
|
||||
class MyAppState extends State<MyApp> {
|
||||
late List data;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Load local JSON file"),
|
||||
),
|
||||
body: Container(
|
||||
child: Center(
|
||||
// Use future builder and DefaultAssetBundle to load the local JSON file
|
||||
child: FutureBuilder(
|
||||
future: DefaultAssetBundle.of(context)
|
||||
.loadString('data_repo/starwars_data.json'),
|
||||
builder: (context, snapshot) {
|
||||
// Decode the JSON
|
||||
var newData = json.decode(snapshot.data.toString());
|
||||
|
||||
return ListView.builder(
|
||||
// Build the ListView
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Text("Name: ${newData[index]['name']}"),
|
||||
Text("Height: ${newData[index]['height']}"),
|
||||
Text("Mass: ${newData[index]['mass']}"),
|
||||
Text("Hair Color: ${newData[index]['hair_color']}"),
|
||||
Text("Skin Color: ${newData[index]['skin_color']}"),
|
||||
Text("Eye Color: ${newData[index]['eye_color']}"),
|
||||
Text("Birth Year: ${newData[index]['birth_year']}"),
|
||||
Text("Gender: ${newData[index]['gender']}")
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
itemCount: newData == null ? 0 : newData.length,
|
||||
);
|
||||
}),
|
||||
),
|
||||
));
|
||||
return MaterialApp(
|
||||
title: "Load local JSON file",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
94
persist_key_value/lib/example.dart
Normal file
94
persist_key_value/lib/example.dart
Normal file
@@ -0,0 +1,94 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
// Example: persist a counter across app restarts with shared_preferences.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
var nameOfApp = "Persist Key Value";
|
||||
|
||||
var counter = 0;
|
||||
|
||||
// define a key to use later
|
||||
var key = "counter";
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadSavedData();
|
||||
}
|
||||
|
||||
Future<void> _loadSavedData() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _onIncrementHit() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0) + 1;
|
||||
});
|
||||
|
||||
// Save Value
|
||||
prefs.setInt(key, counter);
|
||||
}
|
||||
|
||||
Future<void> _onDecrementHit() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0) - 1;
|
||||
});
|
||||
|
||||
// Save Value
|
||||
prefs.setInt(key, counter);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// Appbar
|
||||
appBar: AppBar(
|
||||
// Title
|
||||
title: Text(nameOfApp),
|
||||
),
|
||||
// Body
|
||||
body: Container(
|
||||
// Center the content
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'$counter',
|
||||
textScaler: TextScaler.linear(10.0),
|
||||
),
|
||||
const Padding(padding: EdgeInsets.all(10.0)),
|
||||
ElevatedButton(
|
||||
onPressed: _onIncrementHit,
|
||||
child: const Text('Increment Counter')),
|
||||
const Padding(padding: EdgeInsets.all(10.0)),
|
||||
ElevatedButton(
|
||||
onPressed: _onDecrementHit,
|
||||
child: const Text('Decrement Counter')),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,101 +1,23 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
// Disable the debug flag
|
||||
debugShowCheckedModeBanner: false,
|
||||
// Home
|
||||
home: MyHome()));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyHome extends StatefulWidget {
|
||||
const MyHome({super.key});
|
||||
|
||||
@override
|
||||
MyHomeState createState() {
|
||||
return MyHomeState();
|
||||
}
|
||||
}
|
||||
|
||||
class MyHomeState extends State<MyHome> {
|
||||
var nameOfApp = "Persist Key Value";
|
||||
|
||||
var counter = 0;
|
||||
|
||||
// define a key to use later
|
||||
var key = "counter";
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadSavedData();
|
||||
}
|
||||
|
||||
Future<void> _loadSavedData() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _onIncrementHit() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0) + 1;
|
||||
});
|
||||
|
||||
// Save Value
|
||||
prefs.setInt(key, counter);
|
||||
}
|
||||
|
||||
Future<void> _onDecrementHit() async {
|
||||
// Get shared preference instance
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
|
||||
setState(() {
|
||||
// Get value
|
||||
counter = (prefs.getInt(key) ?? 0) - 1;
|
||||
});
|
||||
|
||||
// Save Value
|
||||
prefs.setInt(key, counter);
|
||||
}
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// Appbar
|
||||
appBar: AppBar(
|
||||
// Title
|
||||
title: Text(nameOfApp),
|
||||
),
|
||||
// Body
|
||||
body: Container(
|
||||
// Center the content
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'$counter',
|
||||
textScaler: TextScaler.linear(10.0),
|
||||
),
|
||||
Padding(padding: EdgeInsets.all(10.0)),
|
||||
ElevatedButton(
|
||||
onPressed: _onIncrementHit, child: Text('Increment Counter')),
|
||||
Padding(padding: EdgeInsets.all(10.0)),
|
||||
ElevatedButton(
|
||||
onPressed: _onDecrementHit, child: Text('Decrement Counter')),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
return MaterialApp(
|
||||
// Disable the debug flag
|
||||
debugShowCheckedModeBanner: false,
|
||||
// Title
|
||||
title: "Persist Key Value",
|
||||
// Home
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
130
push_notifications/lib/example.dart
Normal file
130
push_notifications/lib/example.dart
Normal file
@@ -0,0 +1,130 @@
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: receive and display Firebase Cloud Messaging push notifications.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
String title = "Title will appear here";
|
||||
String messageData = "Message text will appear here";
|
||||
|
||||
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
|
||||
|
||||
@override
|
||||
Future<void> initState() async {
|
||||
super.initState();
|
||||
|
||||
/*
|
||||
Message that we are getting from firebase will be of form:-
|
||||
{
|
||||
notification:{
|
||||
title:'Custom Title that we send from firebase cloud messaging',
|
||||
body:'Text of the message will appear here'
|
||||
},
|
||||
data:{
|
||||
Here the extra data like if we include image,etc optional data from firebase cloud messaging
|
||||
}
|
||||
}
|
||||
|
||||
For sending Push notification go to Grow and then cloud messaging, from there send new message by adding title
|
||||
and other fields as per requirement
|
||||
|
||||
*/
|
||||
// Request permission (iOS) and listen for messages.
|
||||
await _firebaseMessaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
setState(() {
|
||||
title = message.notification?.title ?? title;
|
||||
messageData = message.notification?.body ?? messageData;
|
||||
notification(context, title, messageData);
|
||||
});
|
||||
});
|
||||
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
|
||||
setState(() {
|
||||
title = message.notification?.title ?? title;
|
||||
messageData = message.notification?.body ?? messageData;
|
||||
notification(context, title, messageData);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Push Notification Demo'),
|
||||
backgroundColor: Colors.green,
|
||||
centerTitle: true,
|
||||
),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 30.0),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
SizedBox(
|
||||
height: 20.0,
|
||||
),
|
||||
Text(
|
||||
messageData,
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// this function will be called when a push notification is recieved and show as alert dialog along with
|
||||
// title and message body
|
||||
Future notification(
|
||||
BuildContext context, String title, String messageText) async {
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
buttonPadding: const EdgeInsets.all(10.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20.0)),
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold, fontSize: 20.0),
|
||||
),
|
||||
const SizedBox(
|
||||
height: 15.0,
|
||||
),
|
||||
Text(
|
||||
messageText,
|
||||
style: const TextStyle(fontSize: 16.0),
|
||||
)
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Ok'))
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -14,132 +17,7 @@ class MyApp extends StatelessWidget {
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.blue,
|
||||
),
|
||||
home: MyHomePage(),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyHomePage extends StatefulWidget {
|
||||
const MyHomePage({super.key});
|
||||
|
||||
@override
|
||||
_MyHomePageState createState() => _MyHomePageState();
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
String title = "Title will appear here";
|
||||
String messageData = "Message text will appear here";
|
||||
|
||||
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
|
||||
|
||||
@override
|
||||
Future<void> initState() async {
|
||||
super.initState();
|
||||
|
||||
/*
|
||||
Message that we are getting from firebase will be of form:-
|
||||
{
|
||||
notification:{
|
||||
title:'Custom Title that we send from firebase cloud messaging',
|
||||
body:'Text of the message will appear here'
|
||||
},
|
||||
data:{
|
||||
Here the extra data like if we include image,etc optional data from firebase cloud messaging
|
||||
}
|
||||
}
|
||||
|
||||
For sending Push notification go to Grow and then cloud messaging, from there send new message by adding title
|
||||
and other fields as per requirement
|
||||
|
||||
*/
|
||||
// Request permission (iOS) and listen for messages.
|
||||
await _firebaseMessaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
setState(() {
|
||||
title = message.notification?.title ?? title;
|
||||
messageData = message.notification?.body ?? messageData;
|
||||
notification(context, title, messageData);
|
||||
});
|
||||
});
|
||||
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
|
||||
setState(() {
|
||||
title = message.notification?.title ?? title;
|
||||
messageData = message.notification?.body ?? messageData;
|
||||
notification(context, title, messageData);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Push Notification Demo'),
|
||||
backgroundColor: Colors.green,
|
||||
centerTitle: true,
|
||||
),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 30.0),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
SizedBox(
|
||||
height: 20.0,
|
||||
),
|
||||
Text(
|
||||
messageData,
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// this function will be called when a push notification is recieved and show as alert dialog along with
|
||||
// title and message body
|
||||
Future notification(
|
||||
BuildContext context, String title, String messageText) async {
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
buttonPadding: EdgeInsets.all(10.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20.0)),
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
|
||||
),
|
||||
SizedBox(
|
||||
height: 15.0,
|
||||
),
|
||||
Text(
|
||||
messageText,
|
||||
style: TextStyle(fontSize: 16.0),
|
||||
)
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context), child: Text('Ok'))
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
38
sliver_app_bar_example/lib/example.dart
Normal file
38
sliver_app_bar_example/lib/example.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: a collapsing SliverAppBar over a scrolling list of items.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
// This widget is the root of your application.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: NestedScrollView(
|
||||
floatHeaderSlivers: true,
|
||||
headerSliverBuilder: (context, innerBoxIsScrolled) => [
|
||||
const SliverAppBar(
|
||||
expandedHeight: 240,
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
title: Text('Sliver App Bar Demo'),
|
||||
background: Image(
|
||||
image: AssetImage('assets/sample.jpg'),
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
floating: true,
|
||||
),
|
||||
],
|
||||
body: ListView.separated(
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: 30,
|
||||
itemBuilder: (context, index) => ListTile(
|
||||
title: Text('Item $index'),
|
||||
),
|
||||
separatorBuilder: (context, index) => const SizedBox(
|
||||
height: 10,
|
||||
)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(const MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -13,32 +17,6 @@ class MyApp extends StatelessWidget {
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.blue,
|
||||
),
|
||||
home: Scaffold(
|
||||
body: NestedScrollView(
|
||||
floatHeaderSlivers: true,
|
||||
headerSliverBuilder: (context, innerBoxIsScrolled) => [
|
||||
const SliverAppBar(
|
||||
expandedHeight: 240,
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
title: Text('Sliver App Bar Demo'),
|
||||
background: Image(
|
||||
image: AssetImage('assets/sample.jpg'),
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
floating: true,
|
||||
),
|
||||
],
|
||||
body: ListView.separated(
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: 30,
|
||||
itemBuilder: (context, index) => ListTile(
|
||||
title: Text('Item $index'),
|
||||
),
|
||||
separatorBuilder: (context, index) => const SizedBox(
|
||||
height: 10,
|
||||
)),
|
||||
),
|
||||
));
|
||||
home: const Example());
|
||||
}
|
||||
}
|
||||
|
||||
87
stateless_widgets/lib/example.dart
Normal file
87
stateless_widgets/lib/example.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: build a layout from reusable stateless widgets.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Declare some constants
|
||||
final double myTextSize = 30.0;
|
||||
final double myIconSize = 40.0;
|
||||
final TextStyle myTextStyle =
|
||||
TextStyle(color: Colors.grey, fontSize: myTextSize);
|
||||
|
||||
var column = Column(
|
||||
// Makes the cards stretch in horizontal axis
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
// Setup the card
|
||||
MyCard(
|
||||
// Setup the text
|
||||
title: Text(
|
||||
"Favorite",
|
||||
style: myTextStyle,
|
||||
),
|
||||
// Setup the icon
|
||||
icon: Icon(Icons.favorite, size: myIconSize, color: Colors.red)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Alarm",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.alarm, size: myIconSize, color: Colors.blue)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Airport Shuttle",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.airport_shuttle,
|
||||
size: myIconSize, color: Colors.amber)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Done",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.done, size: myIconSize, color: Colors.green)),
|
||||
],
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Stateless Widget"),
|
||||
),
|
||||
body: Container(
|
||||
// Sets the padding in the main container
|
||||
padding: const EdgeInsets.only(bottom: 2.0),
|
||||
child: Center(
|
||||
child: SingleChildScrollView(child: column),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a reusable stateless widget
|
||||
class MyCard extends StatelessWidget {
|
||||
final Widget icon;
|
||||
final Widget title;
|
||||
|
||||
// Constructor. {} here denote that they are optional values i.e you can use as: MyCard()
|
||||
const MyCard({super.key, required this.title, required this.icon});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.only(bottom: 1.0),
|
||||
child: Card(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Column(
|
||||
children: <Widget>[title, icon],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyApp(),
|
||||
// Define the theme, set the primary swatch
|
||||
theme: ThemeData(primarySwatch: Colors.green),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
@@ -13,82 +11,11 @@ class MyApp extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Declare some constants
|
||||
final double myTextSize = 30.0;
|
||||
final double myIconSize = 40.0;
|
||||
final TextStyle myTextStyle =
|
||||
TextStyle(color: Colors.grey, fontSize: myTextSize);
|
||||
|
||||
var column = Column(
|
||||
// Makes the cards stretch in horizontal axis
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
// Setup the card
|
||||
MyCard(
|
||||
// Setup the text
|
||||
title: Text(
|
||||
"Favorite",
|
||||
style: myTextStyle,
|
||||
),
|
||||
// Setup the icon
|
||||
icon: Icon(Icons.favorite, size: myIconSize, color: Colors.red)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Alarm",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.alarm, size: myIconSize, color: Colors.blue)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Airport Shuttle",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.airport_shuttle,
|
||||
size: myIconSize, color: Colors.amber)),
|
||||
MyCard(
|
||||
title: Text(
|
||||
"Done",
|
||||
style: myTextStyle,
|
||||
),
|
||||
icon: Icon(Icons.done, size: myIconSize, color: Colors.green)),
|
||||
],
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Stateless Widget"),
|
||||
),
|
||||
body: Container(
|
||||
// Sets the padding in the main container
|
||||
padding: const EdgeInsets.only(bottom: 2.0),
|
||||
child: Center(
|
||||
child: SingleChildScrollView(child: column),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a reusable stateless widget
|
||||
class MyCard extends StatelessWidget {
|
||||
final Widget icon;
|
||||
final Widget title;
|
||||
|
||||
// Constructor. {} here denote that they are optional values i.e you can use as: MyCard()
|
||||
const MyCard({super.key, required this.title, required this.icon});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.only(bottom: 1.0),
|
||||
child: Card(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Column(
|
||||
children: <Widget>[title, icon],
|
||||
),
|
||||
),
|
||||
),
|
||||
return MaterialApp(
|
||||
title: "Stateless Widget",
|
||||
// Define the theme, set the primary swatch
|
||||
theme: ThemeData(primarySwatch: Colors.green),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
304
tic_tac_toe/lib/example.dart
Normal file
304
tic_tac_toe/lib/example.dart
Normal file
@@ -0,0 +1,304 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sizer/sizer.dart';
|
||||
|
||||
// Example: a two-player Tic Tac Toe game with score tracking.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
// declarations
|
||||
bool oTurn = true;
|
||||
|
||||
// 1st player is O
|
||||
List<String> displayElement = ['', '', '', '', '', '', '', '', ''];
|
||||
int oScore = 0;
|
||||
int xScore = 0;
|
||||
int filledBoxes = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SafeArea(
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.indigo[900],
|
||||
body: Column(
|
||||
children: <Widget>[
|
||||
SingleChildScrollView(
|
||||
child: SizedBox(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'Player X',
|
||||
style: TextStyle(
|
||||
fontSize: 20.sp,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white),
|
||||
),
|
||||
SizedBox(height: 5.h),
|
||||
Text(
|
||||
xScore.toString(),
|
||||
style:
|
||||
TextStyle(fontSize: 20.sp, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'Player 0',
|
||||
style: TextStyle(
|
||||
fontSize: 20.sp,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white),
|
||||
),
|
||||
SizedBox(height: 5.h),
|
||||
Text(
|
||||
oScore.toString(),
|
||||
style:
|
||||
TextStyle(fontSize: 20.sp, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
/////////////////////////////////
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: GridView.builder(
|
||||
itemCount: 9,
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 3),
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
_tapped(index);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10.0),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.white),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
blurRadius: 25.0,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Container(
|
||||
color: Colors.white,
|
||||
child: Center(
|
||||
child: Text(
|
||||
displayElement[index],
|
||||
style: TextStyle(
|
||||
color: displayElement[index] == 'O'
|
||||
? Colors.red
|
||||
: Colors.green,
|
||||
fontSize: 35.sp,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
// Button for Clearing the Enter board
|
||||
// as well as Scoreboard to start allover again
|
||||
|
||||
child: SizedBox(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.redAccent,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
onPressed: _clearScoreBoard,
|
||||
child: const Text("Clear Score Board"),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/////////////////////////////functions
|
||||
// filling the boxes when tapped with X
|
||||
// or O respectively and then checking the winner function
|
||||
void _tapped(int index) {
|
||||
setState(() {
|
||||
if (oTurn && displayElement[index] == '') {
|
||||
displayElement[index] = 'O';
|
||||
|
||||
filledBoxes++;
|
||||
} else if (!oTurn && displayElement[index] == '') {
|
||||
displayElement[index] = 'X';
|
||||
|
||||
filledBoxes++;
|
||||
}
|
||||
oTurn = !oTurn;
|
||||
_checkWinner();
|
||||
});
|
||||
}
|
||||
|
||||
void _checkWinner() {
|
||||
// Checking rows
|
||||
if (displayElement[0] == displayElement[1] &&
|
||||
displayElement[0] == displayElement[2] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[3] == displayElement[4] &&
|
||||
displayElement[3] == displayElement[5] &&
|
||||
displayElement[3] != '') {
|
||||
showWinSnackBar(displayElement[3]);
|
||||
}
|
||||
if (displayElement[6] == displayElement[7] &&
|
||||
displayElement[6] == displayElement[8] &&
|
||||
displayElement[6] != '') {
|
||||
showWinSnackBar(displayElement[6]);
|
||||
}
|
||||
|
||||
// Checking Column
|
||||
if (displayElement[0] == displayElement[3] &&
|
||||
displayElement[0] == displayElement[6] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[1] == displayElement[4] &&
|
||||
displayElement[1] == displayElement[7] &&
|
||||
displayElement[1] != '') {
|
||||
showWinSnackBar(displayElement[1]);
|
||||
}
|
||||
if (displayElement[2] == displayElement[5] &&
|
||||
displayElement[2] == displayElement[8] &&
|
||||
displayElement[2] != '') {
|
||||
showWinSnackBar(displayElement[2]);
|
||||
}
|
||||
|
||||
// Checking Diagonal
|
||||
if (displayElement[0] == displayElement[4] &&
|
||||
displayElement[0] == displayElement[8] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[2] == displayElement[4] &&
|
||||
displayElement[2] == displayElement[6] &&
|
||||
displayElement[2] != '') {
|
||||
showWinSnackBar(displayElement[2]);
|
||||
} else if (filledBoxes == 9) {
|
||||
showDrawSnackBar();
|
||||
}
|
||||
}
|
||||
|
||||
void showWinSnackBar(String winner) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
duration: const Duration(seconds: 20),
|
||||
content: Container(
|
||||
margin: const EdgeInsets.fromLTRB(0, 0, 0, 75),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(width: 2.0, color: Colors.black),
|
||||
borderRadius: BorderRadius.circular(20)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
"\" $winner \" is Winner!!!",
|
||||
style: const TextStyle(fontSize: 25),
|
||||
),
|
||||
),
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 1000,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
action: SnackBarAction(
|
||||
label: 'Play again',
|
||||
onPressed: () {
|
||||
_clearBoard();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
if (winner == 'O') {
|
||||
oScore++;
|
||||
} else if (winner == 'X') {
|
||||
xScore++;
|
||||
}
|
||||
}
|
||||
|
||||
void showDrawSnackBar() {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
duration: const Duration(seconds: 20),
|
||||
content: Container(
|
||||
margin: const EdgeInsets.fromLTRB(0, 0, 0, 75),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(width: 2.0, color: Colors.black),
|
||||
borderRadius: BorderRadius.circular(20)),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
"Draw",
|
||||
style: TextStyle(fontSize: 25),
|
||||
),
|
||||
),
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 1000,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
action: SnackBarAction(
|
||||
label: 'Play again',
|
||||
onPressed: () {
|
||||
_clearBoard();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _clearBoard() {
|
||||
setState(() {
|
||||
for (int i = 0; i < 9; i++) {
|
||||
displayElement[i] = '';
|
||||
}
|
||||
});
|
||||
|
||||
filledBoxes = 0;
|
||||
}
|
||||
|
||||
void _clearScoreBoard() {
|
||||
setState(() {
|
||||
xScore = 0;
|
||||
oScore = 0;
|
||||
for (int i = 0; i < 9; i++) {
|
||||
displayElement[i] = '';
|
||||
}
|
||||
});
|
||||
filledBoxes = 0;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sizer/sizer.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
@@ -14,309 +16,8 @@ class MyApp extends StatelessWidget {
|
||||
return Sizer(builder: (context, orientation, deviceType) {
|
||||
return const MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: HomePage(),
|
||||
home: Example(),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class HomePage extends StatefulWidget {
|
||||
const HomePage({super.key});
|
||||
|
||||
@override
|
||||
State<HomePage> createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends State<HomePage> {
|
||||
// declarations
|
||||
bool oTurn = true;
|
||||
|
||||
// 1st player is O
|
||||
List<String> displayElement = ['', '', '', '', '', '', '', '', ''];
|
||||
int oScore = 0;
|
||||
int xScore = 0;
|
||||
int filledBoxes = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SafeArea(
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.indigo[900],
|
||||
body: Column(
|
||||
children: <Widget>[
|
||||
SingleChildScrollView(
|
||||
child: SizedBox(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'Player X',
|
||||
style: TextStyle(
|
||||
fontSize: 20.sp,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white),
|
||||
),
|
||||
SizedBox(height: 5.h),
|
||||
Text(
|
||||
xScore.toString(),
|
||||
style:
|
||||
TextStyle(fontSize: 20.sp, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'Player 0',
|
||||
style: TextStyle(
|
||||
fontSize: 20.sp,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white),
|
||||
),
|
||||
SizedBox(height: 5.h),
|
||||
Text(
|
||||
oScore.toString(),
|
||||
style:
|
||||
TextStyle(fontSize: 20.sp, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
/////////////////////////////////
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: GridView.builder(
|
||||
itemCount: 9,
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 3),
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
_tapped(index);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10.0),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.white),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
blurRadius: 25.0,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Container(
|
||||
color: Colors.white,
|
||||
child: Center(
|
||||
child: Text(
|
||||
displayElement[index],
|
||||
style: TextStyle(
|
||||
color: displayElement[index] == 'O'
|
||||
? Colors.red
|
||||
: Colors.green,
|
||||
fontSize: 35.sp,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
// Button for Clearing the Enter board
|
||||
// as well as Scoreboard to start allover again
|
||||
|
||||
child: SizedBox(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.redAccent,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
onPressed: _clearScoreBoard,
|
||||
child: const Text("Clear Score Board"),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/////////////////////////////functions
|
||||
// filling the boxes when tapped with X
|
||||
// or O respectively and then checking the winner function
|
||||
void _tapped(int index) {
|
||||
setState(() {
|
||||
if (oTurn && displayElement[index] == '') {
|
||||
displayElement[index] = 'O';
|
||||
|
||||
filledBoxes++;
|
||||
} else if (!oTurn && displayElement[index] == '') {
|
||||
displayElement[index] = 'X';
|
||||
|
||||
filledBoxes++;
|
||||
}
|
||||
oTurn = !oTurn;
|
||||
_checkWinner();
|
||||
});
|
||||
}
|
||||
|
||||
void _checkWinner() {
|
||||
// Checking rows
|
||||
if (displayElement[0] == displayElement[1] &&
|
||||
displayElement[0] == displayElement[2] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[3] == displayElement[4] &&
|
||||
displayElement[3] == displayElement[5] &&
|
||||
displayElement[3] != '') {
|
||||
showWinSnackBar(displayElement[3]);
|
||||
}
|
||||
if (displayElement[6] == displayElement[7] &&
|
||||
displayElement[6] == displayElement[8] &&
|
||||
displayElement[6] != '') {
|
||||
showWinSnackBar(displayElement[6]);
|
||||
}
|
||||
|
||||
// Checking Column
|
||||
if (displayElement[0] == displayElement[3] &&
|
||||
displayElement[0] == displayElement[6] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[1] == displayElement[4] &&
|
||||
displayElement[1] == displayElement[7] &&
|
||||
displayElement[1] != '') {
|
||||
showWinSnackBar(displayElement[1]);
|
||||
}
|
||||
if (displayElement[2] == displayElement[5] &&
|
||||
displayElement[2] == displayElement[8] &&
|
||||
displayElement[2] != '') {
|
||||
showWinSnackBar(displayElement[2]);
|
||||
}
|
||||
|
||||
// Checking Diagonal
|
||||
if (displayElement[0] == displayElement[4] &&
|
||||
displayElement[0] == displayElement[8] &&
|
||||
displayElement[0] != '') {
|
||||
showWinSnackBar(displayElement[0]);
|
||||
}
|
||||
if (displayElement[2] == displayElement[4] &&
|
||||
displayElement[2] == displayElement[6] &&
|
||||
displayElement[2] != '') {
|
||||
showWinSnackBar(displayElement[2]);
|
||||
} else if (filledBoxes == 9) {
|
||||
showDrawSnackBar();
|
||||
}
|
||||
}
|
||||
|
||||
void showWinSnackBar(String winner) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
duration: const Duration(seconds: 20),
|
||||
content: Container(
|
||||
margin: const EdgeInsets.fromLTRB(0, 0, 0, 75),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(width: 2.0, color: Colors.black),
|
||||
borderRadius: BorderRadius.circular(20)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
"\" $winner \" is Winner!!!",
|
||||
style: const TextStyle(fontSize: 25),
|
||||
),
|
||||
),
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 1000,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
action: SnackBarAction(
|
||||
label: 'Play again',
|
||||
onPressed: () {
|
||||
_clearBoard();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
if (winner == 'O') {
|
||||
oScore++;
|
||||
} else if (winner == 'X') {
|
||||
xScore++;
|
||||
}
|
||||
}
|
||||
|
||||
void showDrawSnackBar() {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
duration: const Duration(seconds: 20),
|
||||
content: Container(
|
||||
margin: const EdgeInsets.fromLTRB(0, 0, 0, 75),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(width: 2.0, color: Colors.black),
|
||||
borderRadius: BorderRadius.circular(20)),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
"Draw",
|
||||
style: TextStyle(fontSize: 25),
|
||||
),
|
||||
),
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 1000,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
action: SnackBarAction(
|
||||
label: 'Play again',
|
||||
onPressed: () {
|
||||
_clearBoard();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _clearBoard() {
|
||||
setState(() {
|
||||
for (int i = 0; i < 9; i++) {
|
||||
displayElement[i] = '';
|
||||
}
|
||||
});
|
||||
|
||||
filledBoxes = 0;
|
||||
}
|
||||
|
||||
void _clearScoreBoard() {
|
||||
setState(() {
|
||||
xScore = 0;
|
||||
oScore = 0;
|
||||
for (int i = 0; i < 9; i++) {
|
||||
displayElement[i] = '';
|
||||
}
|
||||
});
|
||||
filledBoxes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
70
tip_calculator/lib/example.dart
Normal file
70
tip_calculator/lib/example.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: calculate the tip and total from a bill amount and tip percent.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
double billAmount = 0.0;
|
||||
double tipPercentage = 0.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Create first input field
|
||||
TextField billAmountField = TextField(
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (String value) {
|
||||
try {
|
||||
billAmount = double.parse(value);
|
||||
} catch (exception) {
|
||||
billAmount = 0.0;
|
||||
}
|
||||
},
|
||||
decoration: const InputDecoration(labelText: "Bill amount(\$)"),
|
||||
);
|
||||
|
||||
// Create another input field
|
||||
TextField tipPercentageField = TextField(
|
||||
decoration: const InputDecoration(labelText: "Tip %", hintText: "15"),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (String value) {
|
||||
try {
|
||||
tipPercentage = double.parse(value);
|
||||
} catch (exception) {
|
||||
tipPercentage = 0.0;
|
||||
}
|
||||
});
|
||||
|
||||
// Create button
|
||||
ElevatedButton calculateButton = ElevatedButton(
|
||||
child: const Text("Calculate"),
|
||||
onPressed: () {
|
||||
// Calculate tip and total
|
||||
double calculatedTip = billAmount * tipPercentage / 100.0;
|
||||
double total = billAmount + calculatedTip;
|
||||
|
||||
// Generate dialog
|
||||
AlertDialog dialog = AlertDialog(
|
||||
content: Text("Tip: \$$calculatedTip \n"
|
||||
"Total: \$$total"));
|
||||
|
||||
// Show dialog
|
||||
showDialog(
|
||||
context: context, builder: (BuildContext context) => dialog);
|
||||
});
|
||||
|
||||
Container container = Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [billAmountField, tipPercentageField, calculateButton]));
|
||||
|
||||
AppBar appBar = AppBar(title: const Text("Tip Calculator"));
|
||||
|
||||
Scaffold scaffold = Scaffold(appBar: appBar, body: container);
|
||||
return scaffold;
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(title: 'Tip Calculator', home: TipCalculator()));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class TipCalculator extends StatefulWidget {
|
||||
const TipCalculator({super.key});
|
||||
|
||||
@override
|
||||
State<TipCalculator> createState() => _TipCalculatorState();
|
||||
}
|
||||
|
||||
class _TipCalculatorState extends State<TipCalculator> {
|
||||
double billAmount = 0.0;
|
||||
double tipPercentage = 0.0;
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Create first input field
|
||||
TextField billAmountField = TextField(
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (String value) {
|
||||
try {
|
||||
billAmount = double.parse(value);
|
||||
} catch (exception) {
|
||||
billAmount = 0.0;
|
||||
}
|
||||
},
|
||||
decoration: InputDecoration(labelText: "Bill amount(\$)"),
|
||||
return MaterialApp(
|
||||
title: 'Tip Calculator',
|
||||
home: const Example(),
|
||||
);
|
||||
|
||||
// Create another input field
|
||||
TextField tipPercentageField = TextField(
|
||||
decoration: InputDecoration(labelText: "Tip %", hintText: "15"),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (String value) {
|
||||
try {
|
||||
tipPercentage = double.parse(value);
|
||||
} catch (exception) {
|
||||
tipPercentage = 0.0;
|
||||
}
|
||||
});
|
||||
|
||||
// Create button
|
||||
ElevatedButton calculateButton = ElevatedButton(
|
||||
child: Text("Calculate"),
|
||||
onPressed: () {
|
||||
// Calculate tip and total
|
||||
double calculatedTip = billAmount * tipPercentage / 100.0;
|
||||
double total = billAmount + calculatedTip;
|
||||
|
||||
// Generate dialog
|
||||
AlertDialog dialog = AlertDialog(
|
||||
content: Text("Tip: \$$calculatedTip \n"
|
||||
"Total: \$$total"));
|
||||
|
||||
// Show dialog
|
||||
showDialog(
|
||||
context: context, builder: (BuildContext context) => dialog);
|
||||
});
|
||||
|
||||
Container container = Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [billAmountField, tipPercentageField, calculateButton]));
|
||||
|
||||
AppBar appBar = AppBar(title: Text("Tip Calculator"));
|
||||
|
||||
Scaffold scaffold = Scaffold(appBar: appBar, body: container);
|
||||
return scaffold;
|
||||
}
|
||||
}
|
||||
|
||||
39
using_alert_dialog/lib/example.dart
Normal file
39
using_alert_dialog/lib/example.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: show an AlertDialog when the button is pressed.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
// Generate dialog
|
||||
AlertDialog dialog = AlertDialog(
|
||||
content: const Text(
|
||||
"Hello World!",
|
||||
style: TextStyle(fontSize: 30.0),
|
||||
));
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Using Alert Dialog"),
|
||||
),
|
||||
body: Container(
|
||||
child: Center(
|
||||
child: ElevatedButton(
|
||||
child: const Text("Hit to alert!"),
|
||||
// On press of the button
|
||||
onPressed: () {
|
||||
// Show dialog
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) => dialog);
|
||||
}),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyHome(),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyHome extends StatefulWidget {
|
||||
const MyHome({super.key});
|
||||
|
||||
@override
|
||||
MyHomeState createState() => MyHomeState();
|
||||
}
|
||||
|
||||
class MyHomeState extends State<MyHome> {
|
||||
// Generate dialog
|
||||
AlertDialog dialog = AlertDialog(
|
||||
content: Text(
|
||||
"Hello World!",
|
||||
style: TextStyle(fontSize: 30.0),
|
||||
));
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Using Alert Dialog"),
|
||||
),
|
||||
body: Container(
|
||||
child: Center(
|
||||
child: ElevatedButton(
|
||||
child: Text("Hit to alert!"),
|
||||
// On press of the button
|
||||
onPressed: () {
|
||||
// Show dialog
|
||||
showDialog(context: context, builder: (BuildContext context) => dialog);
|
||||
}),
|
||||
),
|
||||
));
|
||||
return MaterialApp(
|
||||
title: "Using Alert Dialog",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
47
using_edittext/lib/example.dart
Normal file
47
using_edittext/lib/example.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: a TextField that appends submitted lines to a result view.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
String results = "";
|
||||
|
||||
final TextEditingController controller = TextEditingController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Using EditText"),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
body: Container(
|
||||
padding: const EdgeInsets.all(10.0),
|
||||
child: Center(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
TextField(
|
||||
decoration:
|
||||
const InputDecoration(hintText: "Enter text here..."),
|
||||
onSubmitted: (String str) {
|
||||
setState(() {
|
||||
results = "$results\n$str";
|
||||
controller.text = "";
|
||||
});
|
||||
},
|
||||
controller: controller,
|
||||
),
|
||||
Text(results)
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyEditText(),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyEditText extends StatefulWidget {
|
||||
const MyEditText({super.key});
|
||||
|
||||
@override
|
||||
MyEditTextState createState() => MyEditTextState();
|
||||
}
|
||||
|
||||
class MyEditTextState extends State<MyEditText> {
|
||||
String results = "";
|
||||
|
||||
final TextEditingController controller = TextEditingController();
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Using EditText"),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
body: Container(
|
||||
padding: const EdgeInsets.all(10.0),
|
||||
child: Center(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
TextField(
|
||||
decoration: InputDecoration(hintText: "Enter text here..."),
|
||||
onSubmitted: (String str) {
|
||||
setState(() {
|
||||
results = "$results\n$str";
|
||||
controller.text = "";
|
||||
});
|
||||
},
|
||||
controller: controller,
|
||||
),
|
||||
Text(results)
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
return MaterialApp(
|
||||
title: "Using EditText",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
69
using_expansionpanel/lib/example.dart
Normal file
69
using_expansionpanel/lib/example.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: an ExpansionPanelList that reveals a description for each item.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
List<bool> isOpenList = List.filled(7, false);
|
||||
|
||||
ExpansionPanel expansionPanel(int index, String name, String description) {
|
||||
return ExpansionPanel(
|
||||
isExpanded: isOpenList[index],
|
||||
headerBuilder: (context, _) => Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
name,
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
|
||||
),
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
description,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Expansion Panel Demo"),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
child: ExpansionPanelList(
|
||||
expandedHeaderPadding: EdgeInsets.zero,
|
||||
expansionCallback: (index, isOpen) {
|
||||
setState(() {
|
||||
isOpenList[index] = !isOpen;
|
||||
});
|
||||
},
|
||||
children: [
|
||||
expansionPanel(0, "Taj Mahal",
|
||||
"Nestled on the banks of the Yamuna river, Taj Mahal was constructed by the Mughal Emperor Shah Jahan in reminiscence of his most endeared wife Mumtaz Mahal. Being shattered by the death of his beloved wife, Shah Jahan decided to construct a domicile for the entombed. The grief of this Shah Jahan led to the formation of the glorious monument of Taj mahal. This ivory-white structure is thronged by its admirers from all over the world. Taj Mahal is an epitome of love, the beauty of which is more arresting during the sunrise and on a full moon night. Being built with the skillfulness of around 20000 artizans, Taj Mahal is the pinnacle spot in the city of Agra, India."),
|
||||
expansionPanel(1, "Great Wall of China",
|
||||
"This awe-inspiring structure is a belt of around 21,196 kilometers from east to west, witnessing the highlands, landscapes, plateaus, and other charms of China. This wall was constructed to protect the Chinese Empire from the assaults and invasions of the nomadic groups. The credit for the brawniness of this archeological grandeur goes to the robust stones, bricks, soil, wood, and other materials used for its construction. This monument symbolizes the strength and dexterity of the artisans in the bygone times. Being swarmed by its admirers from every nook of the world, the Great Wall of China stands tall to inspire the generations to come."),
|
||||
expansionPanel(2, "Christ the Redeemer",
|
||||
"The statue of the God of the Christians in Brazil, has a towering height of 98 feet. Being an embodiment of the Brazilian Christianity, this wonder of the world is the most groovy structure in Rio de Janerio, Brazil. The reason behind the unconventional strength of this structure is the adoption of reinforced concrete and soapstone for its construction. You would be astounded to know that this stupendous edifice was engineered in pieces and then taken on the top of a mountain for compilation. The statue of Jesus Christ embracing the entire world is venerated not only by the Christians, but the people belonging to other religions as well."),
|
||||
expansionPanel(3, "The Colosseum",
|
||||
"The center of the Rome accommodates the spectacular structure of the largest amphitheatre in the world, a.k.a., The Colosseum. It depicts the finesse of the engineering works during the Roman Empire. This otherworldly edifice took 9 years to get completed. If we think of mastering a structure of such massive expanse with all the contemporary methods, wistfully, we would fail to meet the deadlines confronted by the adept architects of those times. This amphitheatre witnessed a plethora of capital punishments and battles, that led to the death of around 400,000 people inside this structure. This structure has been a beholder of several events, shows, contests, and much more. And Mr. Moviebuff, you would be amazed to know that the climax scene of the epic movie Gladiator was shot nowhere else than The Colosseum."),
|
||||
expansionPanel(4, "Machu Picchu",
|
||||
"Hemmed in the midst of the beauteous hillocks and glittering meadows, the Lost City of the Incas, a.k.a Machu Picchu, dates back to the 15th century. The mind-bending structure of this one of the most amazing seven wonders of the world is composed of the dry-stone walls. The preeminent structures of the Machu Picchu comprise of the Inti Watana, The Temple of the Sun, and the Room of the Three Windows. To beckon the tourists and bestow a better picture regarding the origination of this wonder, most of the structures have been revamped by the year 1976."),
|
||||
expansionPanel(5, "Chichen Itza",
|
||||
"The step-pyramid structure of Chichen Itza is a treat to the eyes of the admirers of the archeology. This historical site it tyrannized by the Temple of Kukulcan, stationed at its center. This four-sided pyra mid subsumes a total of 365 steps. Globe-trotters from miles away, travel to Mexico specially for covering one of the seven wonders of the world. This Maya City encompasses some of the most popular buildings, like The Warriors Temple, El Castillo, and the Great Ball Court. The nights of this city are illuminated by the crowd-pleasing light & sound shows."),
|
||||
expansionPanel(6, "Petra",
|
||||
"This man-made marvel was erected out of pink-colored sandstones, due to which it has been designated as the Rose City. Being established as early as 312 BC, Petra is regarded as half as old as time. Undoubtedly, Petra is one of the most treasured attractions in Jordan. This wonder of the world houses a number of tombs and temples, which are profusely revered by the wayfarers. Petra has also won a position in the Smithsonian Magazine, as one of the 28 places to see before you die. The jaw-dropping architecture of Petra will surely leave you in awe of the creators."),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
@@ -15,74 +17,7 @@ class MyApp extends StatelessWidget {
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.blue,
|
||||
),
|
||||
home: const ExpansionPanelScreen(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ExpansionPanelScreen extends StatefulWidget {
|
||||
const ExpansionPanelScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ExpansionPanelScreen> createState() => _ExpansionPanelScreenState();
|
||||
}
|
||||
|
||||
class _ExpansionPanelScreenState extends State<ExpansionPanelScreen> {
|
||||
List<bool> isOpenList = List.filled(7, false);
|
||||
|
||||
ExpansionPanel expansionPanel(int index, String name, String description) {
|
||||
return ExpansionPanel(
|
||||
isExpanded: isOpenList[index],
|
||||
headerBuilder: (context, _) => Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
name,
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
|
||||
),
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
description,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Expansion Panel Demo"),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
child: ExpansionPanelList(
|
||||
expandedHeaderPadding: EdgeInsets.zero,
|
||||
expansionCallback: (index, isOpen) {
|
||||
setState(() {
|
||||
isOpenList[index] = !isOpen;
|
||||
});
|
||||
},
|
||||
children: [
|
||||
expansionPanel(0, "Taj Mahal",
|
||||
"Nestled on the banks of the Yamuna river, Taj Mahal was constructed by the Mughal Emperor Shah Jahan in reminiscence of his most endeared wife Mumtaz Mahal. Being shattered by the death of his beloved wife, Shah Jahan decided to construct a domicile for the entombed. The grief of this Shah Jahan led to the formation of the glorious monument of Taj mahal. This ivory-white structure is thronged by its admirers from all over the world. Taj Mahal is an epitome of love, the beauty of which is more arresting during the sunrise and on a full moon night. Being built with the skillfulness of around 20000 artizans, Taj Mahal is the pinnacle spot in the city of Agra, India."),
|
||||
expansionPanel(1, "Great Wall of China",
|
||||
"This awe-inspiring structure is a belt of around 21,196 kilometers from east to west, witnessing the highlands, landscapes, plateaus, and other charms of China. This wall was constructed to protect the Chinese Empire from the assaults and invasions of the nomadic groups. The credit for the brawniness of this archeological grandeur goes to the robust stones, bricks, soil, wood, and other materials used for its construction. This monument symbolizes the strength and dexterity of the artisans in the bygone times. Being swarmed by its admirers from every nook of the world, the Great Wall of China stands tall to inspire the generations to come."),
|
||||
expansionPanel(2, "Christ the Redeemer",
|
||||
"The statue of the God of the Christians in Brazil, has a towering height of 98 feet. Being an embodiment of the Brazilian Christianity, this wonder of the world is the most groovy structure in Rio de Janerio, Brazil. The reason behind the unconventional strength of this structure is the adoption of reinforced concrete and soapstone for its construction. You would be astounded to know that this stupendous edifice was engineered in pieces and then taken on the top of a mountain for compilation. The statue of Jesus Christ embracing the entire world is venerated not only by the Christians, but the people belonging to other religions as well."),
|
||||
expansionPanel(3, "The Colosseum",
|
||||
"The center of the Rome accommodates the spectacular structure of the largest amphitheatre in the world, a.k.a., The Colosseum. It depicts the finesse of the engineering works during the Roman Empire. This otherworldly edifice took 9 years to get completed. If we think of mastering a structure of such massive expanse with all the contemporary methods, wistfully, we would fail to meet the deadlines confronted by the adept architects of those times. This amphitheatre witnessed a plethora of capital punishments and battles, that led to the death of around 400,000 people inside this structure. This structure has been a beholder of several events, shows, contests, and much more. And Mr. Moviebuff, you would be amazed to know that the climax scene of the epic movie Gladiator was shot nowhere else than The Colosseum."),
|
||||
expansionPanel(4, "Machu Picchu",
|
||||
"Hemmed in the midst of the beauteous hillocks and glittering meadows, the Lost City of the Incas, a.k.a Machu Picchu, dates back to the 15th century. The mind-bending structure of this one of the most amazing seven wonders of the world is composed of the dry-stone walls. The preeminent structures of the Machu Picchu comprise of the Inti Watana, The Temple of the Sun, and the Room of the Three Windows. To beckon the tourists and bestow a better picture regarding the origination of this wonder, most of the structures have been revamped by the year 1976."),
|
||||
expansionPanel(5, "Chichen Itza",
|
||||
"The step-pyramid structure of Chichen Itza is a treat to the eyes of the admirers of the archeology. This historical site it tyrannized by the Temple of Kukulcan, stationed at its center. This four-sided pyra mid subsumes a total of 365 steps. Globe-trotters from miles away, travel to Mexico specially for covering one of the seven wonders of the world. This Maya City encompasses some of the most popular buildings, like The Warriors Temple, El Castillo, and the Great Ball Court. The nights of this city are illuminated by the crowd-pleasing light & sound shows."),
|
||||
expansionPanel(6, "Petra",
|
||||
"This man-made marvel was erected out of pink-colored sandstones, due to which it has been designated as the Rose City. Being established as early as 312 BC, Petra is regarded as half as old as time. Undoubtedly, Petra is one of the most treasured attractions in Jordan. This wonder of the world houses a number of tombs and temples, which are profusely revered by the wayfarers. Petra has also won a position in the Smithsonian Magazine, as one of the 28 places to see before you die. The jaw-dropping architecture of Petra will surely leave you in awe of the creators."),
|
||||
],
|
||||
),
|
||||
),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
89
using_http_get/lib/example.dart
Normal file
89
using_http_get/lib/example.dart
Normal file
@@ -0,0 +1,89 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
// Example: fetch JSON data over HTTP GET and display the results in a list.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
final String url = "https://swapi.dev/api/people";
|
||||
List? data;
|
||||
|
||||
// Function to get the JSON data
|
||||
Future<String> getJSONData() async {
|
||||
var response = await http.get(
|
||||
// Encode the url
|
||||
Uri.parse(url),
|
||||
// Only accept JSON response
|
||||
headers: {"Accept": "application/json"});
|
||||
|
||||
// Logs the response body to the console
|
||||
print(response.body);
|
||||
|
||||
// To modify the state of the app, use this method
|
||||
setState(() {
|
||||
// Get the JSON data
|
||||
var dataConvertedToJSON = json.decode(response.body);
|
||||
try {
|
||||
if (dataConvertedToJSON.statusCode == 200) {
|
||||
// Extract the required part and assign it to the global variable named data
|
||||
data = dataConvertedToJSON['results'];
|
||||
}
|
||||
} catch (e) {
|
||||
print(dataConvertedToJSON.statusCode);
|
||||
}
|
||||
});
|
||||
|
||||
return "Successfull";
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Retrieve JSON Data via HTTP GET"),
|
||||
),
|
||||
// Create a Listview and load the data when available
|
||||
body: ListView.builder(
|
||||
itemCount: data == null ? 0 : data!.length,
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return Container(
|
||||
child: Center(
|
||||
child: Column(
|
||||
// Stretch the cards in horizontal axis
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Card(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(15.0),
|
||||
child: Text(
|
||||
// Read the name field value and set it in the Text widget
|
||||
data![index]['name'],
|
||||
// set some style to text
|
||||
style: const TextStyle(
|
||||
fontSize: 20.0, color: Colors.lightBlueAccent),
|
||||
),
|
||||
),
|
||||
)
|
||||
],
|
||||
)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// Call the getJSONData() method when the app initializes
|
||||
getJSONData();
|
||||
}
|
||||
}
|
||||
@@ -1,95 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:async';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'dart:convert';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
home: MyGetHttpData(),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
// Create a stateful widget
|
||||
class MyGetHttpData extends StatefulWidget {
|
||||
const MyGetHttpData({super.key});
|
||||
|
||||
@override
|
||||
MyGetHttpDataState createState() => MyGetHttpDataState();
|
||||
}
|
||||
|
||||
// Create the state for our stateful widget
|
||||
class MyGetHttpDataState extends State<MyGetHttpData> {
|
||||
final String url = "https://swapi.dev/api/people";
|
||||
List? data;
|
||||
|
||||
// Function to get the JSON data
|
||||
Future<String> getJSONData() async {
|
||||
var response = await http.get(
|
||||
// Encode the url
|
||||
Uri.parse(url),
|
||||
// Only accept JSON response
|
||||
headers: {"Accept": "application/json"});
|
||||
|
||||
// Logs the response body to the console
|
||||
print(response.body);
|
||||
|
||||
// To modify the state of the app, use this method
|
||||
setState(() {
|
||||
// Get the JSON data
|
||||
var dataConvertedToJSON = json.decode(response.body);
|
||||
try {
|
||||
if (dataConvertedToJSON.statusCode == 200) {
|
||||
// Extract the required part and assign it to the global variable named data
|
||||
data = dataConvertedToJSON['results'];
|
||||
}
|
||||
} catch (e) {
|
||||
print(dataConvertedToJSON.statusCode);
|
||||
}
|
||||
});
|
||||
|
||||
return "Successfull";
|
||||
}
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Retrieve JSON Data via HTTP GET"),
|
||||
),
|
||||
// Create a Listview and load the data when available
|
||||
body: ListView.builder(
|
||||
itemCount: data == null ? 0 : data!.length,
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return Container(
|
||||
child: Center(
|
||||
child: Column(
|
||||
// Stretch the cards in horizontal axis
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Card(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(15.0),
|
||||
child: Text(
|
||||
// Read the name field value and set it in the Text widget
|
||||
data![index]['name'],
|
||||
// set some style to text
|
||||
style: TextStyle(
|
||||
fontSize: 20.0, color: Colors.lightBlueAccent),
|
||||
),
|
||||
),
|
||||
)
|
||||
],
|
||||
)),
|
||||
);
|
||||
}),
|
||||
return MaterialApp(
|
||||
title: "Retrieve JSON Data via HTTP GET",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// Call the getJSONData() method when the app initializes
|
||||
getJSONData();
|
||||
}
|
||||
}
|
||||
|
||||
25
using_interactiveviewer/lib/example.dart
Normal file
25
using_interactiveviewer/lib/example.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: a zoomable and pannable FlutterLogo using InteractiveViewer.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Using InteractiveViewer"),
|
||||
),
|
||||
body: InteractiveViewer(
|
||||
boundaryMargin: const EdgeInsets.all(100.0),
|
||||
minScale: 0.1,
|
||||
maxScale: 1.6,
|
||||
child: const Center(
|
||||
child: FlutterLogo(
|
||||
size: 90,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
import 'example.dart';
|
||||
|
||||
void main() => runApp(const MyApp());
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@@ -9,21 +11,7 @@ class MyApp extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Using InteractiveViewer"),
|
||||
),
|
||||
body: InteractiveViewer(
|
||||
boundaryMargin: EdgeInsets.all(100.0),
|
||||
minScale: 0.1,
|
||||
maxScale: 1.6,
|
||||
child: Center(
|
||||
child: FlutterLogo(
|
||||
size: 90,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
49
using_snackbar/lib/example.dart
Normal file
49
using_snackbar/lib/example.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: show a SnackBar with an action button when the button is pressed.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("Using SnackBar"),
|
||||
),
|
||||
body: Center(
|
||||
child: MyButton(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyButton extends StatelessWidget {
|
||||
const MyButton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ElevatedButton(
|
||||
child: const Text('Show SnackBar'),
|
||||
// On pressing the raised button
|
||||
onPressed: () {
|
||||
// show snackbar
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
// set content of snackbar
|
||||
content: const Text("Hello! I am SnackBar :)"),
|
||||
// set duration
|
||||
duration: const Duration(seconds: 3),
|
||||
// set the action
|
||||
action: SnackBarAction(
|
||||
label: "Hit Me (Action)",
|
||||
onPressed: () {
|
||||
// When action button is pressed, show another snackbar
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: const Text(
|
||||
"Hello! I am shown becoz you pressed Action :)"),
|
||||
));
|
||||
}),
|
||||
));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +1,20 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(home: ContactPage(), debugShowCheckedModeBanner: false,));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class ContactPage extends StatelessWidget {
|
||||
const ContactPage({super.key});
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text("Using SnackBar"),
|
||||
),
|
||||
body: Center(
|
||||
child: MyButton(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyButton extends StatelessWidget {
|
||||
const MyButton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ElevatedButton(
|
||||
child: Text('Show SnackBar'),
|
||||
// On pressing the raised button
|
||||
onPressed: () {
|
||||
// show snackbar
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
// set content of snackbar
|
||||
content: Text("Hello! I am SnackBar :)"),
|
||||
// set duration
|
||||
duration: Duration(seconds: 3),
|
||||
// set the action
|
||||
action: SnackBarAction(
|
||||
label: "Hit Me (Action)",
|
||||
onPressed: () {
|
||||
// When action button is pressed, show another snackbar
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(
|
||||
"Hello! I am shown becoz you pressed Action :)"),
|
||||
));
|
||||
}),
|
||||
));
|
||||
},
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: "Using SnackBar",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
94
using_stepper/lib/example.dart
Normal file
94
using_stepper/lib/example.dart
Normal file
@@ -0,0 +1,94 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: a vertical Stepper with three steps and navigation controls.
|
||||
class Example extends StatefulWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
State<Example> createState() => _ExampleState();
|
||||
}
|
||||
|
||||
class _ExampleState extends State<Example> {
|
||||
// init the step to 0th position
|
||||
int current_step = 0;
|
||||
List<Step> my_steps = [
|
||||
Step(
|
||||
// Title of the Step
|
||||
title: const Text("Step 1"),
|
||||
// Content, it can be any widget here. Using basic Text for this example
|
||||
content: const Text("Hello!"),
|
||||
isActive: true),
|
||||
Step(
|
||||
title: const Text("Step 2"),
|
||||
content: const Text("World!"),
|
||||
// You can change the style of the step icon i.e number, editing, etc.
|
||||
state: StepState.editing,
|
||||
isActive: true),
|
||||
Step(
|
||||
title: const Text("Step 3"),
|
||||
content: const Text("Hello World!"),
|
||||
isActive: true),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// Appbar
|
||||
appBar: AppBar(
|
||||
// Title
|
||||
title: const Text("Using Stepper"),
|
||||
),
|
||||
// Body
|
||||
body: Container(
|
||||
child: Stepper(
|
||||
// Using a variable here for handling the currentStep
|
||||
currentStep: current_step,
|
||||
// List the steps you would like to have
|
||||
steps: my_steps,
|
||||
// Define the type of Stepper style
|
||||
// StepperType.horizontal : Horizontal Style
|
||||
// StepperType.vertical : Vertical Style
|
||||
type: StepperType.vertical,
|
||||
// Know the step that is tapped
|
||||
onStepTapped: (step) {
|
||||
// On hitting step itself, change the state and jump to that step
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// jump to the tapped step
|
||||
current_step = step;
|
||||
});
|
||||
// Log function call
|
||||
print("onStepTapped : $step");
|
||||
},
|
||||
onStepCancel: () {
|
||||
// On hitting cancel button, change the state
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// going back one step i.e subtracting 1, until its 0
|
||||
if (current_step > 0) {
|
||||
current_step = current_step - 1;
|
||||
} else {
|
||||
current_step = 0;
|
||||
}
|
||||
});
|
||||
// Log function call
|
||||
print("onStepCancel : $current_step");
|
||||
},
|
||||
// On hitting continue button, change the state
|
||||
onStepContinue: () {
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// going back one step i.e adding 1, until its the length of the step
|
||||
if (current_step < my_steps.length - 1) {
|
||||
current_step = current_step + 1;
|
||||
} else {
|
||||
current_step = 0;
|
||||
}
|
||||
});
|
||||
// Log function call
|
||||
print("onStepContinue : $current_step");
|
||||
},
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,101 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
// Title
|
||||
title: "Simple Material App",
|
||||
// Home
|
||||
home: MyHome()));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyHome extends StatefulWidget {
|
||||
const MyHome({super.key});
|
||||
|
||||
@override
|
||||
MyHomeState createState() => MyHomeState();
|
||||
}
|
||||
|
||||
class MyHomeState extends State<MyHome> {
|
||||
// init the step to 0th position
|
||||
int current_step = 0;
|
||||
List<Step> my_steps = [
|
||||
Step(
|
||||
// Title of the Step
|
||||
title: Text("Step 1"),
|
||||
// Content, it can be any widget here. Using basic Text for this example
|
||||
content: Text("Hello!"),
|
||||
isActive: true),
|
||||
Step(
|
||||
title: Text("Step 2"),
|
||||
content: Text("World!"),
|
||||
// You can change the style of the step icon i.e number, editing, etc.
|
||||
state: StepState.editing,
|
||||
isActive: true),
|
||||
Step(
|
||||
title: Text("Step 3"),
|
||||
content: Text("Hello World!"),
|
||||
isActive: true),
|
||||
];
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// Appbar
|
||||
appBar: AppBar(
|
||||
// Title
|
||||
title: Text("Simple Material App"),
|
||||
),
|
||||
// Body
|
||||
body: Container(
|
||||
child: Stepper(
|
||||
// Using a variable here for handling the currentStep
|
||||
currentStep: current_step,
|
||||
// List the steps you would like to have
|
||||
steps: my_steps,
|
||||
// Define the type of Stepper style
|
||||
// StepperType.horizontal : Horizontal Style
|
||||
// StepperType.vertical : Vertical Style
|
||||
type: StepperType.vertical,
|
||||
// Know the step that is tapped
|
||||
onStepTapped: (step) {
|
||||
// On hitting step itself, change the state and jump to that step
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// jump to the tapped step
|
||||
current_step = step;
|
||||
});
|
||||
// Log function call
|
||||
print("onStepTapped : $step");
|
||||
},
|
||||
onStepCancel: () {
|
||||
// On hitting cancel button, change the state
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// going back one step i.e subtracting 1, until its 0
|
||||
if (current_step > 0) {
|
||||
current_step = current_step - 1;
|
||||
} else {
|
||||
current_step = 0;
|
||||
}
|
||||
});
|
||||
// Log function call
|
||||
print("onStepCancel : $current_step");
|
||||
},
|
||||
// On hitting continue button, change the state
|
||||
onStepContinue: () {
|
||||
setState(() {
|
||||
// update the variable handling the current step value
|
||||
// going back one step i.e adding 1, until its the length of the step
|
||||
if (current_step < my_steps.length - 1) {
|
||||
current_step = current_step + 1;
|
||||
} else {
|
||||
current_step = 0;
|
||||
}
|
||||
});
|
||||
// Log function call
|
||||
print("onStepContinue : $current_step");
|
||||
},
|
||||
)),
|
||||
return MaterialApp(
|
||||
title: "Using Stepper",
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
45
using_theme/lib/example.dart
Normal file
45
using_theme/lib/example.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// Example: use the app theme to style widgets and override it locally.
|
||||
class Example extends StatelessWidget {
|
||||
const Example({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// AppBar
|
||||
appBar: AppBar(
|
||||
// AppBar Title
|
||||
title: const Text("Using Theme"),
|
||||
),
|
||||
body: Container(
|
||||
// Another way to set the background color
|
||||
decoration: const BoxDecoration(color: Colors.black87),
|
||||
child: Center(
|
||||
child: Container(
|
||||
// use the theme accent color as background color for this widget
|
||||
color: Theme.of(context).colorScheme.secondary,
|
||||
child: Text(
|
||||
'Hello World!',
|
||||
// Set text style as per theme
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
floatingActionButton: Theme(
|
||||
// override the accent color of theme for this widget only
|
||||
data: Theme.of(context).copyWith(
|
||||
colorScheme: Theme.of(context)
|
||||
.colorScheme
|
||||
.copyWith(secondary: Colors.pinkAccent),
|
||||
),
|
||||
child: FloatingActionButton(
|
||||
onPressed: null,
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,28 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'example.dart';
|
||||
|
||||
void main() {
|
||||
runApp(MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: MyHome(),
|
||||
// Set the theme's primary color, accent color,
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.green,
|
||||
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.green)
|
||||
.copyWith(secondary: Colors.lightGreenAccent),
|
||||
// Set background color
|
||||
scaffoldBackgroundColor: Colors.black12,
|
||||
),
|
||||
));
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyHome extends StatelessWidget {
|
||||
const MyHome({super.key});
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// AppBar
|
||||
appBar: AppBar(
|
||||
// AppBar Title
|
||||
title: Text("Using Theme"),
|
||||
),
|
||||
body: Container(
|
||||
// Another way to set the background color
|
||||
decoration: BoxDecoration(color: Colors.black87),
|
||||
child: Center(
|
||||
child: Container(
|
||||
// use the theme accent color as background color for this widget
|
||||
color: Theme.of(context).colorScheme.secondary,
|
||||
child: Text(
|
||||
'Hello World!',
|
||||
// Set text style as per theme
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
floatingActionButton: Theme(
|
||||
// override the accent color of theme for this widget only
|
||||
data: Theme.of(context).copyWith(
|
||||
colorScheme: Theme.of(context)
|
||||
.colorScheme
|
||||
.copyWith(secondary: Colors.pinkAccent),
|
||||
),
|
||||
child: FloatingActionButton(
|
||||
onPressed: null,
|
||||
child: Icon(Icons.add),
|
||||
),
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: "Using Theme",
|
||||
// Set the theme's primary color, accent color,
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.green,
|
||||
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.green)
|
||||
.copyWith(secondary: Colors.lightGreenAccent),
|
||||
// Set background color
|
||||
scaffoldBackgroundColor: Colors.black12,
|
||||
),
|
||||
home: const Example(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user