Snippets Collections
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:healum/utils/trackers.dart';
import 'package:intl/intl.dart';

class DataBase {
  final database = FirebaseFirestore.instance;

  isUserAdded(String uid) async {
    return (await database.collection("users").doc(uid).get()).exists;
  }

  addUser(String uid) async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    await database
        .collection('users')
        .doc(uid)
        .set((await deviceInfo.androidInfo).toMap());
  }

  pushTrackerData(
      Tracker tracker, String uid, Map<String, dynamic> trackerData) async {
    DateTime dateTime = DateTime.now();
    Map<String, dynamic> data = {
      "date_added_on": Timestamp.now(),
      "day_added_on": DateFormat('EEEE').format(dateTime)
    };
    data.addEntries(trackerData.entries);
    await database
        .collection('users')
        .doc(uid)
        .collection(tracker.key)
        .doc()
        .set(data);
  }

  getFirstTrackerData(Tracker tracker, String uid) async {
    try {
      return (await database
              .collection('users')
              .doc(uid)
              .collection(tracker.key)
              .orderBy("date_added_on", descending: true)
              .limit(1)
              .get())
          .docChanges
          .first
          .doc
          .data()['value']
          .toString();
    } catch (_) {
      return null;
    }
  }

  updateSpecificTrackerDataByTimestamp(
      Tracker tracker, String uid, Timestamp timestamp) async {
    final doc = (await database
            .collection('users')
            .doc(uid)
            .collection(tracker.key)
            .where("date_added_on", isEqualTo: timestamp)
            .limit(1)
            .get())
        .docChanges
        .first
        .doc
        .reference;
    Map existingData = (await doc.get()).data();
    print(existingData);
    existingData['value'] = tracker.value;
    var batch = database.batch();
    batch.update(doc, existingData);
    await batch.commit();
  }

  Future<List> getAllTrackerData(Tracker tracker, String uid) async {
    try {
      var snapshotList = (await database
              .collection('users')
              .doc(uid)
              .collection(tracker.key)
              .orderBy("date_added_on", descending: true)
              .get())
          .docChanges;
      List<Map<String, dynamic>> mapList =
          snapshotList.map((e) => e.doc.data()).toList();
      return mapList;
    } catch (_) {
      return null;
    }
  }
}
1. createState(): When the Framework is instructed to build a StatefulWidget, it immediately calls createState()

2. mounted is true: When createState creates your state class, a buildContext is assigned to that state. buildContext is, overly simplified, the place in the widget tree in which this widget is placed. Here's a longer explanation. All widgets have a bool this.mounted property. It is turned true when the buildContext is assigned. It is an error to call setState when a widget is unmounted.

3. initState(): This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. It must call super.initState().

4. didChangeDependencies(): This method is called immediately after initState on the first time the widget is built.

5. build(): This method is called often. It is required, and it must return a Widget.

6. didUpdateWidget(Widget oldWidget): If the parent widget changes and has to rebuild this widget (because it needs to give it different data), but it's being rebuilt with the same runtimeType, then this method is called. This is because Flutter is re-using the state, which is long lived. In this case, you may want to initialize some data again, as you would in initState.

7. setState(): This method is called often from the framework itself and from the developer. Its used to notify the framework that data has changed

8. deactivate(): Deactivate is called when State is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because State objects can be moved from one point in a tree to another.

9. dispose(): dispose() is called when the State object is removed, which is permanent. This method is where you should unsubscribe and cancel all animations, streams, etc.

10. mounted is false: The state object can never remount, and an error is thrown is setState is called.
import 'dart:isolate';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          CircularProgressIndicator(),
          ElevatedButton(
            child: Text('start'),
            onPressed: () async {

              //ReceivePort is to listen for the isolate to finish job
              final receivePort = ReceivePort();
              // here we are passing method name and sendPort instance from ReceivePort as listener
              await Isolate.spawn(
                  computationallyExpensiveTask, receivePort.sendPort);

              //It will listen for isolate function to finish
              receivePort.listen((sum) {
                print(sum);
              });
            },
          )
        ],
      ),
    );
  }
}

// this function should be either top level(outside class) or static method
void computationallyExpensiveTask(SendPort sendPort) {
  print('heavy work started');
  var sum = 0;
  for (var i = 0; i <= 1000000000; i++) {
    sum += i;
  }
  print('heavy work finished');
  //Remember there is no return, we are sending sum to listener defined defore.
  sendPort.send(sum);
}
import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  TextEditingController textarea = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Multi Line TextField"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children: [
                   TextField(
                      controller: textarea,
                      keyboardType: TextInputType.multiline,
                      maxLines: 4,
                      decoration: InputDecoration( 
                         hintText: "Enter Remarks",
                         focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(width: 1, color: Colors.redAccent)
                         )
                      ),
                       
                   ),

                   ElevatedButton(
                     onPressed: (){
                         print(textarea.text);
                     }, 
                     child: Text("Get TextField Value")
                    )
               ],
             ),
          )
      );
  }
}
class MySwitcher extends StatelessWidget {
  const MySwitcher({super.key});

  @override
  Widget build(BuildContext context) {
    final status = context.select((MyBloc bloc) => bloc.state.status);
    switch (status) {
      case MyStatus.initial:
      case MyStatus.loading:
        return const Center(child: CircularProgressIndicator());
      case MyStatus.success:
        return const MyView();
      case MyStatus.error:
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('Something went wrong.'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  context.read<MyBloc>().add(MyDataRequested());
                },
                child: const Text('Try again'),
              ),
            ],
          ),
        );
    }
  }
}
// PAGE
class MyPage extends StatelessWidget {
  const MyPage({super.key});
 
  static String path = 'my';
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Inject Bloc(s)
      body: BlocProvider(
        create: (context) => MyBloc(
          dependency: context.read<Dependency>(),
        )..add(MyDataRequested()),
        // SWITCHER
        // MySwitcher, and all its nested child Widgets, will have access to MyBloc
        child: const MySwitcher(),
      ),
    );
  }
}
class MyBloc extends Bloc<MyEvent, MyState> {
  MyBloc({required Dependency dependency})
      : _dependency = dependency,
        super(const MyState()) {
    on<MyDataRequested>(_dataRequested);
  }

  final Dependency _dependency;

  FutureOr<void> _dataRequested(
    MyDataRequested event,
    Emitter<MyState> emit,
  ) async {
    emit(state.copyWith(status: MyStatus.loading));
    try {
      final myAsyncData = await _dependency.asyncCall();
      emit(
        state.copyWith(
          myAsyncData: myAsyncData,
          status: MyStatus.success,
        ),
      );
    } catch (error, stackTrace) {
      addError(error, stackTrace);
      emit(state.copyWith(status: MyStatus.error));
    }
  }
}
enum MyStatus { initial, loading, success, error }

class MyState extends Equatable {
  const MyState({
    this.myAsyncData,
    this.status = MyStatus.initial,
  });

  final AsyncData? myAsyncData;
  final MyStatus status;

  @override
  List<Object> get props => [myAsyncData, status];

  // Creates a new state with the changed data keeping the BlocState immutable
  MyState copyWith({
    AsyncData? myAsyncData,
    MyStatus? status,
  }) {
    return MyState(
      myAsyncData: myAsyncData ?? this.myAsyncData,
      status: status ?? this.status,
    );
  }
}
// PAGE
class MyPage extends StatelessWidget {
  const MyPage({super.key});
 
  static String path = 'my';
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Inject Bloc(s)
      body: BlocProvider(
        create: (context) => MyBloc(dependency: context.read<Dependency>()),
        // VIEW
        // MyView, and all its nested child Widgets, will have access to MyBloc
        child: const MyView(),
      ),
    );
  }
}
import 'dart:ui' show ImageFilter;

import 'package:flutter/material.dart';

class BlurContainer extends StatelessWidget {
  final Widget child;
  final double? height;
  final double? width;
  final double elevation;
  final double blur;
  final EdgeInsetsGeometry padding;
  final Color color;
  final BorderRadius borderRadius;
  final String? image;
  final AlignmentGeometry? imageAlignment;

  const BlurContainer({
    Key? key,
    required this.child,
    this.height,
    this.width,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = const BorderRadius.all(Radius.circular(20)),
    this.image,
    this.imageAlignment,
  }) : super(key: key);

  const BlurContainer.square({
    Key? key,
    required this.child,
    double? dimension,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = const BorderRadius.all(Radius.circular(20)),
    this.image,
    this.imageAlignment,
  })  : width = dimension,
        height = dimension,
        super(key: key);

  const BlurContainer.expand({
    Key? key,
    required this.child,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = BorderRadius.zero,
    this.image,
    this.imageAlignment,
  })  : width = double.infinity,
        height = double.infinity,
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: elevation,
      color: Colors.transparent,
      borderRadius: borderRadius,
      child: ClipRRect(
        borderRadius: borderRadius,
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
          child: Container(
            height: height,
            width: width,
            padding: padding,
            decoration: BoxDecoration(
                color: color,
                image: image != null
                    ? DecorationImage(
                        image: AssetImage(image!),
                        alignment: imageAlignment ?? Alignment.center,
                      )
                    : null),
            child: child,
          ),
        ),
      ),
    );
  }
}
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class BlocLoggerObserver extends BlocObserver {
  @override
  void onCreate(BlocBase bloc) {
    super.onCreate(bloc);
    _log("bloc created: $bloc");
  }

  @override
  void onClose(BlocBase bloc) {
    super.onClose(bloc);
    _log("bloc closed: $bloc");
  }

  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    _log("bloc changed: $bloc, $change");
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    super.onError(bloc, error, stackTrace);
    _log("bloc error: $bloc, $error, $stackTrace");
  }

  @override
  void onEvent(Bloc bloc, Object? event) {
    super.onEvent(bloc, event);
    _log("bloc event: $bloc, $event");
  }


  void _log(message) {
    if (kDebugMode) {
      print(message);
    }
  }
}
import 'package:flutter/material.dart';

extension ImagePreloadExtention on Image {
  void preload({
    VoidCallback? onImageLoaded,
    VoidCallback? onError,
  }) {
    image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
          onImageLoaded?.call();
        }, onError: (Object exception, StackTrace? stackTrace) {
          onError?.call();
        }));
  }
}

extension PreloadImageProviderExtension on ImageProvider {
  void preload({
    VoidCallback? onImageLoaded,
    VoidCallback? onError,
  }) {
    this
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
          onImageLoaded?.call();
        }, onError: (Object exception, StackTrace? stackTrace) {
          onError?.call();
        }));
  }
}
       Image.network(
                  widget.networkUrl,
                  fit: BoxFit.fill,
                  loadingBuilder: (BuildContext context, Widget child,
                      ImageChunkEvent? loadingProgress) {
                    if (loadingProgress == null) return child;
                    return Center(
                      child: CircularProgressIndicator(
                        value: loadingProgress.expectedTotalBytes != null
                            ? loadingProgress.cumulativeBytesLoaded /
                                loadingProgress.expectedTotalBytes!
                            : null,
                      ),
                    );
                  },
                ),
BarChart(
    ...
    domainAxis: charts.OrdinalAxisSpec(
              renderSpec: charts.SmallTickRendererSpec(labelRotation: 60),
       ),
 ),
Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else ...[
          StatsScreen(),
        ],
    ],
 ),
import 'package:flutter/material.dart';

class FormValidator {
  static String? empty(
    String? value,
    String errorMessage,
  ) {
    if (value == null || value.length <= 3) {
      return 'Required';
    }
    return null;
  }

  static String? validateEmail(value) {
    bool emailValid = RegExp(
            r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(value ?? '');
    if (value == null || value.isEmpty || !emailValid) {
      return 'Please enter email';
    }
    return null;
  }

  static String? password(String? value) {
    if (empty(value, 'Required') != null) {
      return empty(value, 'Required');
    }

    RegExp regEx = RegExp(r"(?=.*[A-Z])\w+");

    if (value!.length < 8 || !regEx.hasMatch(value)) {
      return 'Please enter password';
    }

    return null;
  }

  static String? passwordConfirm(value, TextEditingController controller) {
    if (value == null || value.isEmpty) {
      return 'Required';
    }

    if (value.toString() != controller.text) {
      return 'Required';
    }

    return null;
  }
}
Container(
                      width: 200.0,
                      height: 200.0,
                      decoration: BoxDecoration(
                        color: const Color(0xff7c94b6),
                        image: DecorationImage(
                          image: NetworkImage(
                              'https://media-exp1.licdn.com/dms/image/C5603AQEzw6Dk3IPgHA/profile-displayphoto-shrink_800_800/0/1608714667178?e=1650499200&v=beta&t=LOwP7T4YXz7as8iYcmzjrtdBcAVMBUN5hGSkSgSDl-8'),
                          fit: BoxFit.cover,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(95.0)),
                        border: Border.all(
                          color: Color(0xFFe0e0e0),
                          width: 4.0,
                        ),
                      ),
                    ),
 ListTile(
              title: Text(
                'Exit',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              trailing: Icon(
                Icons.logout,
              ),
              onTap: () {
                exit(0);
              },
            ),
Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            SizedBox(
                              width: 200.0,
                              height: 25.0,
                              child: Container(
                                width: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  color: Colors.red,
                                ),
                                child: Text(
                                  categoris[index].categoryName,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontSize: 21, color: Colors.black),
                                ),
                              ),
                            ),
                          ]),
                  Text(
                    'Password',
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black26),
                    ),
                    child: TextFormField(
                      decoration: InputDecoration(
                        labelText: 'Enter Password Here',
                        labelStyle: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                        prefixIcon: Icon(Icons.lock),
                        contentPadding: EdgeInsets.all(5),
                      ),
                    ),
                  ),
        showDialog<dynamic>(
            useRootNavigator: false,
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  Utils.getString(context, 'report_item'),
                ),
                content: TextField(
                  controller: showdialogText,
                  keyboardType: TextInputType.multiline,
                  textInputAction: TextInputAction.newline,
                  minLines: 1,
                  maxLines: 5,
                  onChanged: (value) {
                    setState(() {
                      valueText = value;
                    });
                  },
                ),
                actions: <Widget>[
                  Container(
                    padding: EdgeInsets.all(5),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: ElevatedButton.icon(
                            icon: const Icon(Icons.cancel),
                            label: Text(
                              Utils.getString(context, 'cancel'),
                            ),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            style: ElevatedButton.styleFrom(
                              primary: Colors.red,
                              onPrimary: Colors.white,
                            ),
                          ),
                        ),
                        const SizedBox(width: 5),
                        Expanded(
                            flex: 1,
                            child: ElevatedButton.icon(
                              icon: const Icon(Icons.save),
                              label: Text(
                                Utils.getString(context, 'save'),
                              ),
                              onPressed: () async {
                                await PsProgressDialog.showDialog(context);
                                final UserReportItemParameterHolder userReportItemParameterHolder = UserReportItemParameterHolder(
                                  itemId: widget.itemId,
                                  reportedUserId: widget.reportedUserId,
                                  message: valueText,
                                );
                                final PsResource<ApiStatus> _apiStatus = await widget.userProvider!.userReportItem(userReportItemParameterHolder.toMap());

                                if (_apiStatus.data != null && _apiStatus.data!.status != null) {
                                  await widget.itemDetailProvider.deleteLocalProductCacheById(widget.itemId, widget.reportedUserId);
                                }

                                PsProgressDialog.dismissDialog();
                                Navigator.pushReplacementNamed(
                                  context,
                                  RoutePaths.home,
                                );
                              },
                              style: ElevatedButton.styleFrom(
                                primary: Colors.green,
                                onPrimary: Colors.white,
                              ),
                            )),
                      ],
                    ),
                  ),
                ],
              );
            });
 body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: Container(
              child: ListView.builder(
                itemCount: 10,
                itemBuilder: (context, index) => Container(
                  height: 200,
                  width: 200,
                  color: Colors.blueGrey[300],
                ),
              ),
              height: 300,
              width: 400,
            ),
          ),
        ],
      ),
Container(
                                child: Text(
                                  items[index].itemName,
                                  style: TextStyle(
                                      color: Colors.black, fontSize: 30),
                                  textAlign: TextAlign.center,
                                ), //Text
                                height: 40,
                                width: 400,
                                  decoration:
                               BoxDecoration(
                  border: Border.all(color: Colors.black38, width: 3),
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.5),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                  ],
                  color: Colors.white,
                  image: DecorationImage(
                    image: AssetImage(filterList[index].itemImg),
                    fit: BoxFit.contain,
                  ),
                ),
child: Padding(
                        padding: EdgeInsets.all(5),
                        child: Container(
                          height: 100,
                          width: 350,
                          color: Colors.amber[700],
                          child: Text(items[index].itemName), //Text
                        ),
                      ),
child: Text(
                      categoris[index].categoryName,
                      style: TextStyle(color: Colors.black, fontSize: 40),
                      textAlign: TextAlign.center,
                    ),
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
IconButton(
          onPressed: () {
            print('It was pressed');
          },
            tooltip: 'Menu Bar',
          iconSize: 40,
          icon: Icon(Icons.menu),
          color: Colors.black,
        )
 appBar: PreferredSize(
        preferredSize: Size.fromHeight(90),
        child: AppBar(
          title: Text(
            'About This App',
            style: TextStyle(fontSize: 28),
          ),
          centerTitle: true,
          backgroundColor: Color(0xffbf360c),
          elevation: 10,
          shadowColor: Color(0xff3f51b5),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(25),
              bottomRight: Radius.circular(25),
            ),
          ),
        ),
      ),
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Text_input(),
      ),
    );
body: Stack(
        children: [
          Positioned(
            bottom: 20,
            right: 10,
            height: 25,
            width: 75,
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(
                  context,
                  MaterialPageRoute(
                    builder: (builder) => Text_input(),
                  ),
                );
              },
              child: Text('Back'),
            ),
          )
        ],
      ),
 TextField(
            decoration: InputDecoration(
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20)),
                focusColor: Colors.amber,
                hintText: '@gmail.com',
                labelText: 'Your email',
                prefixIcon: Icon(Icons.account_circle_sharp)),
            onChanged: (value) {}),
hasSpecialCharacters = password.contains(new RegExp(r'[!@#$%^&*(),.?":{}|<>]')); 

  final bool isNumeric = password.contains(RegExp('[0-9]'));
  final bool isLowerCase = password.contains(RegExp("(?:[^a-z]*[a-z]){1}"));
  final bool isUpperCase = password.contains(RegExp("(?:[^A-Z]*[A-Z]){1}"));
InputDecoration(
   isDense: true,
   prefixIcon:Text("\$"),
   prefixIconConstraints: BoxConstraints(minWidth: 0, minHeight: 0),
),
RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: const <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)
RotatedBox(quarterTurns:turns,
  child: AspectRatio(
    aspectRatio: _controller.value.aspectRatio,
    child:  Stack(
      alignment: Alignment.bottomCenter,
      children: [

        VideoPlayer(_controller),
        _ControlsOverlay(controller: _controller,onClickCallback:(){
          setState(() {
            if( turns==0)
              turns=1;
            else turns=0;
          });
        }),
        VideoProgressIndicator(_controller, allowScrubbing: true),

      ],

    ),),
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}
@override
Widget build(BuildContext context) {

  return new FutureBuilder<User>(
      future: userInfo,
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) 
    {
      switch(snapshot.connectionState) {
        case ConnectionState.none:
          _showDialog(context);
          return Container();
        case ConnectionState.waiting:
          return new Center(
            child: new CircularProgressIndicator());
        case ConnectionState.active:
          return new Text('');
        case ConnectionState.done:
          if(snapshot.hasError) {
            error = snapshot.error;
            _showDialog(context);
            return Container();
          } else {
            return Container();
          }
      }
  });
import 'dart:async';
import 'dart:isolate';
main() async {
  var receivePort = new ReceivePort();
  await Isolate.spawn(echo, receivePort.sendPort);
// The 'echo' isolate sends it's SendPort as the first message
  var sendPort = await receivePort.first;
var msg = await sendReceive(sendPort, "bye");
  print('received $msg');
  msg = await sendReceive(sendPort, "hello");
  print('received $msg');
}
// the entry point for the isolate
echo(SendPort sendPort) async {
  // Open the ReceivePort for incoming messages.
  var port = new ReceivePort();
// Notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
await for (var msg in port) {
    var data = msg[0];
    SendPort replyTo = msg[1];
    replyTo.send(data);
    if (data == "hello") port.close();
  }
}
/// sends a message on a port, receives the response,
/// and returns the message
Future sendReceive(SendPort port, msg) {
  ReceivePort response = new ReceivePort();
  port.send([msg, response.sendPort]);
  return response.first;
}
TextField(
 enabled: false, // to trigger disabledBorder
 decoration: InputDecoration(
   filled: true,
   fillColor: Color(0xFFF2F2F2),
   focusedBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.red),
   ),
   disabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.orange),
   ),
   enabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.green),
   ),
   border: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,)
   ),
   errorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.black)
   ),
   focusedErrorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.yellowAccent)
   ),
   hintText: "HintText",
   hintStyle: TextStyle(fontSize: 16,color: Color(0xFFB3B1B1)),
   errorText: snapshot.error,
 ),
 controller: _passwordController,
 onChanged: _authenticationFormBloc.onPasswordChanged,
                            obscureText: false,
),
class AppColors {
  static MaterialColor hex(String hex) =>
      AppColors._factoryColor(AppColors._getColorHexFromStr(hex));

  static MaterialColor _factoryColor(int color) {
    return MaterialColor(color, <int, Color>{
      50: Color(color),
      100: Color(color),
      200: Color(color),
      300: Color(color),
      400: Color(color),
      500: Color(color),
      600: Color(color),
      700: Color(color),
      800: Color(color),
      900: Color(color),
    });
  }

  static int _getColorHexFromStr(String colorStr) {
    colorStr = "FF" + colorStr;
    colorStr = colorStr.replaceAll("#", "");
    int val = 0;
    int len = colorStr.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = colorStr.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        val = 0xFFFFFFFF;
      }
    }
    return val;
  }
}

// Example: In your app
// ...
class MyExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
    	height: 100.0,
      	width: 100.0,
      	decoration: BoxDecoration(
    		color: AppColors.hex('#000000'),	
    ),
    );
  }
}
Column( 
  crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( child: Text('${payment.name}',textAlign: TextAlign.left,), color: Colors.redAccent, ), ...... )
 decoration: BoxDecoration(
          border: Border(
            top: BorderSide(width: 16.0, color: Colors.lightBlue.shade600),
            bottom: BorderSide(width: 16.0, color: Colors.lightBlue.shade900),
          ),
          color: Colors.white,
        ),
extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
}
appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(signedIn ? 'Home' : 'Sign In'),
      ),
Container(
      height: 120.0,
      width: 120.0,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
              'assets/assets/alucard.jpg'),
          fit: BoxFit.fill,
        ),
        shape: BoxShape.circle,
      ),
    )
const color = const Color(0xffb74093); // Second `const` is optional in assignments.
Text(
  'Hello world',
  style: TextStyle(
    decoration: TextDecoration.underline,
  ),
)
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];

ListView.separated(
  padding: const EdgeInsets.all(8),
  itemCount: entries.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 50,
      color: Colors.amber[colorCodes[index]],
      child: Center(child: Text('Entry ${entries[index]}')),
    );
  },
  separatorBuilder: (BuildContext context, int index) => const Divider(),
);
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
import 'package:flutter/material.dart';

void main() {
  runApp(
    new MaterialApp(
      title: 'Hello World App',
      home: new myApp(),
    )
  );
}

class myApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Hello World App'),
      ),
      body: new Center(
        child: new Text(
          'Hello, world!'
        ),
      ),
    );
  }
}
Text("Border test",
    style: TextStyle(
      inherit: true,
      fontSize: 48.0,
      color: Colors.pink,
      shadows: [
        Shadow( // bottomLeft
          offset: Offset(-1.5, -1.5),
          color: Colors.white
        ),
        Shadow( // bottomRight
          offset: Offset(1.5, -1.5),
          color: Colors.white
        ),
        Shadow( // topRight
          offset: Offset(1.5, 1.5),
          color: Colors.white
        ),
        Shadow( // topLeft
          offset: Offset(-1.5, 1.5),
          color: Colors.white
        ),
      ]
    ),
);
String capitalize(String s) {
  if (s == null || s.isEmpty) {
    return s;
  }
  return s.length < 1 ? s.toUpperCase() : s[0].toUpperCase() + s.substring(1);
}
star

Sun Nov 27 2022 15:32:15 GMT+0000 (UTC)

#flutter
star

Tue Nov 08 2022 10:57:04 GMT+0000 (UTC)

#flutter
star

Tue Nov 08 2022 10:52:17 GMT+0000 (UTC) https://codingwithtashi.medium.com/isoltate-flutter-dart-multithreading-cf5f67de9b46

#flutter #dart
star

Wed Oct 19 2022 04:21:14 GMT+0000 (UTC) https://medium.com/@mibcoder/folder-creation-in-flutter-a554c238b7e8

#dart #flutter
star

Mon Oct 10 2022 22:46:16 GMT+0000 (UTC) https://www.fluttercampus.com/guide/176/how-to-make-multi-line-textfield-input-textarea-in-flutter/

#dart #flutter
star

Thu Oct 06 2022 15:54:44 GMT+0000 (UTC)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:58:50 GMT+0000 (UTC)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:19:52 GMT+0000 (UTC)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:18:34 GMT+0000 (UTC)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 11:22:44 GMT+0000 (UTC)

#dart #flutter #bloc #page #view
star

Sat Aug 27 2022 13:04:41 GMT+0000 (UTC)

#flutter #dart
star

Thu Jul 21 2022 09:37:04 GMT+0000 (UTC)

#flutter #dart
star

Thu Jul 14 2022 04:59:44 GMT+0000 (UTC)

#flutter #dart
star

Fri May 27 2022 06:04:14 GMT+0000 (UTC) https://stackoverflow.com/questions/53577962/better-way-to-load-images-from-network-flutter

#dart #flutter
star

Tue May 24 2022 20:56:04 GMT+0000 (UTC) https://stackoverflow.com/questions/54437448/charts-flutter-labels-text-on-x-axis-overlapping-each-other

#dart #flutter
star

Fri May 20 2022 14:41:48 GMT+0000 (UTC) https://stackoverflow.com/questions/49713189/how-to-use-conditional-statement-within-child-attribute-of-a-flutter-widget-cen

#flutter
star

Tue Apr 05 2022 11:46:23 GMT+0000 (UTC)

#flutter #dart
star

Sat Feb 19 2022 05:43:45 GMT+0000 (UTC)

#flutter #dart
star

Sun Feb 13 2022 20:38:55 GMT+0000 (UTC)

#flutter #dart
star

Fri Feb 11 2022 08:09:17 GMT+0000 (UTC) https://imgur.com/a/gMhKD7B

#flutter #dart
star

Wed Feb 09 2022 18:54:34 GMT+0000 (UTC) https://imgur.com/a/TrU40gV

#flutter #dart
star

Wed Feb 09 2022 08:26:10 GMT+0000 (UTC)

#dart #flutter
star

Sun Jan 30 2022 11:39:22 GMT+0000 (UTC)

#flutter #dart
star

Sun Jan 30 2022 09:21:01 GMT+0000 (UTC)

#flutter #dart
star

Sun Jan 30 2022 08:43:08 GMT+0000 (UTC)

#flutter #dart
star

Fri Jan 28 2022 16:49:28 GMT+0000 (UTC) https://stackoverflow.com/questions/63873338/what-does-widgetsflutterbinding-ensureinitialized-do

#dart #flutter
star

Tue Jan 25 2022 14:02:13 GMT+0000 (UTC)

#flutter #dart
star

Sun Jan 23 2022 19:33:41 GMT+0000 (UTC)

#dart #flutter
star

Sun Jan 23 2022 10:05:33 GMT+0000 (UTC)

#dart #flutter
star

Sun Jan 23 2022 08:57:24 GMT+0000 (UTC) https://www.youtube.com/watch?v=EgtPleVwxBQ&t=64s

#dart #flutter
star

Fri Jan 21 2022 20:22:34 GMT+0000 (UTC)

#dart #flutter
star

Fri Jan 14 2022 15:10:07 GMT+0000 (UTC) https://gist.github.com/rahulbagal/4a06a997497e6f921663b69e5286d859

#flutter
star

Sat Sep 18 2021 00:29:49 GMT+0000 (UTC) https://stackoverflow.com/questions/58819979/is-there-a-way-to-create-a-text-field-with-a-prefix-that-is-always-visible-in-fl

#dart #flutter
star

Tue Sep 14 2021 15:43:06 GMT+0000 (UTC) https://api.flutter.dev/flutter/widgets/RichText-class.html

#dart #flutter
star

Tue Sep 14 2021 12:54:07 GMT+0000 (UTC) https://rrtutors.com/tutorials/how-to-rotate-flutter-widget

#flutter #android
star

Tue Sep 14 2021 04:23:19 GMT+0000 (UTC) https://stackoverflow.com/questions/54135078/how-to-solve-error-running-pod-install-in-flutter-on-mac

#dart #flutter
star

Sat Sep 11 2021 03:44:46 GMT+0000 (UTC) https://pub.dev/packages/shared_preferences

#flutter
star

Fri Aug 27 2021 05:58:23 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-threading-5c3a7b0c065f

#flutter #dart
star

Fri Aug 27 2021 05:28:55 GMT+0000 (UTC) https://medium.com/flutterdevs/threading-in-flutter-e5b84c7d8d31

#flutter #dart #threading
star

Sun Jul 04 2021 12:02:09 GMT+0000 (UTC) https://gist.github.com/matteocrippa/3a8b84c7b49c10bc070e58a66860e83f#file-flutter-md

#flutter #dart
star

Sun Jul 04 2021 12:00:39 GMT+0000 (UTC) https://github.com/Temidtech/Flutter-Cheat-Sheet/blob/master/README.md

#dart #flutter
star

Mon Jun 28 2021 14:12:38 GMT+0000 (UTC) https://www.advancedinstaller.com/install-test-certificate-from-msix.html

#flutter
star

Wed Jun 09 2021 11:44:26 GMT+0000 (UTC) https://pub.dev/packages/table_calendar

#flutter
star

Fri Apr 23 2021 17:34:56 GMT+0000 (UTC) https://stackoverflow.com/questions/50122394/not-able-to-change-textfield-border-color

#dart #flutter
star

Fri Apr 23 2021 02:25:58 GMT+0000 (UTC)

#dart #flutter
star

Sat Apr 10 2021 06:33:52 GMT+0000 (UTC)

#dart #flutter
star

Thu Mar 25 2021 15:10:11 GMT+0000 (UTC) https://fluttercentral.com/Articles/Post/1056/How_to_add_a_border_to_only_one_part_of_the_container_in_Flutter

#dart #flutter
star

Mon Mar 22 2021 10:50:27 GMT+0000 (UTC) https://stackoverflow.com/questions/29628989/how-to-capitalize-the-first-letter-of-a-string-in-dart

#dart #flutter
star

Wed Mar 17 2021 13:56:41 GMT+0000 (UTC) https://github.com/flutter/flutter/issues/67277

#dart #flutter
star

Tue Mar 16 2021 16:29:48 GMT+0000 (UTC) https://stackoverflow.com/questions/52211283/inserting-image-into-a-container-flutter-app

#dart #flutter
star

Mon Mar 15 2021 10:38:42 GMT+0000 (UTC) https://stackoverflow.com/questions/50081213/how-do-i-use-hexadecimal-color-strings-in-flutter

#dart #flutter
star

Thu Mar 11 2021 14:20:12 GMT+0000 (UTC) https://stackoverflow.com/questions/50614661/how-to-underline-text-in-flutter

#dart #flutter
star

Mon Mar 08 2021 13:00:55 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (UTC)

#flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (UTC)

#flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (UTC)

#flutter
star

Fri Aug 07 2020 16:15:21 GMT+0000 (UTC) https://api.flutter.dev/flutter/widgets/ListView-class.html

#flutter
star

Tue May 12 2020 11:03:36 GMT+0000 (UTC) https://gist.github.com/basselch/51b8a047c5c86355c5859a2e5f198fd0

#dart #flutter
star

Tue May 12 2020 11:02:17 GMT+0000 (UTC) https://stackoverflow.com/questions/48893935/how-to-remove-debug-banner-in-flutter-on-android-emulator

#dart #flutter
star

Wed Jan 22 2020 18:43:41 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter #layouts
star

Wed Jan 22 2020 18:35:33 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter #layout
star

Sun Dec 29 2019 19:42:22 GMT+0000 (UTC) https://kodestat.gitbook.io/flutter/flutter-hello-world

#android #dart #flutter #ios #helloworld
star

Thu Dec 26 2019 18:27:15 GMT+0000 (UTC) https://stackoverflow.com/questions/52146269/how-to-decorate-text-stroke-in-flutter

#dart #flutter #howto

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension