#onpress
Explore tagged Tumblr posts
blogdeprogramacion · 2 years ago
Text
Crear un modal en Flutter con 2 botones
Crear un modal en Flutter con 2 botones aparece primero en nuestro https://jonathanmelgoza.com/blog/crear-un-modal-en-flutter/
Hoy hablamos sobre cómo crear un modal en Flutter con dos botones de opción, cancelar y confirmar, te dejo una función lista, para integrar en tus proyectos rápidamente y te explico lo que hacemos para que no te pierdas de nada.
Recientemente, he estado trabajando en un proyecto de aplicación móvil multiplataforma.
La elección tomada fue Flutter por su simplicidad y el gigante detrás de esta tecnología.
En este proyecto he tenido que experimentar mucho con esta tecnología, por lo que próximamente estaré subiendo más snippets de código.
Hoy les hablaré un poco sobre una funcionalidad que recientemente tuve que implementar y que creo es muy necesaria en cualquier proyecto.
Veremos como crear un modal en Flutter con dos botones de acción: cancelar y eliminar.
Por supuesto puedes cambiar estas opciones, pues la estructura es la misma, puedes hacer por ejemplo un cancelar y confirmar.
Como te he comentado antes he puesto el código en una función para que sea más fácil integrar en tus proyectos.
Solo debes de tomar en cuenta a partir del código del botón que abre el modal para llamar la función.
onPressed: () async showConfirmDelete(context); ,
Lo único que hacemos es llamar a una función y mandar como parámetro nuestro contexto.
Ahora vemos la función principal de este post.
showConfirmDelete(BuildContext context) Widget cancelButton = ElevatedButton( child: Text("Cancelar"), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(primarycolor), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), ), onPressed: () print("Cancelando.."); Navigator.of(context).pop(); , ); Widget continueButton = ElevatedButton( child: Text("Eliminar"), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(redcolor), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), ), onPressed: () print("Eliminando.."); // Otras acciones de eliminar , ); // set up the AlertDialog AlertDialog alert = AlertDialog( title: Text("Eliminar cuenta"), content: Text("¿Estás seguro de eliminar permanentemente tu cuenta?"), actions: [ cancelButton, continueButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) return alert; , );
Lo primero que hacemos es crear nuestros dos botones de acción: cancelar y eliminar.
Agregamos un pequeño estilo, en mi caso el botón de Eliminar lo he puesto en rojo.
Puedes notar que para simplemente salir del modal para por ejemplo el botón de cancelar usamos:
Navigator.of(context).pop();
Nuestro modal lo creamos con AlertDialog donde podemos personalizar el título y contenido, además de por supuesto agregar los botones que creamos antes.
Como puedes ver no es nada complicado, pero es muy útil en proyectos de apps móviles con Flutter.
Si este artículo sobre cómo crear un modal en Flutter te ha sido de utilidad, no olvides compartirlo en tus redes sociales y dejarnos un comentario en la sección de abajo si tienes cualquier duda respecto a este tema, será un placer ayudarte.
¡Hasta luego!
3 notes · View notes
foggynightdonut · 23 days ago
Text
OnPress book Printing
fair prices
0 notes
ai-play · 9 months ago
Text
Flutterで位置情報を取得する方法は、locationというパッケージを使うのが一般的です¹。locationパッケージは、iOSとAndroidの両方で位置情報の取得やパーミッションの管理を簡単に行うことができます¹。
locationパッケージを使うには、以下の手順を踏む必要があります。
- pubspec.yamlファイルにlocationパッケージの依存関係を追加する¹。
- iOSの場合は、Info.plistファイルに位置情報の使用目的とバックグラウンドモードの設定を追加する¹。
- Androidの場合は、AndroidManifest.xmlファイルに位置情報のパーミッションの設定を追加する¹。
- locationパッケージをインポートし、Locationクラスのインスタンスを作成する¹。
- serviceEnabledメソッドとrequestServiceメソッドで位置情報サービスの有効化を確認する¹。
- hasPermissionメソッドとrequestPermissionメソッドで位置情報のパーミッションの取得を確認する¹。
- getLocationメソッドで現在の位置情報を取得する¹。
- onLocationChanged.listenメソッドで位置情報の変化を監視する¹。
以下は、locationパッケージを使って位置情報を取得するサンプルコードです²。
```dart
import 'package:flutter/material.dart';
import 'package:location/location.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Location location = Location();
bool? _serviceEnabled;
PermissionStatus? _permissionGranted;
LocationData? _locationData;
@override
void initState() {
super.initState();
_checkLocationService();
}
// 位置情報サービスの有効化を確認するメソッド
Future<void> _checkLocationService() async {
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled!) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled!) {
return;
}
}
_checkLocationPermission();
}
// 位置情報のパーミッションの取得を確認するメソッド
Future<void> _checkLocationPermission() async {
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
_getLocation();
}
// 現在の位置情報を取得するメソッド
Future<void> _getLocation() async {
_locationData = await location.getLocation();
setState(() {});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Location Example'),
),
body: Center(
child: _locationData != null
? Text(
'Latitude: ${_locationData!.latitude}\nLongitude: ${_locationData!.longitude}')
: Text('No location data'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 位置情報の変化を監視する
location.onLocationChanged.listen((LocationData currentLocation) {
_locationData = currentLocation;
setState(() {});
});
},
child: Icon(Icons.location_on),
),
),
);
}
}
```
このサンプルコードは、位置情報サービスとパーミッションの確認��行った後、現在の位置情報を取得し、テキストで表示するものです。また、フローティングアクションボタンを押すと、位置情報の変化を監視し、テキストを更新するようになっています。
以上、Flutterで位置情報を取得する方法についての回答でした。ご参考になれば幸いです。😊
¹: [Location | Flutter Package](^1^)
²: [How to get user current location in Flutter - KindaCode](^3^)
ソース: Bing との会話 2024/3/2
(1) 【flutter(location)】位置情報の取得・距離計算 #Flutter - Qiita. https://qiita.com/appzs/items/f6c5afbeaefd6cca7de5.
(2) Location In Flutter. Learn to get current location of user .... https://medium.flutterdevs.com/location-in-flutter-27ca6fa1126c.
(3) 【flutter(location)】位置情報の取得・距離計算 #Flutter - Qiita. https://qiita.com/appzs/items/f6c5afbeaefd6cca7de5.
(4) How to get user current location in Flutter - KindaCode. https://www.kindacode.com/article/how-to-get-user-current-location-in-flutter/.
(5) FlutterのGeoLocationで位置情報を取ってみる #Flutter - Qiita. https://qiita.com/kazutxt/items/1af63e9e32a780daba32.
(6) Flutterの位置情報パッケージを比較してみた |パイオニア .... https://note.jpn.pioneer/n/n25998ea6422f.
0 notes
flutter4u · 1 year ago
Text
Custom Date Range Picker for Flutter
Custom Date Range Picker for Flutter custom_date_range_picker custom_date_range_picker Usage ... floatingActionButton: FloatingActionButton( onPressed: () { showCustomDateRangePicker( context, dismissible: true, minimumDate: DateTime.now().subtract(const Duration(days: 30)), maximumDate: DateTime.now().add(const Duration(days: 30)), endDate: endDate, startDate: startDate, backgroundColor:…
Tumblr media
View On WordPress
0 notes
flutterdevs · 1 year ago
Text
How to Design Custom Flutter Buttons
Tumblr media
Flutter provides a flexible and powerful framework for designing user interfaces, including buttons. While Flutter offers a variety of built-in button widgets, you may want to create custom buttons that match your app's unique design. In this blog post, we will walk through the steps to design custom Flutter buttons.
Step 1: Define the Button Design
The first step in designing a custom Flutter button is to define its visual appearance. Consider the following aspects:
Button Shape: Decide whether you want a rectangular, circular, or any other shape for your button.
Button Size: Determine the dimensions of your button, such as width and height.
Button Colors: Choose the background color, text color, and any other colors you want to use for your button.
Button Typography: Select the font style, size, and weight for the button text.
Step 2: Create a Custom Button Widget
Once you have defined the design of your custom button, you can create a custom widget to encapsulate its functionality and appearance. Here's an example of how you can create a custom button widget: import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  const CustomButton({required this.text, required this.onPressed});
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(
        text,
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
      style: ElevatedButton.styleFrom(
        primary: Colors.blue, // Set the background color of the button
        onPrimary: Colors.white, // Set the text color of the button
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8), // Set the button shape
        ),
      ),
    );
  }
}
In this example, we create a CustomButton widget that extends the StatelessWidget class. The widget takes two required parameters: text for the button label and onPressed for the button's callback function.
Step 3: Implement the Custom Button
To use the custom button in your Flutter app, follow these steps:
Import the custom button widget into your Dart file.
Add an instance of the CustomButton widget to your app's widget tree.
Provide the necessary parameters, such as the button text and the callback function.
Here's an example of how you can implement the custom button in your app: import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Custom Button Example'),
        ),
        body: Center(
          child: CustomButton(
            text: 'Click Me',
            onPressed: () {
              // Add your button's functionality here
              print('Button clicked!');
            },
          ),
        ),
      ),
    );
  }
}
In this example, we create a simple Flutter app with a custom button. When the button is clicked, it prints a message to the console.
Conclusion
Designing custom Flutter buttons allows you to create buttons that align with your app's unique design requirements. By following the steps outlined in this blog post, you can easily create and implement custom buttons in your Flutter app.
I hope this blog post helps you in designing custom Flutter buttons. Happy coding!
0 notes
brilworks · 1 year ago
Text
React Native Best Practices
Tumblr media
What Does it Mean by Best Practices?
It goes in the coding world — there are no strict rules, but some guidelines (more like suggestions) that many coders tend to avoid while writing code. When you’re first starting out, it can be tempting to skip over coding guidelines. After all, your code might work just fine without them. But as your codebase grows bigger, you’ll start to realize that adhering to guidelines is essential for keeping your code healthy and maintainable.
There are several benefits that we have discussed in our Java blog; you can read our blog about the benefits of clean code and best practices.
Tumblr media
1. Use TypeScript with Your React Native App
TypeScript is a statically typed programming language which means it requires explicitly defining the data types for variables, functions, and other elements. This not only leads to more reliable code but also helps developers catch bugs during the compilation process.
Consider the following to calculate order pricefunction calculateOrderPrice(order) { return order.price + 1200; }
The current code works fine, but it doesn’t tell us much about what properties the order object contains, which could lead further to a crash if we try to access a property that doesn’t exist.
To prevent the crash and enhance readability, we can use TypeScript. TypeScript is a programming language that adds types to JavaScript. This means that we can specify the type of each property in the object, which will help us avoid errors.interface Order { price: number; name: string; taxPercentage: number; } function calculateOrderPrice(order: Order) { const { price, taxPercentage } = order; const taxValue = price * taxPercentage; return price + taxValue; }
Here is the same function, but now you and your editor are aware of the object properties and their types in code, which makes it easier to extend the functionality.
2. Functional Components over the Class Components
In React Native, you will have two main components: Functional and Class components. But functional components are the way to go in React Native. They’re simpler, more concise, and faster than class components. This makes them easier to read, write, and test. Plus, they can improve your app’s performance.
If you’re not sure what components are, they’re functions that return React elements. So if you’re looking for a way to improve your React Native code, use functional components over class components. They’re the future of React Native development.
Class Component Exampleimport React, { Component } from 'react'; class ClassComponent extends Component { constructor(props) { super(props); this.state = { count: 0, }; } incrementCount = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <View> <Text style={styles.h1}>Class Component</Text> <Text>Count: {this.state.count}</Text> <Button title='Increment' onPress={this.incrementCount}/> </View> ); } } export default ClassComponent;
In this class component example, we’re using the Component class from react to create a component. State is managed within the component’s constructor, and the render method defines the component’s UI.
Functional Component Exampleimport React, { useState } from 'react'; const FunctionalComponent = () => { const [count, setCount] = useState(0); const incrementCount = () => { setCount(count + 1); }; return ( <View> <Text style={styles.h1}>Functional Component</Text> <Text>Count: {count}</Text> <Button title='Increment' onPress={incrementCount}/> </View> ); }; export default FunctionalComponent;
In this functional component example, we’re using the useState hook from react to manage state. The component is defined as a simple JavaScript function that returns JSX to render the UI.
3. Import your dependencies in order
When you have a bunch of imports in one file, it could be a headache trying to find that one specific import you need if you have not organized your imports properly. Therefore it is essential to order imports in a consistent way.
At the same time, you should also ensure that the dependencies have a proper sequence of imports. If the order is not correct, it can affect how components behave and lead to bugs that are hard to find.
Here’s an example of how you can organize your imports:
External imports — react
Internal imports, like relative paths — ../button
In folder imports like ./styles.ts
The imports may be sorted alphabetically in every group
Every group must be divided by white space
import React from 'react'; import { TouchableOpacity, View } from 'react-native'; import { Button, Card } from '../components' import { MainLayout } from '../layouts' import { StyledCard } from './styles.ts'
You can use formatting tools like Eslint and Prettier to automate and enforce the correct import order to avoid such issues.
4. Use Path Alias to avoid long imports
Path aliases are a way to create shorter and more meaningful import paths in your code. This can be helpful when you have a deep or nested folder structure, and it can make your imports easier to read and understand.
For example, instead of writing a long import like this:import { IconButton } from '../../components/buttons'; import { CircleButton } from 'components/buttons'; OR import { CircleButton } from 'buttons';
Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.
Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.
Path Alias in TypeScript
Create or update the tsconfig.json file in your project if it doesn’t exist already.
Set the baseUrl to . , which represents the root of the directory. This sets the starting point for all path aliases.
Add path aliases to the paths object. In this example, we have two path aliases defined:
// tsconfig.json { "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, // Path alias config "baseUrl": ".", "paths": { // This needs to be mirrored in babel.config.js // Components is a directory with sub directories "components/*": ["src/components/*"], // We want to expose the exports of the buttons index file "buttons": ["src/components/buttons/index"] } } }
Now, TypeScript will be able to understand and parse the following imports:import { CircleButton } from "components/buttons" import { CircleButton } from "buttons"
2. React Native Path Alias
First, install the babel-plugin-module-resolver as a developer dependencyyarn add - dev babel-plugin-module-resolver npm install babel-plugin-module-resolver - save-dev
Now we can update the babel.config.js file to use the **module-resolver**plugin and point to our directories.**// babel.config.js** module.exports = function (api) { api.cache(true) return { presets: ["babel-preset-expo"], plugins: [ [ "module-resolver", { alias: { // This needs to be mirrored in tsconfig.json components: "./src/components", buttons: "./src/components/buttons", }, }, ], ], } }
Responsive style properties in React refer to the use of functions to create an adaptive user interface or a layout that adjusts to various screen sizes and orientations. Developing a responsive React Native app can be done in multiple ways, and one of them is by using react-native-normalize. This handy library offers functions that help you create responsive layouts effortlessly.
5. Implement Crash Analytics Tools
Crash analytics tools are like your magic tools that keep an eye on your app 24/7. They do real-time monitoring to help you identify crashes and errors. These tools analyze the crash data and give you the lowdown on what’s causing the chaos.
So, if you’re in the development process, and suddenly, the app crashes out of the blue. With the implementation of crash analytics, you can easily find the root causes of these crashes.
There are a bunch of awesome crash analytics tools out there, like Sentry, Firebase, Crashlytics, and more. They’re like your trusty companions, helping you debug and rescue your app from potential crashes.
Read more at https://www.brilworks.com/blog/react-native-best-practices/
0 notes
magnigeeks · 1 year ago
Text
Flutter and Material Design: Perfect Partners for UI/UX
Welcome to the world of Flutter and Material Design—where code meets creativity and pixels dance to perfection. In this blog, we'll take a trip into the world of UI/UX design, where Flutter and Material Design prove to be the ideal partners for designing apps that are not only functional but also aesthetically beautiful. So buckle up as we explore the fascinating world of Material Design and Flutter, where technology and fashion converge.
They say, "Two heads are better than one," and that's certainly the case when it comes to Flutter and Material Design. Flutter, Google's cross-platform app development framework, works in tandem with Material Design which is also a Google's design system. Together, they produce an aesthetic and practical symphony that is perfect.
The Flutter Advantage
But why choose Flutter in the first place? Here's a tangy tidbit for you: Flutter is the "fast food" of app development. It's quick, efficient, and satisfies your craving for speedy UI/UX design.
Code That Paints the Screen
In Flutter, you paint the screen with code. The declarative UI approach allows you to create visually stunning interfaces using just a few lines of code. Let's dive into a quick example:
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello, Flutter!'),
        ),
        body: Center(
          child: Text('Welcome to the world of Flutter and Material Design!'),
        ),
      ),
    ); } } You see, Flutter makes it a breeze to design your app's structure.
The Material Design
Let's now add a little Material Design magic to the mixture. A set of design concepts and user interface elements provided by Material Design make sure that your app not only looks fantastic but also complies with accepted standards for user experience. It's like having a qualified designer at your service.
Ready-Made UI Components
You can save time and effort by using the built-in Material widgets in Flutter. From buttons to cards to navigation drawers, you'll find a plethora of ready-made components to make your design process a breeze.
Here's a snappy code snippet using a Material button:
ElevatedButton(
  onPressed: () {
    // Action to perform on button press
  },
  child: Text('Click Me'),
)
Flutter and Material Design aren't just a partnership; they're a dynamic duo! This combination delivers a beautiful marriage of design and functionality, whether you're creating slick software for your firm or a feature-rich application for a client.
Flutter and Material Design Services by Magnigeeks
Before we go, if you're looking for professional help to unlock the full potential of Flutter and Material Design, look no further. Magnigeeks is here to give top-tier UI/UX design services using these dynamic technologies. Your app idea can become a magnificent reality with the help of our talented designers and developers, who will also guarantee an unparalleled user experience that complements the personality of your company.
Join Magnigeeks in leveraging the power of Flutter and Material Design, and together, let's build an app that not only performs flawlessly but also captivates customers with its elegant, user-friendly design. Visit https://magnigeeks.com/ to get in touch with us right away and start your UI/UX adventure!
So there you have it, the journey into the world of Flutter and Material Design—a delightful blend of tech and style. These two partners are your best allies in creating apps that not only work flawlessly but look fantastic while doing so. Get ready to embark on your UI/UX adventure with Flutter and Material Design, and watch your app come to life in style!
0 notes
kamanori · 1 year ago
Text
The Eternal Question:Biological variations on a Platonic dialogue
:Jakob von Uexküll, Thure von Uexküll
Abstract. The reinterpretation of Nature by biology, which will prevail inspite of all obstacles, has brought our thinking closer to antiquity, giving usthe chance to reinvigorate our perused terminology with the help of theresources to be found in the thoughts of the greatest minds of mankind. Theway to Plato thus being cleared, I perceived the idea to seek enlightenment onpressing biological questions from the great Sage. As means to this end, Ichose to make Socrates continue one of his dialogues, with the adjustment ofgiving him the knowledge of our contemporary biological problems. Thussome kind of interaction between the Ancients and ourselves is created, to ourconsiderable benefit.
0 notes
flutteragency · 1 year ago
Text
Handling Events and User Input in Flutter
Tumblr media
This blog article will explore the exciting topic of handling user input and events in Flutter.
You’ll discover that user interaction is critical to developing exciting and dynamic Flutter mobile applications as you progress in your app development journey.
Let’s get down to the very details of how Flutter handles user input and events so that we can develop responsive, user-friendly apps. Also you can read this blog from our official website Events and User Input in Flutter.
Understanding User Input and Events
In Flutter, user input is any action a user performs responding to interactions like tapping buttons, typing text, or scrolling.
On the other side, events are the responses triggered by user input.
To deliver a seamless user experience, you must record these events as a Flutter developer and manage them accordingly.
Handling Button Taps
The user interface of any application must include buttons. Let’s look at how the ‘onPressed’ property may be used to manage button taps:
import 'package:flutter/material.dart';class ButtonTapDemo extends StatelessWidget {  const ButtonTapDemo({super.key});  @override  Widget build(BuildContext context) {    return Scaffold(      body: Center(        child: ElevatedButton(          onPressed: () {            // This function will be called when the button is tapped            print('Hey There! How are you?');          },          child: const Text('Tap Me'),        ),      ),    );  }}
In the above example, when the user taps the button, it will print ‘Hey There! How are you?’ to the console. Other than the print() function, we can perform many more actions when the button is tapped like, navigate to another screen, update the content, etc.
Handling Text Input
The TextField widget can be used to manage user-provided text input. Here is an example of how to retrieve user input from a text field:
import 'package:flutter/material.dart';class TextFieldEventDemo extends StatefulWidget {  const TextFieldEventDemo({super.key});  @override  _TextFieldEventDemoState createState() => _TextFieldEventDemoState();}class _TextFieldEventDemoState extends State<textfieldeventdemo> {  String input = '';  @override  Widget build(BuildContext context) {    return Scaffold(      body: Center(        child: Column(          mainAxisAlignment: MainAxisAlignment.center,          children: [            TextField(              onChanged: (value) {                // This function is called whenever the user types in the text field                setState(() {                  input = value;                });              },              decoration: const InputDecoration(                labelText: 'Write something',                border: OutlineInputBorder(),              ),            ),            Text(input)          ],        ),      ),    );  }}</textfieldeventdemo>
In this example, we have used a StatefulWidget which shows that the TextField widget takes the input from the user and updates the text below it. Whenever the user will type in the textfield, the onChange method of the TextField will be triggered and the state of the text below it will be changed.
Gestures Handling
Flutter has a variety of widgets to handle various gestures, including tapping, swiping, and dragging.
Let’s look at an illustration of how the GestureDetector widget handles a tap gesture:
import 'package:flutter/material.dart';class GestureDetectorDemo extends StatelessWidget {  const GestureDetectorDemo({super.key});  @override  Widget build(BuildContext context) {    return GestureDetector(      onTap: () {        // This function is called when the user taps anywhere on the widget        print('Screen tapped!');      },      child: const Scaffold(        body: Center(          child: Text(            'Tap anywhere on the screen',          ),        ),      ),    );  }}
In this example, we have wrapped the whole screen in the GestureDetector. So, when the user taps anywhere on the screen, the ‘onTap’ function is triggered and ‘Screen tapped!’ will be printed in the console.
Handle Slider Changes
Sliders help choose a value from a range. To track and react to changes in slider value, utilize Flutter’s Slider widget.
import 'package:flutter/material.dart';class SliderDemo extends StatefulWidget {  const SliderDemo({super.key});  @override  _SliderDemoState createState() => _SliderDemoState();}class _SliderDemoState extends State<sliderdemo> {  int _value = 35;  @override  Widget build(BuildContext context) {    return Scaffold(      body: Center(        child: Padding(          padding: const EdgeInsets.all(15.0),          child: Center(            child: Row(              mainAxisAlignment: MainAxisAlignment.spaceEvenly,              mainAxisSize: MainAxisSize.max,              children: [                SizedBox(                  width: 70,                  child: Icon(                    Icons.volume_up,                    size: _value.toDouble(),                  ),                ),                Expanded(                  child: Slider(                    value: _value.toDouble(),                    min: 10.0,                    max: 60.0,                    divisions: 10,                    activeColor: Colors.deepPurple,                    inactiveColor: Colors.orange,                    label: _value.toString(),                    onChanged: (double newValue) {                      setState(() {                        _value = newValue.round();                      });                    },                    semanticFormatterCallback: (double newValue) {                      return '${newValue.round()} dollars';                    },                  ),                ),              ],            ),          ),        ),      ),    );  }}</sliderdemo>
In this example, we have a sound icon and a slider next to it, based on the slider’s value the size of the sound icon will be changed. When the user drags the slider’s head, the onChanged() function will be triggered and the size of the sound icon will be changed.
Handling Checkbox Changes
Binary choices are frequently selected using checkboxes. You can monitor changes in the checkbox’s state and respond to them using Flutter’s Checkbox widget.
import 'package:flutter/material.dart';class CheckBoxDemo extends StatefulWidget {  const CheckBoxDemo({super.key});  @override  _CheckBoxDemoState createState() => _CheckBoxDemoState();}class _CheckBoxDemoState extends State<checkboxdemo> {  bool? valuefirst = false;  bool? valuesecond = false;  @override  Widget build(BuildContext context) {    return MaterialApp(      home: Scaffold(        body: SizedBox(            child: Column(          mainAxisAlignment: MainAxisAlignment.center,          crossAxisAlignment: CrossAxisAlignment.start,          children: <widget>[            const Text(              'Checkbox without Header and Subtitle:',              style: TextStyle(fontSize: 15.0),            ),            Row(              children: <widget>[                Checkbox(                  // checkColor: Colors.greenAccent,                  // activeColor: Colors.red,                  value: valuefirst,                  onChanged: (bool? value) {                    setState(() {                      valuefirst = value;                    });                  },                ),                Text(valuefirst.toString())              ],            ),            Row(              children: [                Checkbox(                  value: valuesecond,                  onChanged: (bool? value) {                    setState(() {                      valuesecond = value;                    });                  },                ),                Text(valuesecond.toString())              ],            )          ],        )),      ),    );  }}</widget></widget></checkboxdemo>
In this example, there are two checkBoxes whose byDefault value is false and when tapped, the onChanged() function is triggered and the value of that particular checkbox is set to true.
Conclusion
Handling user input and events is essential to creating responsive Flutter applications. Using several Flutter widgets and callbacks, we explored how to handle button taps, collect text input, detect gestures, respond to checkbox changes, and handle slider interactions.
Congratulations on mastering the art of using Flutter to handle user input and events!
Hence, these abilities enable you to develop responsive and responsive and fascinating apps. Visit www.flutteragency.com to stay updated on the latest Flutter trends, best practices, and development tips.
Frequently Asked Questions (FAQs)
1. Which widget does Flutter use for user input?
Flutter uses various widgets to handle user inputs such as, gesture detector, inkwell, textfield, checkbox, button, etc. The most popular widget for user input is textfield.
2. How does Flutter handle user input?
Flutter provides us with a very rich set of widgets and event handling mechanisms. Using these widgets and event handlers, developers can easily capture and respond to user input which makes the application user friendly and responsive.
3. How to Handle User Input and Events in Flutter?
To manage user input and events in Flutter:
1. Select the appropriate widget based on the desired user input, like TextField, GestureDetector, InkWell, Checkbox, Radio, Switch, Slider, DropdownButton, etc. 2. Attach event handlers to widgets that respond to user interactions. These handlers, or callback functions, execute when the corresponding events occur. 3. Use the TextField widget to capture textual input. You can provide a controller to track and manipulate the input and define callbacks for text changes.
By following these steps, you can efficiently handle user input and events in Flutter, creating a seamless and interactive user experience.
0 notes
flutteronetutorials · 1 year ago
Text
How to Create a Custom Dialog Box in Flutter
Tumblr media
Are you looking to enhance the user experience in your Flutter app by adding a custom dialog box? Dialog boxes are a great way to display important information, prompt user actions, or provide additional context. In this tutorial, we'll walk you through the process of creating a custom dialog box in Flutter, step by step.
Introduction
Dialog boxes are an essential component of any interactive app. While Flutter provides built-in dialog widgets, creating a custom dialog box allows you to tailor the design and functionality to your specific needs. By following the steps outlined in this tutorial, you'll be able to create a custom dialog box that aligns with your app's branding and provides a seamless user experience.
Tumblr media
Creating a Custom Dialog Box
Prerequisites
Before we begin, make sure you have Flutter installed and set up on your development machine. You can follow the official Flutter documentation to get started if you haven't already.
Step 1: Set up the Project
Start by creating a new Flutter project using the Flutter CLI or your preferred IDE. Open the project in your code editor and navigate to the lib directory.
Step 2: Implement the CustomDialogBox Widget
Inside the lib directory, create a new file called custom_dialog_box.dart. This file will contain the code for our custom dialog box widget. Copy and paste the following code into the custom_dialog_box.dart file:
Step 3: Customize the Dialog Box
In the CustomDialogBox class, we'll define the structure and appearance of our custom dialog box. Let's add the necessary code to create a visually appealing and user-friendly dialog box. Replace the // TODO comment with the following code:
Step 4: Customize the Dialog Box Content
Inside the contentBox method, we'll define the content of our dialog box. This can include a title, description, images, buttons, or any other widget you desire. Replace the // TODO comment with the following code:
Step 5: Show the Custom Dialog Box
To show the custom dialog box in your app, navigate to your app's main page or any other page where you want to trigger the dialog box. Add a button or any other widget that triggers the dialog box when pressed. Replace the existing onPressed event handler with the following code:
Final code
In the above code, the CustomDialogBox class represents the custom dialog box widget. It extends StatelessWidget and creates a Dialog widget with a custom content box. The contentBox method defines the content of the dialog, including the title, description, and a close button. To use the custom dialog box, you can call showDialog and pass an instance of the CustomDialogBox widget as the builder. This will display the dialog box on the screen. You can customize the appearance and content of the dialog box by modifying the properties and widgets within the contentBox method. Remember to import the necessary packages, such as flutter/material.dart, to use the required Flutter widgets and classes.
Output
Tumblr media
Creating a Custom Dialog Box in Flutter
Conclusion
Congratulations! You've successfully created a custom dialog box in Flutter. By customizing the appearance and content of the dialog box, you can create unique and interactive experiences for your app users. Feel free to experiment with different designs and add additional functionality based on your specific requirements. Remember to test your app thoroughly and gather user feedback to ensure the dialog box provides a seamless and intuitive user experience. Happy coding! Read the full article
0 notes
codehunter · 2 years ago
Text
Using styled-components with props and TypeScript
I'm trying to integrate TypeScript into our project and so far I stumbled upon one issue with styled-components library.
Consider this component
import * as React from "react";import styled from "styled-components/native";import { TouchableOpacity } from "react-native";// -- types ----------------------------------------------------------------- //export interface Props { onPress: any; src: any; width: string; height: string;}// -- styling --------------------------------------------------------------- //const Icon = styled.Image` width: ${(p: Props) => p.width}; height: ${(p: Props) => p.height};`;class TouchableIcon extends React.Component<Props> { // -- default props ------------------------------------------------------- // static defaultProps: Partial<Props> = { src: null, width: "20px", height: "20px" }; // -- render -------------------------------------------------------------- // render() { const { onPress, src, width, height } = this.props; return ( <TouchableOpacity onPress={onPress}> <Icon source={src} width={width} height={height} /> </TouchableOpacity> ); }}export default TouchableIcon;
Following line throws 3 errors, that are same in nature <Icon source={src} width={width} height={height} />
Type {source: any; width: string; height: string;} is not assignableto type IntrinsicAttributes ... Property 'onPress' is missing in type{source: any; width: string; height: string;}
Not entirely sure what this is and how to fix it, do I somehow need to declare these on Icon or something of this sort?
EDIT: typescript v2.6.1, styled-components v2.2.3
https://codehunter.cc/a/reactjs/using-styled-components-with-props-and-typescript
0 notes
caylakyazilimci · 2 years ago
Text
react native expo firebase authenticate ile login ve register örneği
Tumblr media
firebase authenticate kullanarak login ve register işlemi yapacağız. Firebase panelinden authanticate kısmını seçip gerekli import linklerini oradan aldıktan sonra
expo so react native tarafı şöyle
app.js sayfasına home ve login sayfalarını ekleyin
--------
<NavigationContainer> <Stack.Navigator> <Stack.Screen options={{ headerShown: false }} name="Login" component={LoginScreen} /> <Stack.Screen name="Home" component={HomeScreen} /> </Stack.Navigator> </NavigationContainer>
login.js sayfası
-----
import React, { useEffect, useState } from 'react' import { KeyboardAvoidingView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native' import { getAuth, createUserWithEmailAndPassword,signInWithEmailAndPassword } from "firebase/auth"; const auth = getAuth();
const LoginScreen = ({ navigation }) => { const [email, setEmail] = useState('') const [password, setPassword] = useState('')
useEffect(() => { const unsubscribe = auth.onAuthStateChanged(user => { if (user) { navigation.navigate("Calender") } })
return unsubscribe }, [])
const handleSignUp = () => { createUserWithEmailAndPassword(auth,email, password) .then(userCredentials => { const user = userCredentials.user; console.log('Registered with:', user.email); }) .catch(error => alert(error.message)) }
const handleLogin = () => { signInWithEmailAndPassword(auth,email, password) .then(userCredentials => { const user = userCredentials.user; console.log('Logged in with:', user.email); }) .catch(error => alert(error.message)) }
return ( <KeyboardAvoidingView style={styles.container} // behavior="padding" >
<View style={styles.inputContainer}>
<Text style={styles.logo}>Hr Calender</Text>
<TextInput placeholder="Email" value={email} onChangeText={text => setEmail(text)} style={styles.input} /> <TextInput placeholder="Password" value={password} onChangeText={text => setPassword(text)} style={styles.input} secureTextEntry /> </View>
<View style={styles.buttonContainer}> <TouchableOpacity onPress={handleLogin} style={styles.button} > <Text style={styles.buttonText}>Login</Text> </TouchableOpacity> <TouchableOpacity onPress={handleSignUp} style={[styles.button, styles.buttonOutline]} > <Text style={styles.buttonOutlineText}>Register</Text> </TouchableOpacity> </View> </KeyboardAvoidingView> ) }
export default LoginScreen
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, inputContainer: { width: '80%' }, input: { backgroundColor: 'white', paddingHorizontal: 15, paddingVertical: 10, borderRadius: 10, marginTop: 5, }, buttonContainer: { width: '60%', justifyContent: 'center', alignItems: 'center', marginTop: 40, }, button: { backgroundColor: '#0782F9', width: '100%', padding: 15, borderRadius: 10, alignItems: 'center', }, buttonOutline: { backgroundColor: 'white', marginTop: 5, borderColor: '#0782F9', borderWidth: 2, }, buttonText: { color: 'white', fontWeight: '700', fontSize: 16, }, buttonOutlineText: { color: '#0782F9', fontWeight: '700', fontSize: 16, }, logo: { fontSize: 30, color: 'black', paddingBottom: 15, textAlign: 'center' },
})
home.js sayfası
-------------
import { useNavigation } from '@react-navigation/core' import React from 'react' import { StyleSheet, Text, TouchableOpacity, View } from 'react-native' import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); console.log("auth",auth)
const HomeScreen = () => { const navigation = useNavigation()
const handleSignOut = () => { signOut(auth) .then(() => { navigation.navigate("Login") }) .catch(error => alert(error.message)) }
return ( <View style={styles.container}> <Text>Email: {auth.currentUser?.email}</Text> <TouchableOpacity onPress={handleSignOut} style={styles.button} > <Text style={styles.buttonText}>Sign out</Text> </TouchableOpacity> </View> ) }
export default HomeScreen
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' }, button: { backgroundColor: '#0782F9', width: '60%', padding: 15, borderRadius: 10, alignItems: 'center', marginTop: 40, }, buttonText: { color: 'white', fontWeight: '700', fontSize: 16, }, })
daha fazlasına bu elemanın repodan bakabilirsini https://github.com/mattfrances/FirebaseExpoAuthentication
0 notes
tomssharepointdiscoveries · 2 years ago
Text
Buttons to use with SPFX
Absolutely awesome buttons that work well.
Had to use:
import { AwesomeButton } from 'react-awesome-button';
import 'react-awesome-button/dist/styles.css'; And:
    <AwesomeButtonProgress
                type="primary"
                onPress={(element, next) => {
                    _commentAdd();
                    next();
                }
                }>
                Respond to agent
            </AwesomeButtonProgress >
For example.
0 notes
ai-play · 9 months ago
Text
Flutter のトーストとは、画面の一部に一定期間表示される小さなポップアップメッセージのことです。操作の確認や短い情報の提供に使われます。Flutter では SDK 標準のトーストは用意されていないため、別途ライブラリを組み込んでやる必要があります。一般的には **fluttertoast**¹ というライブラリを使ってトーストを表示します。以下は fluttertoast を使ったコードの例です。
```dart
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class Sample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('サンプル'),
),
body: RaisedButton(
child: Text('トーストの表示'),
onPressed: () {
Fluttertoast.showToast(msg: 'ボタンがクリックされました');
},
),
);
}
}
```
¹: [fluttertoast | Flutter Package](^3^)
ソース: Bing との会話 2024/3/2
(1) [Flutter] トーストを表示する | BUILDBOX.net. https://buildbox.net/flutter-toast/.
(2) 【Flutter】Fluttertoastの使い方|トーストを表示する - Code .... https://coderenkin.com/flutter-fluttertoast/.
(3) [Flutter]トースト(toast)を表示するには? - ちょげぶろぐ. https://www.choge-blog.com/programming/fluttertoastshow/.
(4) flutterでトースト表示|blue - note(ノート). https://note.com/blue_69/n/n0fb83e03541a.
(5) Flutterで簡単にToastメッセージを表示する方法とカスタマイズに .... https://gr-st-dev.tistory.com/2901.
(6) undefined. https://pub.dev/packages/fluttertoast.
0 notes
flutter4u · 1 year ago
Text
Day Night Time Picker in flutter
Flutter Day Night Time Picker – A day night time picker in Flutter with Zero Dependencies. Installation Add to pubspec.yaml. dependencies: day_night_time_picker: Usage To use plugin, just import package import 'package:day_night_time_picker/day_night_time_picker.dart'; Example TextButton( onPressed: () { Navigator.of(context).push( showPicker( context: context, value: _time, onChange:…
Tumblr media
View On WordPress
0 notes
flutterdevs · 1 year ago
Text
A Comprehensive Guide of Flutter AppBar Widget
Tumblr media
The AppBar widget is an essential component in Flutter for creating a top-level navigation bar in your application. It provides a consistent and customizable way to display the toolbar, leading icon, title, and actions at the top of the screen. In this blog post, we will explore the various features and usage of the Flutter AppBar widget.
What is the AppBar widget?
The AppBar widget is based on Material Design principles and is part of the Flutter material library. It serves as the primary navigation component for your application and is typically placed at the top of the screen. The AppBar can contain other widgets within its layout, making it versatile for different use cases.
Key Features of the AppBar widget
Toolbar: The AppBar displays the toolbar widgets, including the leading icon, title, and actions. The toolbar provides a space for important controls and information.
Leading Icon: The leading icon is typically an icon or widget placed at the start of the AppBar. It can be used for navigation or to indicate the current screen or context.
Title: The title is a text or widget that represents the current screen or application. It is usually centered within the AppBar.
Actions: Actions are a set of widgets placed at the end of the AppBar. They can be used for additional functionality, such as search, settings, or user profile.
FlexibleSpace: The AppBar can have a flexible space that allows for more customization. This space can contain widgets like images, gradients, or animations.
Usage of the AppBar widget
To use the AppBar widget in your Flutter application, follow these steps:
Import the material library:
import 'package:flutter/material.dart';
Create a Scaffold widget as the root of your application:
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: <link>AppBar</link>(
          title: Text('My App'),
        ),
        body: Container(
          // Your app content goes here
        ),
      ),
    );
  }
}
Customize the AppBar as per your requirements:
appBar: <link>AppBar</link>(
  leading: IconButton(
    icon: Icon(Icons.menu),
    onPressed: () {
      // Handle leading icon press
    },
  ),
  title: Text('My App'),
  actions: [
    IconButton(
      icon: Icon(Icons.search),
      onPressed: () {
        // Handle search action
      },
    ),
    IconButton(
      icon: Icon(Icons.settings),
      onPressed: () {
        // Handle settings action
      },
    ),
  ],
),
Add additional widgets and functionality to your application as needed.
Conclusion
The Flutter AppBar widget is a powerful tool for creating a top-level navigation bar in your application. It provides a consistent and customizable way to display important controls and information. By understanding its features and usage, you can create stunning and user-friendly app bars in your Flutter projects.
I hope this blog post helps you in understanding the Flutter AppBar widget better. Happy coding!
Remember to replace the code snippets with your own implementation and customize the AppBar according to your application's needs.
0 notes