repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter-examples/animation_example | mirrored_repositories/flutter-examples/animation_example/lib/main.dart | import 'package:flutter/material.dart';
import 'home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pen Assignement',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home:HomePage(),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/animation_example | mirrored_repositories/flutter-examples/animation_example/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:penassignment/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/persist_key_value | mirrored_repositories/flutter-examples/persist_key_value/lib/main.dart | import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MaterialApp(
// Disable the debug flag
debugShowCheckedModeBanner: false,
// Home
home: MyHome()));
}
class MyHome extends StatefulWidget {
@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();
}
_loadSavedData() async {
// Get shared preference instance
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
// Get value
counter = (prefs.getInt(key) ?? 0);
});
}
_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);
}
_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',
textScaleFactor: 10.0,
),
Padding(padding: EdgeInsets.all(10.0)),
RaisedButton(
onPressed: _onIncrementHit,
child: Text('Increment Counter')),
Padding(padding: EdgeInsets.all(10.0)),
RaisedButton(
onPressed: _onDecrementHit,
child: Text('Decrement Counter')),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/persist_key_value/android | mirrored_repositories/flutter-examples/persist_key_value/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/persist_key_value/android | mirrored_repositories/flutter-examples/persist_key_value/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/GetImg.dart | import 'package:image_picker/image_picker.dart';
import 'dart:io';
GetiImg(_image)async{
var pickedFile=await ImagePicker().getImage(source: ImageSource.gallery);
if(pickedFile!=null){
_image=File(pickedFile.path);
return _image;
}
else{
return null;
}
} | 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/ApplyFilters.dart | import 'package:photofilters/photofilters.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:image/image.dart' as imageLib;
ApplyFilters(context,_image)async{
var image = imageLib.decodeImage(_image.readAsBytesSync());
image = imageLib.copyResize(image, width: 600);
String fileName=basename(_image.path);
Map imagefile = await Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new PhotoFilterSelector(
title: Text("Photo Filter Example"),
image: image,
appBarColor: Colors.greenAccent[400],
filters: presetFiltersList,
filename: fileName,
loader: Center(child: CircularProgressIndicator()),
fit: BoxFit.contain,
),
),
);
if (imagefile != null && imagefile.containsKey('image_filtered')) {
_image = imagefile['image_filtered'];
return _image;
}
else{
return null;
}
} | 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/EditImg.dart | import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
EditImg(_image)async{
var CroppedImg=await ImageCropper.cropImage(
sourcePath: _image.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
activeControlsWidgetColor: Colors.greenAccent[400],
toolbarColor: Colors.greenAccent[400],
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
)
);
if(CroppedImg!=null){
_image=CroppedImg;
return _image;
}
else
return null;
}
| 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/SaveInGallery.dart | import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';
SaveImg(_image)async{
var result=await GallerySaver.saveImage(_image.path,albumName: 'ImageEditor').then((bool success) {
success?Fluttertoast.showToast(
msg:
"Image saved in gallery/ImageEditor",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green[400],
textColor: Colors.white,
fontSize: 16.0):
Fluttertoast.showToast(
msg:
"Something went wrong try again plz!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green[400],
textColor: Colors.white,
fontSize: 16.0);
});
} | 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/HomePage.dart | import 'package:flutter/material.dart';
import 'package:image_editor/ApplyFilters.dart';
import 'package:image_editor/EditImg.dart';
import 'package:image_editor/GetImg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_editor/SaveInGallery.dart';
import 'dart:io';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _selected = false; //to check if a image is selected or not
File _image; //here we will store the selected image and apply modifications
double _ImageContainerHeight=450, _ImageContainerWidth=400;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.greenAccent[400],
title: Text('Flutter Image Editor'),
),
body: Container(
child: Column(
children: <Widget>[
Container(
height: _ImageContainerHeight,
width: _ImageContainerWidth,
child: _selected // checks if a image is selected or not
? Image.file(_image)
: Image.asset('images/cam.png')),
Row(
children: <Widget>[
Spacer(
flex: 2,
),
RaisedButton(
color: Colors.greenAccent[400],
child: Text(
'Get_Image', // to select a image from gallery
style: TextStyle(color: Colors.white),
),
onPressed: () async {
var _Ifile = await GetiImg(_image); // function called from GetImg.dart
if (_Ifile != null) {
setState(() {
_image = _Ifile;
_selected = true;
});
}
}),
Spacer(
flex: 1,
),
RaisedButton(
color: Colors.greenAccent[400],
child: Text(
'Edit Image', //to start editing the shape, size, etc of the selected image
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if (_image != null) {
var _Ifile = await EditImg(_image); // function called from EditImg.dart
if (_Ifile != null) {
setState(() {
_image = _Ifile;
});
}
} else {
Fluttertoast.showToast(
msg: "Select a image first :-(",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
}
}),
Spacer(
flex: 2,
),
],
),
Row(
children: <Widget>[
Spacer(
flex: 2,
),
RaisedButton(
color: Colors.greenAccent[400],
child: Text(
'Apply Filters', //to start apply various photo filters to the selected image
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if (_image != null) {
var _Ifile = await ApplyFilters(context, _image); // function called from ApplyFilters.dart
if (_Ifile != null) {
setState(() {
_image = _Ifile;
});
}
} else {
Fluttertoast.showToast(
msg: "Select a image first :-(",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
}
}),
Spacer(
flex: 1,
),
RaisedButton(
color: Colors.greenAccent[400],
child: Text(
'Download Editted image', //to save the edited image to gallery
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if (_image != null) {
await SaveImg(_image); // function called from SaveInGallery.dart
} else {
Fluttertoast.showToast(
msg: "Select a image first :-(",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
}
}),
Spacer(
flex: 2,
),
],
),
],
)),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/lib/main.dart | import 'package:flutter/material.dart';
import 'package:image_editor/HomePage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage()
);
}
}
| 0 |
mirrored_repositories/flutter-examples/image_editor | mirrored_repositories/flutter-examples/image_editor/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_editor/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_http_get | mirrored_repositories/flutter-examples/using_http_get/lib/main.dart | import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MaterialApp(
home: MyGetHttpData(),
));
}
// Create a stateful widget
class MyGetHttpData extends StatefulWidget {
@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.encodeFull(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: 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(
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),
),
// added padding
padding: const EdgeInsets.all(15.0),
),
)
],
)),
);
}),
);
}
@override
void initState() {
super.initState();
// Call the getJSONData() method when the app initializes
this.getJSONData();
}
}
| 0 |
mirrored_repositories/flutter-examples/using_http_get/android | mirrored_repositories/flutter-examples/using_http_get/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_http_get/android | mirrored_repositories/flutter-examples/using_http_get/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/infinite_list | mirrored_repositories/flutter-examples/infinite_list/lib/main.dart | import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Infinite List',
theme: ThemeData(
primaryColor: Colors.blue, accentColor: Colors.lightBlue),
home: RandomWords(),
);
}
}
class RandomWords extends StatefulWidget {
@override
createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _saved = Set<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]);
});
}
}
| 0 |
mirrored_repositories/flutter-examples/infinite_list/android | mirrored_repositories/flutter-examples/infinite_list/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/infinite_list/android | mirrored_repositories/flutter-examples/infinite_list/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/scan_qr_code | mirrored_repositories/flutter-examples/scan_qr_code/lib/main.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:scan_qr_code/utils/qr_code_scanner.dart';
import 'package:scan_qr_code/utils/scanner_box_border_painter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Code Scanner',
home: MyHomePage(title: 'Code Scanner Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final MobileScannerController _mobileScannerController = MobileScannerController();
late Function(Barcode barcode, MobileScannerArguments? args) _onDetect;
bool _isScanning = true;
@override
void initState() {
super.initState();
_onDetect = (Barcode barcode, MobileScannerArguments? args) {
_mobileScannerController.stop();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Code info'),
content: Text(barcode.rawValue?.trim() ?? 'No data found', textAlign: TextAlign.center),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
);
}).then((value) {
_mobileScannerController.start();
setState(() {
_isScanning = true;
});
});
setState(() {
_isScanning = false;
});
};
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: SizedBox.square(
dimension: MediaQuery.of(context).size.width - 48.0,
child: Padding(
padding: const EdgeInsets.all(2.5), // Required otherwise side edges hides under outside padding
child: CustomPaint(
foregroundPainter: ScannerBoxBorderPainter(borderColor: _isScanning ? Colors.black : Colors.green),
child: Padding(
padding: const EdgeInsets.all(2.5), // Required otherwise scanner hides under side edges
child: QRCodeScanner(mobileScannerController: _mobileScannerController, allowDuplicates: false, onDetect: _onDetect),
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/scan_qr_code/lib | mirrored_repositories/flutter-examples/scan_qr_code/lib/utils/qr_code_scanner.dart | import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
class QRCodeScanner extends StatelessWidget {
final MobileScannerController mobileScannerController;
final bool allowDuplicates;
final Function(Barcode barcode, MobileScannerArguments? args) onDetect;
const QRCodeScanner({Key? key, required this.mobileScannerController,required this.allowDuplicates, required this.onDetect}) : super(key: key);
@override
Widget build(BuildContext context) {
return MobileScanner(
allowDuplicates: allowDuplicates,
controller: mobileScannerController,
onDetect: onDetect,
);
}
}
| 0 |
mirrored_repositories/flutter-examples/scan_qr_code/lib | mirrored_repositories/flutter-examples/scan_qr_code/lib/utils/scanner_box_border_painter.dart | import 'package:flutter/material.dart';
class ScannerBoxBorderPainter extends CustomPainter {
final Color borderColor;
ScannerBoxBorderPainter({required this.borderColor});
@override
void paint(Canvas canvas, Size size) {
double sh = size.height; // for convenient shortage
double sw = size.width; // for convenient shortage
double cornerSide = 78.0; // desirable value for corners side
Paint paint = Paint()
..color = borderColor
..strokeWidth = 5
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.square;
Path path = Path()
..moveTo(cornerSide, 0)
..lineTo(0, 0)
..lineTo(0, cornerSide)
..moveTo(0, sh - cornerSide)
..lineTo(0, sh)
..lineTo(cornerSide, sh)
..moveTo(sw - cornerSide, sh)
..lineTo(sw, sh)
..lineTo(sw, sh - cornerSide)
..moveTo(sw, cornerSide)
..lineTo(sw, 0)
..lineTo(sw - cornerSide, 0)
..moveTo(cornerSide, 0);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(ScannerBoxBorderPainter oldDelegate) => false;
@override
bool shouldRebuildSemantics(ScannerBoxBorderPainter oldDelegate) => false;
}
| 0 |
mirrored_repositories/flutter-examples/scan_qr_code | mirrored_repositories/flutter-examples/scan_qr_code/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:scan_qr_code/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app | mirrored_repositories/flutter-examples/lunch_app/lib/main.dart | import 'package:flutter/material.dart';
import 'package:lunch_app/views/prototype/food_detail_view.dart';
import 'views/prototype/home.dart';
void main() => runApp(LunchApp());
class LunchApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
iconTheme: IconThemeData(
color: Colors.white,
),
appBarTheme: AppBarTheme(
elevation: 0,
backgroundColor: Colors.transparent,
titleTextStyle: TextStyle(
color: Colors.black,
),
),
),
home: Home(),
// home: FoodDetailView(),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/food_detail_view.dart | import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:lunch_app/views/prototype/widgets/carousel_indicator.dart';
class FoodDetailView extends StatefulWidget {
@override
_FoodDetailViewState createState() => _FoodDetailViewState();
}
class _FoodDetailViewState extends State<FoodDetailView> {
int _currentPage;
@override
void initState() {
super.initState();
_currentPage = 0;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text("Deals of the week"),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
onPageChanged: (i) {
setState(() {
_currentPage = i;
});
},
itemBuilder: (c, i) {
return Image.asset(
"assets/images/burger.png",
fit: BoxFit.contain,
);
},
),
),
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, bottom: 25),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CarouselIndicator(length: 3, selected: _currentPage),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Delicious Burger",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 50,
color: Colors.white,
),
),
const SizedBox(height: 5),
Text(
"Who doesn't love a big,\ntender, juicy burger?",
style:
TextStyle(color: Colors.grey.shade300, height: 1.5),
),
const SizedBox(height: 15),
],
),
Container(
height: 50,
width: MediaQuery.of(context).size.width / 1.5,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(8)),
child: Center(
child: Text(
"Get Started",
style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/home.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lunch_app/views/prototype/widgets/category_selector.dart';
import 'package:lunch_app/views/prototype/widgets/food_lister.dart';
import 'package:lunch_app/views/prototype/widgets/options_selector.dart';
import 'bottom_nav/bottom_nav.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: SvgPicture.asset(
"assets/nav/drawer.svg",
width: 25,
color: Colors.black.withOpacity(0.7),
),
),
),
body: Column(
children: [
Expanded(
child: ListView(
children: [
OptionsSelector(
onChange: (x) {},
),
CategorySelector(
onChange: (cat) {},
),
FoodLister(),
],
),
),
BottomNav(),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/widgets/category_selector.dart | import 'package:flutter/material.dart';
import 'package:lunch_app/model/prototype/category.dart';
import 'package:lunch_app/views/prototype/widgets/main_btn.dart';
class CategorySelector extends StatefulWidget {
final Function(Category) onChange;
const CategorySelector({Key key, @required this.onChange}) : super(key: key);
@override
_CategorySelectorState createState() => _CategorySelectorState();
}
class _CategorySelectorState extends State<CategorySelector> {
final List<Category> categories = [
Category("All", null),
Category("Foods", Icons.local_pizza),
Category("Drinks", Icons.local_drink_sharp),
];
int _current;
@override
void initState() {
super.initState();
_current = 0;
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: List.generate(
categories.length,
(i) {
var cur = categories[i];
return Padding(
padding: (i == 0)
? const EdgeInsets.symmetric(horizontal: 15.0)
: const EdgeInsets.only(right: 15),
child: MainBtn(
onTap: () {
setState(() {
_current = i;
});
widget.onChange(categories[i]);
},
title: cur.title,
icon: cur.icon,
active: i == _current,
),
);
},
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/widgets/options_selector.dart | import 'package:flutter/material.dart';
class OptionsSelector extends StatefulWidget {
final Function(String) onChange;
const OptionsSelector({Key key, @required this.onChange}) : super(key: key);
@override
_OptionsSelectorState createState() => _OptionsSelectorState();
}
class _OptionsSelectorState extends State<OptionsSelector> {
final List<String> options = ["Offers", "Foods", "Drinks"];
int _current;
@override
void initState() {
super.initState();
_current = 0;
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.fromLTRB(15, 10, 0, 10),
child: Row(
children: List.generate(
options.length,
(i) => Padding(
padding: const EdgeInsets.only(right: 20),
child: GestureDetector(
onTap: () {
setState(() {
_current = i;
});
widget.onChange(options[i]);
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
width: 5,
color:
(i == _current) ? Colors.amber : Colors.transparent,
),
),
),
child: Text(
options[i],
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w500,
),
),
),
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/widgets/main_btn.dart | import 'package:flutter/material.dart';
class MainBtn extends StatelessWidget {
final IconData icon;
final String title;
final bool active;
final Function onTap;
const MainBtn({
Key key,
this.icon,
this.title = "All",
this.active = true,
this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: MediaQuery.of(context).size.width / 3,
minHeight: 50,
),
child: Container(
decoration: BoxDecoration(
color: active ? Colors.blueGrey : null,
borderRadius: BorderRadius.circular(10),
border: active ? null : Border.all(color: Colors.grey.shade400),
),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
(icon != null)
? Row(
children: [
Icon(
icon,
color: active ? Colors.white : Colors.grey.shade400,
),
SizedBox(width: 4),
],
)
: SizedBox(),
Text(
title,
style: TextStyle(
fontWeight: FontWeight.w400,
color: active ? Colors.white : Colors.grey.shade400,
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/widgets/food_lister.dart | import 'package:flutter/material.dart';
import 'package:lunch_app/views/prototype/food_detail_view.dart';
class FoodLister extends StatefulWidget {
@override
_FoodListerState createState() => _FoodListerState();
}
class _FoodListerState extends State<FoodLister> {
final PageController controller =
PageController(initialPage: 2, viewportFraction: 0.9);
@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.width * 0.8,
child: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: 10,
controller: controller,
itemBuilder: (c, i) {
return _ItemWidget();
},
),
);
}
}
class _ItemWidget extends StatefulWidget {
@override
__ItemWidgetState createState() => __ItemWidgetState();
}
class __ItemWidgetState extends State<_ItemWidget> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (c) => FoodDetailView()));
},
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
child: Stack(
children: [
_buildBackgroundCard(),
SizedBox(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: _buildImage(),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 10),
child: _buildDetails(),
),
),
],
),
),
],
),
),
);
}
Widget _buildBackgroundCard() {
return Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.width * 0.8 * 0.2,
),
Expanded(
child: Container(
// margin: const EdgeInsets.only(top: 40.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
border: Border.all(
color: Colors.grey.shade300,
),
),
),
),
],
);
}
Widget _buildImage() {
return Center(
child: Image.asset(
"assets/images/burger.png",
fit: BoxFit.contain,
),
);
}
Widget _buildDetails() {
return Column(
children: [
Text(
"Hello Burger",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
),
overflow: TextOverflow.ellipsis,
),
Expanded(
child: Center(
child: Text(
"An 100% beef party whipped in a soft bean and topped with onion, cheese and tomato",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.grey.shade400,
fontWeight: FontWeight.w400,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"\$3.58",
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
color: Colors.green,
),
),
const SizedBox(width: 10),
Text(
"\$5.58",
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
color: Colors.grey.shade400,
),
),
],
),
const SizedBox(height: 5),
],
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/widgets/carousel_indicator.dart | import 'package:flutter/material.dart';
class CarouselIndicator extends StatelessWidget {
final int length;
final int selected;
const CarouselIndicator(
{Key key, @required this.length, @required this.selected})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
length,
(i) {
var active = i == selected;
return Container(
height: 8,
width: 8,
decoration: BoxDecoration(
color: active ? Colors.white : Colors.white.withOpacity(0.4),
shape: BoxShape.circle,
),
margin: const EdgeInsets.only(right: 5),
);
},
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype | mirrored_repositories/flutter-examples/lunch_app/lib/views/prototype/bottom_nav/bottom_nav.dart | import 'package:flutter/material.dart';
class BottomNav extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(10),
height: 60,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(15),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Column(
children: [
Expanded(
child: Icon(Icons.home),
),
],
),
),
Container(
height: 45,
width: 45,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Icon(
Icons.link,
color: Colors.black,
),
),
Expanded(
child: Column(
children: [
Expanded(
child: Icon(
Icons.shopping_basket,
color: Colors.white.withOpacity(0.5),
),
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/lunch_app/lib/model | mirrored_repositories/flutter-examples/lunch_app/lib/model/prototype/category.dart | import 'package:flutter/cupertino.dart';
class Category {
final String title;
final IconData icon;
Category(this.title, this.icon);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Category && other.title == title && other.icon == icon;
}
@override
int get hashCode => title.hashCode ^ icon.hashCode;
}
| 0 |
mirrored_repositories/flutter-examples/using_alert_dialog | mirrored_repositories/flutter-examples/using_alert_dialog/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyHome(),
));
}
class MyHome extends StatefulWidget {
@override
MyHomeState createState() => MyHomeState();
}
class MyHomeState extends State<MyHome> {
// Generate dialog
AlertDialog dialog = AlertDialog(
content: Text(
"Hello World!",
style: TextStyle(fontSize: 30.0),
));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Using Alert Dialog"),
),
body: Container(
child: Center(
child: RaisedButton(
child: Text("Hit to alert!"),
// On press of the button
onPressed: () {
// Show dialog
showDialog(context: context, builder: (BuildContext context) => dialog);
}),
),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/using_alert_dialog/android | mirrored_repositories/flutter-examples/using_alert_dialog/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_alert_dialog/android | mirrored_repositories/flutter-examples/using_alert_dialog/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/getx_counter_app | mirrored_repositories/flutter-examples/getx_counter_app/lib/main.dart | import 'package:flutter/material.dart';
//import get package
import 'package:get/get.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: 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.headline4,
)),
],
),
),
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),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/getx_counter_app | mirrored_repositories/flutter-examples/getx_counter_app/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:getx_counter_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_custom_fonts | mirrored_repositories/flutter-examples/using_custom_fonts/lib/utils.dart | import 'package:flutter/material.dart';
TextStyle getCustomFontTextStyle() {
// text style which defines a custom font
return const TextStyle(
// set color of text
color: Colors.blueAccent,
// set the font family as defined in pubspec.yaml
fontFamily: 'Pacifico',
// set the font weight
fontWeight: FontWeight.w400,
// set the font size
fontSize: 36.0);
}
| 0 |
mirrored_repositories/flutter-examples/using_custom_fonts | mirrored_repositories/flutter-examples/using_custom_fonts/lib/main.dart | import 'package:flutter/material.dart';
import './utils.dart' as utils;
void main() {
runApp(MaterialApp(
// Title
title: "Using Custom Fonts",
// Home
home: Scaffold(
// Appbar
appBar: AppBar(
// Title
title: Text("Using Custom Fonts"),
),
// Body
body: Container(
// Center the content
child: Center(
// Add Text
child: Text("The quick brown fox jumps over the lazy dog",
// Center align text
textAlign: TextAlign.center,
// set a text style which defines a custom font
style: utils.getCustomFontTextStyle()),
),
),
)));
}
| 0 |
mirrored_repositories/flutter-examples/using_custom_fonts/android | mirrored_repositories/flutter-examples/using_custom_fonts/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_custom_fonts/android | mirrored_repositories/flutter-examples/using_custom_fonts/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner | mirrored_repositories/flutter-examples/expense_planner/lib/main.dart | import 'package:flutter/material.dart';
import './widgets/new_transaction.dart';
import './widgets/transaction_list.dart';
import './widgets/chart.dart';
import './models/transaction.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.amber,
// errorColor: Colors.red,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
button: TextStyle(color: Colors.white),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
// String titleInput;
// String amountInput;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
// Transaction(
// id: 't1',
// title: 'New Shoes',
// amount: 69.99,
// date: DateTime.now(),
// ),
// Transaction(
// id: 't2',
// title: 'Weekly Groceries',
// amount: 16.53,
// date: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime chosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: chosenDate,
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deleteTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tx) => tx.id == id);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Personal Expenses',
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
],
),
body: SingleChildScrollView(
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Chart(_recentTransactions),
TransactionList(_userTransactions, _deleteTransaction),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/widgets/user_transactions.dart | import 'package:flutter/material.dart';
import './new_transaction.dart';
import './transaction_list.dart';
import '../models/transaction.dart';
class UserTransactions extends StatefulWidget {
@override
_UserTransactionsState createState() => _UserTransactionsState();
}
class _UserTransactionsState extends State<UserTransactions> {
Function deleteTx;
final List<Transaction> _userTransactions = [
Transaction(
id: 't1',
title: 'New Shoes',
amount: 69.99,
date: DateTime.now(),
),
Transaction(
id: 't2',
title: 'Weekly Groceries',
amount: 16.53,
date: DateTime.now(),
),
];
void _addNewTransaction(String txTitle, double txAmount) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: DateTime.now(),
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
NewTransaction(_addNewTransaction),
TransactionList(_userTransactions, deleteTx()),
],
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/widgets/new_transaction.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
@override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
@override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
),
],
),
),
RaisedButton(
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
onPressed: _submitData,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/widgets/transaction_list.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
final Function deleteTx;
TransactionList(this.transactions, this.deleteTx);
@override
Widget build(BuildContext context) {
return Container(
height: 450,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.title,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.title,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
trailing: IconButton(
icon: Icon(Icons.delete),
color: Theme.of(context).errorColor,
onPressed: () => deleteTx(transactions[index].id),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/widgets/chart.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import './chart_bar.dart';
import '../models/transaction.dart';
class Chart extends StatelessWidget {
final List<Transaction> recentTransactions;
Chart(this.recentTransactions);
List<Map<String, Object>> get groupedTransactionValues {
return List.generate(7, (index) {
final weekDay = DateTime.now().subtract(
Duration(days: index),
);
var totalSum = 0.0;
for (var i = 0; i < recentTransactions.length; i++) {
if (recentTransactions[i].date.day == weekDay.day &&
recentTransactions[i].date.month == weekDay.month &&
recentTransactions[i].date.year == weekDay.year) {
totalSum += recentTransactions[i].amount;
}
}
return {
'day': DateFormat.E().format(weekDay).substring(0, 1),
'amount': totalSum,
};
}).reversed.toList();
}
double get totalSpending {
return groupedTransactionValues.fold(0.0, (sum, item) {
return sum + item['amount'];
});
}
@override
Widget build(BuildContext context) {
return Card(
elevation: 6,
margin: EdgeInsets.all(20),
child: Padding(
padding: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: groupedTransactionValues.map((data) {
return Flexible(
fit: FlexFit.tight,
child: ChartBar(
data['day'],
data['amount'],
totalSpending == 0.0
? 0.0
: (data['amount'] as double) / totalSpending,
),
);
}).toList(),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/widgets/chart_bar.dart | import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
height: 20,
child: FittedBox(
child: Text('\$${spendingAmount.toStringAsFixed(0)}'),
),
),
SizedBox(
height: 4,
),
Container(
height: 60,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
),
],
),
),
SizedBox(
height: 4,
),
Text(label),
],
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/lib | mirrored_repositories/flutter-examples/expense_planner/lib/models/transaction.dart | import 'package:flutter/foundation.dart';
class Transaction {
final String id;
final String title;
final double amount;
final DateTime date;
Transaction({
@required this.id,
@required this.title,
@required this.amount,
@required this.date,
});
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner | mirrored_repositories/flutter-examples/expense_planner/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:expense_planner/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/android | mirrored_repositories/flutter-examples/expense_planner/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/expense_planner/android | mirrored_repositories/flutter-examples/expense_planner/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_edittext | mirrored_repositories/flutter-examples/using_edittext/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyEditText(),
));
}
class MyEditText extends StatefulWidget {
@override
MyEditTextState createState() => MyEditTextState();
}
class MyEditTextState extends State<MyEditText> {
String results = "";
final TextEditingController controller = TextEditingController();
@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)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_edittext/android | mirrored_repositories/flutter-examples/using_edittext/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_edittext/android | mirrored_repositories/flutter-examples/using_edittext/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/sliver_app_bar_example | mirrored_repositories/flutter-examples/sliver_app_bar_example/lib/main.dart | import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
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,
)),
),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/main.dart | import 'package:flutter/material.dart';
import 'package:save_data_locally_with_sqlite/screens/homescreen/homescreen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/database/local_database.dart | import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class LocalDatabase {
static final _databaseName = "database.db";
static final _databaseVersion = 1;
static Database? _database;
LocalDatabase._privateConstructor();
static final LocalDatabase instance = LocalDatabase._privateConstructor();
Future<Database?> get database async {
if (_database != null)
return _database; //if database already present it return the database else create a new one then return it
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, '$_databaseName');
return await openDatabase(path, version: _databaseVersion,
onCreate: (db, int) async {
await db.execute('''
CREATE TABLE data (
datetime TEXT,
note TEXT,
timestamp TIMESTAMP
)
''');
});
}
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/database/database_queries.dart | import 'package:save_data_locally_with_sqlite/database/local_database.dart';
import 'package:sqflite/sqflite.dart';
Future<void> InsertData(String note, String datetime) async {
Database? db = await LocalDatabase.instance.database;
await db!.rawQuery('''
INSERT INTO data (datetime,note,timestamp) VALUES ('$datetime','$note',CURRENT_TIMESTAMP)
''');
}
Future<List<Map>> GetData() async {
Database? db = await LocalDatabase.instance.database;
List<Map> list = await db!.rawQuery('''
SELECT * FROM data ORDER BY timestamp DESC
''');
return list;
}
Future<void> DeleteData(String datetime) async {
Database? db = await LocalDatabase.instance.database;
await db!.rawQuery('''
DELETE FROM data WHERE datetime='$datetime'
''');
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/screens | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/screens/homescreen/homescreen.dart | import 'package:flutter/material.dart';
import 'package:save_data_locally_with_sqlite/database/database_queries.dart';
import 'package:save_data_locally_with_sqlite/screens/homescreen/widgets/note_container.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String note = '';
List<Map> notes = [];
TextEditingController textEditingController = TextEditingController();
void AddDatatoDatabase(String note) async {
String datetime =
'${DateTime.now().day}-${DateTime.now().month}-${DateTime.now().year} ${DateTime.now().hour}:${DateTime.now().minute}:${DateTime.now().second}';
await InsertData(note, datetime);
UpdateNotesList();
}
void DeleteDataFromDatabase(String datetime) async {
print(datetime);
await DeleteData(datetime);
UpdateNotesList();
}
void UpdateNotesList() async {
notes = await GetData();
print(notes);
setState(() {});
}
@override
void initState() {
super.initState();
print('init');
UpdateNotesList();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Container(
child: Text('Save Data locally using sqlite'),
),
),
body: Container(
height: double.infinity,
width: double.infinity,
color: Colors.white,
child: Column(
children: [
Container(
height: 140,
width: 350,
margin: EdgeInsets.only(top: 20),
child: Column(
children: [
Container(
child: TextField(
controller: textEditingController,
onChanged: (text) {
note = text;
},
maxLines: 2,
decoration: InputDecoration(
hintText: 'Enter Text',
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.lightBlueAccent, width: 1.0),
borderRadius:
BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.lightBlueAccent, width: 2.0),
borderRadius:
BorderRadius.all(Radius.circular(32.0)),
),
),
),
),
GestureDetector(
onTap: () {
AddDatatoDatabase(note);
textEditingController.clear();
note = '';
},
child: Container(
width: 60,
height: 30,
alignment: Alignment.center,
margin: EdgeInsets.only(top: 10),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10)),
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
),
)
],
),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return GestureDetector(
onLongPress: () {
DeleteDataFromDatabase(notes[index]['datetime']);
},
child: NoteContainer(
text: notes[index]['note'],
datetime: notes[index]['datetime'],
),
);
},
itemCount: notes.length,
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/screens/homescreen | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/lib/screens/homescreen/widgets/note_container.dart | import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
class NoteContainer extends StatelessWidget {
final String text;
final String datetime;
NoteContainer({Key? key, this.text = '', this.datetime = ''})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 7, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
boxShadow: [
BoxShadow(
color: Colors.blue.withOpacity(.4),
spreadRadius: 2.5,
blurRadius: 2.5,
)
],
color: Colors.white,
),
child: Column(
children: [
Container(
alignment: Alignment.center,
child: Text(
'$datetime',
style: TextStyle(
color: Colors.grey.shade700,
fontSize: 12,
),
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
child: Container(
padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Text(
'$text',
),
),
),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/save_data_locally_with_sqlite | mirrored_repositories/flutter-examples/save_data_locally_with_sqlite/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:save_data_locally_with_sqlite/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_snackbar | mirrored_repositories/flutter-examples/using_snackbar/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: ContactPage(), debugShowCheckedModeBanner: false,));
}
class ContactPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Using SnackBar"),
),
body: Center(
child: MyButton(),
),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
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 :)"),
));
}),
));
},
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_snackbar/android | mirrored_repositories/flutter-examples/using_snackbar/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_snackbar/android | mirrored_repositories/flutter-examples/using_snackbar/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_expansionpanel | mirrored_repositories/flutter-examples/using_expansionpanel/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Expansion Panel Demonstration App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const ExpansionPanelScreen(),
);
}
}
class ExpansionPanelScreen extends StatefulWidget {
const ExpansionPanelScreen({Key? key}) : super(key: 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."),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/load_local_json | mirrored_repositories/flutter-examples/load_local_json/lib/main.dart | import 'dart:convert';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
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 new_data = 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: " + new_data[index]['name']),
Text("Height: " + new_data[index]['height']),
Text("Mass: " + new_data[index]['mass']),
Text(
"Hair Color: " + new_data[index]['hair_color']),
Text(
"Skin Color: " + new_data[index]['skin_color']),
Text(
"Eye Color: " + new_data[index]['eye_color']),
Text(
"Birth Year: " + new_data[index]['birth_year']),
Text("Gender: " + new_data[index]['gender'])
],
),
);
},
itemCount: new_data == null ? 0 : new_data.length,
);
}),
),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/load_local_json/android | mirrored_repositories/flutter-examples/load_local_json/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/load_local_json/android | mirrored_repositories/flutter-examples/load_local_json/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/grid_layout | mirrored_repositories/flutter-examples/grid_layout/lib/gridview.dart | import 'package:flutter/material.dart';
class MyGridView {
GestureDetector getStructuredGridCell(name, image) {
// Wrap the child under GestureDetector to setup a on click action
return GestureDetector(
onTap: () {
print("onTap called.");
},
child: Card(
elevation: 1.5,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
Image(image: AssetImage('data_repo/img/' + image)),
Center(
child: Text(name),
)
],
)),
);
}
GridView build() {
return GridView.count(
primary: true,
padding: const EdgeInsets.all(1.0),
crossAxisCount: 2,
childAspectRatio: 0.85,
mainAxisSpacing: 1.0,
crossAxisSpacing: 1.0,
children: <Widget>[
getStructuredGridCell("Facebook", "social/facebook.png"),
getStructuredGridCell("Twitter", "social/twitter.png"),
getStructuredGridCell("Instagram", "social/instagram.png"),
getStructuredGridCell("Linkedin", "social/linkedin.png"),
getStructuredGridCell("Google Plus", "social/google_plus.png"),
getStructuredGridCell("Launcher Icon", "ic_launcher.png"),
],
);
}
}
| 0 |
mirrored_repositories/flutter-examples/grid_layout | mirrored_repositories/flutter-examples/grid_layout/lib/main.dart | import 'package:flutter/material.dart';
import 'package:grid_layout/gridview.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final MyGridView myGridView = MyGridView();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text("GridView Example"),
),
body: myGridView.build(),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/grid_layout/android | mirrored_repositories/flutter-examples/grid_layout/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/grid_layout/android | mirrored_repositories/flutter-examples/grid_layout/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive | mirrored_repositories/flutter-examples/using_platform_adaptive/lib/platform_adaptive.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
abstract class PlatformAdaptiveWidget extends StatelessWidget {
const PlatformAdaptiveWidget({super.key, this.forcePlatform});
final TargetPlatform? forcePlatform;
@override
Widget build(BuildContext context) {
switch (forcePlatform ?? defaultTargetPlatform) {
case TargetPlatform.iOS:
return buildIOS(context);
default:
return buildAndroid(context);
}
}
Widget buildIOS(BuildContext context);
Widget buildAndroid(BuildContext context);
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive | mirrored_repositories/flutter-examples/using_platform_adaptive/lib/main.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:using_platform_adaptive/common_widgets/adaptive_button.dart';
import 'package:using_platform_adaptive/common_widgets/adaptive_date_picker.dart';
import 'package:using_platform_adaptive/common_widgets/adaptive_indicator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Platform Adaptive',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const MyHomePage(title: 'Using Platform Adaptive'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TargetPlatform? selectedPlatform;
final String introText = "Flutter's flagship feature is it's ability to write"
" code once and have it run on multiple devices. While this is great, sometimes"
" you want the user interface to look more native to its platform. This project"
" showcases the Platform Adaptive pattern, a powerful pattern that allows you"
" to create widgets that you write once and look natural on any device. The"
" demo is just set up to work on android and iOS but can be extended to work"
" on web, native and any other platform flutter supports.";
@override
Widget build(BuildContext context) {
final platforms = {
"Default": null,
"Android": TargetPlatform.android,
"iOS": TargetPlatform.iOS,
};
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: const EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(introText),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Force a platform: "),
DropdownButton(
value: selectedPlatform,
items: List<DropdownMenuItem>.from(platforms.entries.map(
(e) => DropdownMenuItem(
value: e.value, child: Text(e.key)))),
onChanged: (value) {
setState(() {
selectedPlatform = value;
});
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Buttons: "),
AdaptiveButton(
forcePlatform: selectedPlatform,
color: Colors.teal,
onPressed: () {},
child: const Text("I'm a button"),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Dialogs: "),
AdaptiveButton(
forcePlatform: selectedPlatform,
color: Colors.teal,
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AdaptiveDialog(
title: "Test",
content: const Text("This is the content area"),
actions: [
AdaptiveDialogAction(
text: "Action 1",
forcePlatform: selectedPlatform,
onPressed: () {},
),
AdaptiveDialogAction(
text: "Action 2",
forcePlatform: selectedPlatform,
onPressed: () {},
),
],
forcePlatform: selectedPlatform,
);
});
},
child: const Text("Show"),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Loading Indicator: "),
AdaptiveIndicator(
forcePlatform: selectedPlatform,
),
],
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive/lib | mirrored_repositories/flutter-examples/using_platform_adaptive/lib/common_widgets/adaptive_indicator.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:using_platform_adaptive/platform_adaptive.dart';
class AdaptiveIndicator extends PlatformAdaptiveWidget {
const AdaptiveIndicator({super.forcePlatform, super.key});
@override
Widget buildAndroid(BuildContext context) {
return const CircularProgressIndicator();
}
@override
Widget buildIOS(BuildContext context) {
return const CupertinoActivityIndicator();
}
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive/lib | mirrored_repositories/flutter-examples/using_platform_adaptive/lib/common_widgets/adaptive_date_picker.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:using_platform_adaptive/platform_adaptive.dart';
class AdaptiveDialog extends PlatformAdaptiveWidget {
const AdaptiveDialog(
{super.key,
super.forcePlatform,
required this.title,
required this.actions,
this.content});
final String title;
final Widget? content;
final List<AdaptiveDialogAction> actions;
@override
Widget buildAndroid(BuildContext context) {
return AlertDialog(
title: Text(title),
content: content,
actions: actions,
);
}
@override
Widget buildIOS(BuildContext context) {
return CupertinoAlertDialog(
title: Text(title),
content: content,
actions: actions,
);
}
}
class AdaptiveDialogAction extends PlatformAdaptiveWidget {
const AdaptiveDialogAction(
{super.forcePlatform, this.onPressed, required this.text, super.key});
final void Function()? onPressed;
final String text;
@override
Widget buildAndroid(BuildContext context) {
return TextButton(onPressed: onPressed, child: Text(text));
}
@override
Widget buildIOS(BuildContext context) {
return CupertinoDialogAction(onPressed: onPressed, child: Text(text));
}
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive/lib | mirrored_repositories/flutter-examples/using_platform_adaptive/lib/common_widgets/adaptive_button.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:using_platform_adaptive/platform_adaptive.dart';
class AdaptiveButton extends PlatformAdaptiveWidget {
const AdaptiveButton(
{super.forcePlatform,
this.color,
required this.child,
this.onPressed,
super.key});
final void Function()? onPressed;
final Widget child;
final Color? color;
@override
Widget buildAndroid(BuildContext context) {
return MaterialButton(
onPressed: onPressed,
color: color,
child: child,
);
}
@override
Widget buildIOS(BuildContext context) {
return CupertinoButton(
onPressed: onPressed,
color: color,
child: child,
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_platform_adaptive | mirrored_repositories/flutter-examples/using_platform_adaptive/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:using_platform_adaptive/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/stateless_widgets | mirrored_repositories/flutter-examples/stateless_widgets/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
// Define the theme, set the primary swatch
theme: ThemeData(primarySwatch: Colors.green),
));
}
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()
MyCard({this.title, 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>[this.title, this.icon],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/stateless_widgets | mirrored_repositories/flutter-examples/stateless_widgets/test/widget_test.dart | // This is a basic Flutter widget test.
// To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter
// provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to
// find child widgets in the widget tree, read text, and verify that the values of widget properties
// are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../lib/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/stateless_widgets/android | mirrored_repositories/flutter-examples/stateless_widgets/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/stateless_widgets/android | mirrored_repositories/flutter-examples/stateless_widgets/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/biometrics | mirrored_repositories/flutter-examples/biometrics/lib/biometrics_verifier.dart | import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
class BiometricsVerifier {
late LocalAuthentication auth;
BiometricsVerifier() {
auth = LocalAuthentication();
}
Future<void> _ableToAuthenticate() async {
bool supported = await auth.canCheckBiometrics;
bool entryExists = await auth.isDeviceSupported();
if (!supported) throw "Device doesn't support Biometrics.";
if (!entryExists) throw "Biometric entry not found in phone.";
}
Future<void> verifyBiometrics(String? prompt) async {
await _ableToAuthenticate();
late bool didAuthenticate;
try {
didAuthenticate = await auth.authenticate(
localizedReason: prompt ?? 'Please authenticate with biometrics',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
} on PlatformException {
throw "Platform Exception : Biometrics Failed !";
}
if (!didAuthenticate) throw "Biometrics Failed";
}
}
| 0 |
mirrored_repositories/flutter-examples/biometrics | mirrored_repositories/flutter-examples/biometrics/lib/main.dart | import 'package:biometrics/biometrics_verifier.dart';
import 'package:flutter/material.dart';
void main() => runApp(Biometrics());
class Biometrics extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Biometrics',
theme: ThemeData(
appBarTheme: const AppBarTheme(elevation: 0),
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late bool isVerified;
late BiometricsVerifier verifier;
@override
void initState() {
super.initState();
isVerified = false;
verifier = BiometricsVerifier();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
isVerified ? 'Verification Complete' : 'Unverified',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
isVerified
? TextButton(
onPressed: () {
setState(() {
isVerified = false;
});
},
child: const Text('Unverify'),
)
: TextButton(
onPressed: () async {
try {
await verifier
.verifyBiometrics('Please enter your fingerprint');
// ---- Add your logic after finger print verification here
// ---
// ---
setState(() {
isVerified = true;
});
} catch (e) {
// ---- Verification Failed
showDialog(
context: context,
builder: (c) => AlertDialog(
title: const Text('Error !'),
content: Text(e.toString()),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Ok'),
)
],
),
);
}
},
child: const Text('Verify with Fingerprint'),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_firebase_db | mirrored_repositories/flutter-examples/using_firebase_db/lib/main.dart | import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class Note {
String id;
String content;
String createdOn;
Note(content) {
this.content = content;
this.createdOn = DateTime.now().toString();
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Firebase demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final notesRef = FirebaseDatabase.instance.reference().child('notes');
final inputController = TextEditingController();
StreamSubscription<Event> _noteAddedStream;
var items;
@override
void initState() {
super.initState();
items = new List();
_noteAddedStream =
notesRef.orderByChild("created_on").onChildAdded.listen(_onNoteAdded);
}
// Creates a new child under notes in the database
void _addNote() {
var note = Note(inputController.text);
inputController.text = "";
if (note.content.isNotEmpty) {
notesRef.push().set({
'content': note.content,
'created_on': note.createdOn,
});
}
}
// Fired whenever the database sees a new child under the notes
// database reference
void _onNoteAdded(Event event) {
setState(() {
var note = Note(event.snapshot.value["content"]);
note.id = event.snapshot.key;
note.createdOn = event.snapshot.value["created_on"];
items.add(note);
});
}
// The note has to be cleared from the database and the local list
void _deleteNote(int position) {
String id = items[position].id;
notesRef.child(id).remove().then((_) {
setState(() {
items.removeAt(position);
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Using Firebase DB"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.all(15.0),
child: TextField(
style: new TextStyle(
fontSize: 24.0, height: 2.0, color: Colors.black),
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Add a note'),
controller: inputController,
),
),
Expanded(
child: SizedBox(
height: 200.0,
child: ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.all(10.0),
itemBuilder: (context, position) {
return Card(
child: ListTile(
leading: Icon(Icons.note),
title: Text(items[position].content),
onLongPress: () {
_deleteNote(position);
},
),
);
}),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _addNote,
tooltip: 'Add Note',
child: Icon(Icons.add),
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/using_firebase_db | mirrored_repositories/flutter-examples/using_firebase_db/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:using_firebase_db/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/main.dart | import 'package:flutter/material.dart';
import 'screens/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Covid-19',
theme: ThemeData(
primarySwatch: Colors.blue,
accentColor: Color(0xfff4796b),
brightness: Brightness.dark,
),
home: Home(),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/widgets/graph.dart | import 'package:flutter/material.dart';
import 'package:bezier_chart/bezier_chart.dart';
// Widget that will build the graph
Widget buildGraph(
BuildContext context, List<Map<String, dynamic>> datesAndValues) {
// Data is avalaible from a particular date and we are getting that here
final fromDate = datesAndValues[0]['date'];
// Data is avalaible until a particular date and we are getting that here
final toDate = datesAndValues.last['date'];
// Add dates and values corresponding to those dates
// in a list
List<DataPoint<DateTime>> dataPoints = [];
for (final dateAndValue in datesAndValues) {
dataPoints.add(DataPoint<DateTime>(
value: double.parse(dateAndValue['value'].toString()),
xAxis: dateAndValue['date']));
}
return Center(
child: Container(
decoration: BoxDecoration(
color: Colors.red,
),
height: MediaQuery.of(context).size.height / 2,
width: MediaQuery.of(context).size.width,
child: BezierChart(
fromDate: fromDate,
bezierChartScale: BezierChartScale.WEEKLY,
toDate: toDate,
selectedDate: toDate,
series: [
BezierLine(
data: dataPoints,
),
],
config: BezierChartConfig(
physics: BouncingScrollPhysics(),
verticalIndicatorStrokeWidth: 3.0,
verticalIndicatorColor: Colors.black26,
showVerticalIndicator: true,
verticalIndicatorFixedPosition: false,
backgroundColor: Colors.transparent,
footerHeight: 30.0,
),
),
),
);
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/widgets/foldable_cell_widgets.dart | import 'package:flutter/material.dart';
import 'package:folding_cell/folding_cell.dart';
import 'package:number_display/number_display.dart';
// To display data in a width-limited component
// Eg: converts 2,000,000 to 2M
String updateNumberDisplay(String number) {
final display = createDisplay(length: 4);
// we are converting number to an integer because it is a string
// and display expects an integer
return display(int.parse(number));
}
// the front widget for the foldable cell(when cell is collapsed)
Widget buildFrontWidget(
BuildContext context, String flagUrl, String country, String cases) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: <Widget>[
Container(
child: Image.network(
flagUrl,
width: MediaQuery.of(context).size.width * 0.2,
fit: BoxFit.cover,
)),
SizedBox(
width: 20.0,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Country: $country",
),
Text("Total Cases: ${updateNumberDisplay(cases)}"),
],
),
),
],
),
);
}
// the inner top widget for the foldable cell(when cell is expanded)
Widget buildInnerTopWidget(String country, String todayCases, String deaths,
String todayDeaths, String recovered, String critical, String cpm) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
color: Color(0xfff44e3f),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
country,
style: TextStyle(fontSize: 20.0),
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Today Cases: ${updateNumberDisplay(todayCases)}",
style: TextStyle(fontSize: 18.0),
),
Text(
"Deaths: ${updateNumberDisplay(deaths)}",
style: TextStyle(fontSize: 18.0),
),
Text(
"Cases/Million: ${updateNumberDisplay(cpm)}",
style: TextStyle(fontSize: 18.0),
),
],
),
SizedBox(
width: 10.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Recovered: ${updateNumberDisplay(recovered)}",
style: TextStyle(fontSize: 18.0),
),
Text(
"Today Deaths: ${updateNumberDisplay(todayDeaths)}",
style: TextStyle(fontSize: 18.0),
),
Text(
"Critical: ${updateNumberDisplay(critical)}",
style: TextStyle(fontSize: 18.0),
),
],
),
],
),
],
),
);
}
// the inner bottom widget for the foldable cell(when cell is expanded)
Widget buildInnerBottomWidget(String cases) {
return Builder(builder: (context) {
return Container(
color: Color(0xfff44e3f),
padding: EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Expanded(
child: Text(
"Total Cases:\n${updateNumberDisplay(cases)}",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
),
)),
FlatButton(
onPressed: () {
SimpleFoldingCellState foldingCellState =
context.findAncestorStateOfType();
foldingCellState?.toggleFold();
},
child: Text(
"Close",
),
color: Colors.black,
shape: StadiumBorder(),
splashColor: Colors.white.withOpacity(0.5),
),
],
),
);
});
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/widgets/drawer.dart | import '../screens/home.dart';
import '../screens/countrylist.dart';
import 'package:flutter/material.dart';
class DrawerWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
Container(
child: Image.asset('assets/virus.gif'),
),
ListTile(
leading: CircleAvatar(
child: Image.asset("assets/logo.png"),
),
title: Text('Home'),
onTap: () {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => Home()));
},
),
ListTile(
leading: CircleAvatar(
child: Image.asset("assets/logo.png"),
),
title: Text('Affected Countries'),
onTap: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => CountryList()));
},
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/widgets/info_card.dart | import 'package:flutter/material.dart';
// this is the rounded rectangle card widget that appears on the homescreen
Widget infoCard(BuildContext context, String title, String number) {
return Card(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
),
),
SizedBox(
height: 5.0,
),
Text(
number,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
),
),
],
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40.0)),
color: Color(0xfff44e3f),
);
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/resources/fetch_data_functions.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
// function to fetch global Corona Virus(all countries together)
// to fetch data of a particular country(in this case, India)
Future getAllData() async {
try {
var allCountriesUrl = 'https://corona.lmao.ninja/v2/all';
var allCountriesResponse = await http.get(allCountriesUrl);
var particularCountryUrl = 'https://corona.lmao.ninja/v2/historical/India';
var particularCountryResponse = await http.get(particularCountryUrl);
// a list to store the data points
List<Map<String, dynamic>> dataPoints = [];
jsonDecode(particularCountryResponse.body)['timeline']['cases']
.forEach((k, v) {
List a = k.split('/');
DateTime b = DateTime(int.parse(a[2]), int.parse(a[0]), int.parse(a[1]));
dataPoints.add({"date": b, "value": v});
});
List<Map<String, dynamic>> dataPoints1 = [];
jsonDecode(particularCountryResponse.body)['timeline']['deaths']
.forEach((k, v) {
List a = k.split('/');
DateTime b = DateTime(int.parse(a[2]), int.parse(a[0]), int.parse(a[1]));
dataPoints1.add({"date": b, "value": v});
});
List<Map<String, dynamic>> dataPoints2 = [];
jsonDecode(particularCountryResponse.body)['timeline']['recovered']
.forEach((k, v) {
List a = k.split('/');
DateTime b = DateTime(int.parse(a[2]), int.parse(a[0]), int.parse(a[1]));
dataPoints2.add({"date": b, "value": v});
});
return {
"all": allCountriesResponse.body,
"country": dataPoints,
"deaths": dataPoints1,
"recovered": dataPoints2
};
} catch (e) {
print(e);
}
}
// function to fetch data of all countries(country wise)
Future getAllCountriesData() async {
try {
var url = 'https://corona.lmao.ninja/v2/countries?sort=country';
var response = await http.get(url);
return response.body;
} catch (e) {
print(e);
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/screens/searchCountry.dart | import 'package:covid19_mobile_app/widgets/foldable_cell_widgets.dart';
import 'package:flutter/material.dart';
import 'package:folding_cell/folding_cell.dart';
class CountrySearchDelegate extends SearchDelegate {
List<dynamic> results;
CountrySearchDelegate(this.results);
// to put the 'Clear Icon(X)' in the traling part of the search text field
// to clear the contents of the text field
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
)
];
}
// to put the 'Back icon(<-)' in the leading part of the search text field
// to go back
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
);
}
// to build results according to the query
// it is when the user types something and presses enter
@override
Widget buildResults(BuildContext context) {
final suggestionsList = results
.where((element) => element['country']
.toString()
.toLowerCase()
.contains(query.toLowerCase()))
.toList();
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: suggestionsList.length,
itemBuilder: (context, index) {
var _foldingCellKey = GlobalKey<SimpleFoldingCellState>();
return Container(
color: Color(0xFF2e282a),
alignment: Alignment.topCenter,
child: SimpleFoldingCell(
key: _foldingCellKey,
frontWidget: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
SimpleFoldingCellState foldingCellState =
context.findAncestorStateOfType();
foldingCellState?.toggleFold();
},
child: Container(
color: Color(0xff000000),
child: buildFrontWidget(
context,
suggestionsList[index]['countryInfo']['flag'],
suggestionsList[index]['country'],
suggestionsList[index]['cases'].toString())),
);
},
),
innerTopWidget: buildInnerTopWidget(
suggestionsList[index]['country'],
suggestionsList[index]['todayCases'].toString(),
suggestionsList[index]['deaths'].toString(),
suggestionsList[index]['todayDeaths'].toString(),
suggestionsList[index]['recovered'].toString(),
suggestionsList[index]['critical'].toString(),
suggestionsList[index]['casesPerOneMillion'].toString(),
),
innerBottomWidget: buildInnerBottomWidget(
suggestionsList[index]['cases'].toString()),
cellSize: Size(MediaQuery.of(context).size.width, 125),
padding: EdgeInsets.all(15),
animationDuration: Duration(milliseconds: 300),
borderRadius: 10,
),
);
},
);
}
// to set a placeholder for the search text field
@override
String get searchFieldLabel => 'Search Country';
// to set the theme for search bar
@override
ThemeData appBarTheme(BuildContext context) {
return ThemeData(
primaryColor: Colors.black,
textTheme: Theme.of(context).textTheme.apply(),
);
}
// to build suggestions according to the query
// it is when the user types something but does not press enter
@override
Widget buildSuggestions(BuildContext context) {
final suggestionsList = results
.where((element) => element['country']
.toString()
.toLowerCase()
.contains(query.toLowerCase()))
.toList();
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: suggestionsList.length,
itemBuilder: (context, index) {
var _foldingCellKey = GlobalKey<SimpleFoldingCellState>();
return Container(
color: Color(0xFF2e282a),
alignment: Alignment.topCenter,
child: SimpleFoldingCell(
key: _foldingCellKey,
frontWidget: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
SimpleFoldingCellState foldingCellState =
context.findAncestorStateOfType();
foldingCellState?.toggleFold();
},
child: Container(
color: Color(0xff000000),
child: buildFrontWidget(
context,
suggestionsList[index]['countryInfo']['flag'],
suggestionsList[index]['country'],
suggestionsList[index]['cases'].toString())),
);
},
),
innerTopWidget: buildInnerTopWidget(
suggestionsList[index]['country'],
suggestionsList[index]['todayCases'].toString(),
suggestionsList[index]['deaths'].toString(),
suggestionsList[index]['todayDeaths'].toString(),
suggestionsList[index]['recovered'].toString(),
suggestionsList[index]['critical'].toString(),
suggestionsList[index]['casesPerOneMillion'].toString(),
),
innerBottomWidget: buildInnerBottomWidget(
suggestionsList[index]['cases'].toString()),
cellSize: Size(MediaQuery.of(context).size.width, 125),
padding: EdgeInsets.all(15),
animationDuration: Duration(milliseconds: 300),
borderRadius: 10,
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/screens/countrylist.dart | import 'package:covid19_mobile_app/resources/fetch_data_functions.dart';
import 'package:covid19_mobile_app/widgets/foldable_cell_widgets.dart';
import '../screens/searchCountry.dart';
import '../widgets/drawer.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:folding_cell/folding_cell.dart';
class CountryList extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<dynamic> results;
return Scaffold(
drawer: DrawerWidget(),
appBar: AppBar(
title: Text("Affected Countries"),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(
context: context,
delegate: CountrySearchDelegate(results),
);
},
),
],
),
body: FutureBuilder(
future: getAllCountriesData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: CircularProgressIndicator(),
);
if (snapshot.hasError)
return Center(
child: Text("Error! please check you wifi connection"),
);
results = jsonDecode(snapshot.data);
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: results.length,
itemBuilder: (context, index) {
var _foldingCellKey = GlobalKey<SimpleFoldingCellState>();
return Container(
color: Color(0xFF2e282a),
alignment: Alignment.topCenter,
child: SimpleFoldingCell(
key: _foldingCellKey,
frontWidget: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
SimpleFoldingCellState foldingCellState =
context.findAncestorStateOfType();
foldingCellState?.toggleFold();
},
child: Container(
color: Color(0xff000000),
child: buildFrontWidget(
context,
results[index]['countryInfo']['flag'],
results[index]['country'],
results[index]['cases'].toString())),
);
},
),
innerTopWidget: buildInnerTopWidget(
results[index]['country'],
results[index]['todayCases'].toString(),
results[index]['deaths'].toString(),
results[index]['todayDeaths'].toString(),
results[index]['recovered'].toString(),
results[index]['critical'].toString(),
results[index]['casesPerOneMillion'].toString(),
),
innerBottomWidget: buildInnerBottomWidget(
results[index]['cases'].toString()),
cellSize: Size(MediaQuery.of(context).size.width, 125),
padding: EdgeInsets.all(15),
animationDuration: Duration(milliseconds: 300),
borderRadius: 10,
),
);
},
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app/lib | mirrored_repositories/flutter-examples/covid19_mobile_app/lib/screens/home.dart | import 'dart:convert';
import 'package:covid19_mobile_app/resources/fetch_data_functions.dart';
import 'package:covid19_mobile_app/widgets/graph.dart';
import 'package:covid19_mobile_app/widgets/info_card.dart';
import '../widgets/drawer.dart';
import 'package:number_display/number_display.dart';
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
final refreshKey = GlobalKey<RefreshIndicatorState>();
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: DrawerWidget(),
appBar: AppBar(
title: Text(
"World Wide Cases",
),
centerTitle: true,
),
body: RefreshIndicator(
// pull to refresh
key: refreshKey,
onRefresh: () => Navigator.pushReplacement(context,
PageRouteBuilder(pageBuilder: (context, a1, a2) => Home())),
child: FutureBuilder(
future: getAllData(),
builder: (context, snapshot) {
// Display CircularProgressIndicator if data isn't fetched yet
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
// If in case an error occurs
if (snapshot.hasError) {
return Container(
child: Center(
child: Text(
"Failed to load data. Please check you wifi connection!",
style: TextStyle(color: Colors.red),
),
),
);
}
// results of all countries(taken together)
Map<String, dynamic> globalResults =
json.decode(snapshot.data['all']);
// daily cases results
List<Map<String, dynamic>> dailyCasesResults =
(snapshot.data['country']);
// daily deaths results
List<Map<String, dynamic>> dailyDeaths =
(snapshot.data['deaths']);
// daily recoveries results
List<Map<String, dynamic>> dailyRecoveries =
(snapshot.data['recovered']);
// To display data in a width-limited component
// Eg: converts 2,000,000 to 2M
final updateNumberDisplay = createDisplay(length: 4);
return Padding(
padding:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: ListView(
physics: BouncingScrollPhysics(),
children: <Widget>[
GridView.count(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 2,
children: <Widget>[
infoCard(context, "Total Cases",
globalResults['cases'].toString()),
infoCard(context, "Deaths",
globalResults['deaths'].toString()),
infoCard(context, "Recovered",
globalResults['recovered'].toString()),
infoCard(context, "Active",
globalResults['active'].toString()),
infoCard(context, "Updated",
updateNumberDisplay(globalResults['updated'])),
infoCard(context, "Affected Countries",
globalResults['affectedCountries'].toString()),
],
),
SizedBox(
height: 25.0,
),
Text(
"Daily Cases in India",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
),
),
SizedBox(
height: 5.0,
),
buildGraph(context, dailyCasesResults),
SizedBox(
height: 25.0,
),
Text(
"Daily Deaths in India",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
),
),
SizedBox(
height: 5.0,
),
buildGraph(context, dailyDeaths),
SizedBox(
height: 25.0,
),
Text(
"Daily Recoveries in India",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
),
),
SizedBox(
height: 5.0,
),
buildGraph(context, dailyRecoveries),
],
),
);
}),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/covid19_mobile_app | mirrored_repositories/flutter-examples/covid19_mobile_app/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:covid19_mobile_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/load_local_image | mirrored_repositories/flutter-examples/load_local_image/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Load local image"),
),
body: Container(
child: Center(
child: Text(
"Hello World!",
style: TextStyle(color: Colors.white),
),
),
// Set the image as the background of the 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)),
));
}
}
| 0 |
mirrored_repositories/flutter-examples/load_local_image/android | mirrored_repositories/flutter-examples/load_local_image/android/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/flutter-examples/load_local_image/android | mirrored_repositories/flutter-examples/load_local_image/android/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:android/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-examples/using_listwheelscrollview | mirrored_repositories/flutter-examples/using_listwheelscrollview/lib/roundcontainer.dart | import 'package:flutter/material.dart';
class NewWidget extends StatelessWidget {
final Widget l;
final String s;
double radius = 8;
NewWidget({this.size, this.l, this.s});
final double size;
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: Duration(milliseconds: 1000),
curve: Curves.elasticInOut,
margin: EdgeInsets.symmetric(horizontal: 70, vertical: 20),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(20.0),
boxShadow: [
BoxShadow(
offset: Offset(5, 5),
blurRadius: radius,
color: Color(0XFF585858).withOpacity(.3),
// color: Color(0XFF383838).withOpacity(.4),
),
],
),
child: Center(
child: ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 25),
leading: l,
trailing: Text(
s,
style: TextStyle(
fontSize: 21,
color: Colors.white54,
fontWeight: FontWeight.w200),
),
),
),
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.