How to

How to Add a Border to a Container in Flutter

How to Add a Border to a Container in Flutter

During flutter app development, you have to use a lot of widgets. These widgets could be text, row, columns, stack, and containers. Sometimes you might need to add a border to a container widget to create a UI box like a button, key, or card. Borders help to organize content, draw attention to specific parts of the UI, and enhance the overall aesthetic. In this practical guide, we are going to learn how to add a border to a container in Flutter. You can simply add borders to container flutter by applying the BoxDecoration class. I will be giving you an example with a code to add borders to containers in Flutter. Moreover, you can change the border’s width, height, color, or radius. You can also add a border to only one or more than one side of the container. Such as only the left side of the container or only the top and bottom of the container, etc. What You Need to Know About Flutter Containers and BoxDecoration In Flutter, the Container widget is one of the most versatile widgets, often used as a building block for more complex UIs. The BoxDecoration class provides customization options that can be applied to containers to add styles like borders, shadows, background colors, gradients, and more. This allows you to create unique, customized elements in your app’s interface. Why Add Borders to Containers in Flutter? Adding borders to containers serves both functional and aesthetic purposes. Borders can: Highlight specific parts of the app, such as buttons or active items. Create distinct sections in a list or layout. Enhance the visual design by adding style and structure to the UI. Help achieve consistency across different widgets or screens in an app. Add Border to Containers To add a border to a container in flutter is not a big deal. You just need to wrap a widget in a container and add BoxDecoration class to it as in the code below. Container( width: 150, height: 150, decoration: BoxDecoration( border: Border.all( width: 5, color: Colors.black, ), ), ), As you can see there are some defined parameters like width, height, and colors. You can change the values of these parameters and put them according to your needs. Customizing the Border Color You can use different colors to create visually appealing borders. Flutter provides a wide range of color options in the Colors class, such as Colors.blue, Colors.red, and even custom color values using Color(0xFF000000). Here’s an example: Container( width: 150, height: 150, decoration: BoxDecoration( border: Border.all( width: 3, color: Colors.blueAccent, ), ), ), In this example, the border is blue with a thickness of 3 pixels. You can customize the border to match your app’s color scheme or design preferences. Changing Border Thickness The width parameter in Border.all allows you to adjust the thickness of the border. The default thickness is 1.0, but you can set it to any value. Here’s how to change the border thickness: Container( width: 150, height: 150, decoration: BoxDecoration( border: Border.all( width: 8, // Adjust the thickness as desired color: Colors.green, ), ), ), By setting width: 8, the border is now thicker and more prominent. Adding Rounded Corners to Borders To create a rounded border, use the borderRadius property in BoxDecoration. This is particularly useful when creating buttons or cards. Container( width: 150, height: 150, decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.red, width: 3), borderRadius: BorderRadius.circular(15), // Radius for rounded corners ), ), With BorderRadius.circular(15), the container now has rounded corners, giving it a softer, more polished look. Add Border to Specific Sides of Container As discussed earlier, you can add borders to specific sides of a container in Flutter. You just need to specify the side to which you want to add borders and the rest of the code will be the same as above. You can also use the code given below to add a border to a specific side of a container. Container( width: 150, height: 150, decoration: BoxDecoration( border: Border( left: BorderSide(color: Colors.yellow, width: 6), top: BorderSide(color: Colors.pink, width: 10), ), ), ), In this code, the border is applied only to the left and top sides of the container, using different colors and thicknesses for each side. Add Borders to Symmetrical Sides of a Container You can also add borders to the symmetrical side of a container. The side may be symmetrical vertically or horizontally. Use the code given below to add a border to the symmetrical side of a container. Container( width: 150, height: 150, decoration: BoxDecoration( border: Border.symmetric( horizontal: BorderSide(color: Colors.grey, width: 2), vertical: BorderSide(color: Colors.purple, width: 7), ), ), ), With Border.symmetric, you can apply borders to symmetrical sides, making the container visually balanced Adding Dashed or Dotted Borders While Flutter doesn’t have built-in support for dashed or dotted borders, you can achieve this effect by using third-party packages like flutter_dash. Here’s an example using the dotted_border package, which you’ll need to add to your pubspec.yaml file. dependencies: dotted_border: ^2.0.0 Once you have the package, you can use it as follows: import ‘package:dotted_border/dotted_border.dart’; DottedBorder( color: Colors.red, dashPattern: [6, 3], strokeWidth: 2, child: Container( width: 150, height: 150, color: Colors.white, ), ), This code will create a dotted red border around the container. You can adjust dashPattern to control the length and spacing of the dots or dashes. Adding Shadows to Borders in Flutter Adding shadows to borders can give your containers a 3D effect, making them look more prominent on the screen. Use the boxShadow property in BoxDecoration to achieve this effect. Container( width: 150, height: 150, decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.black, width: 2), borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 3, blurRadius: 5, offset: Offset(0, 3), ), ], ), ), The boxShadow property adds a subtle shadow to the container, enhancing its depth and making it stand out. Using Gradient Borders in Flutter Flutter doesn’t directly support gradient borders, but you can create the effect by layering widgets. Here’s how to create a gradient border using

Read More »

How to Add Borders to TextField in Flutter

TextField in Flutter is a text input widget that is most commonly used to collect inputs from users. We can the input either from a hardware keyboard or an on-screen keyboard. We can use the TextField widget in different forms like building forms, sending messages, creating search experiences, and many more. Flutter TextField allows different kinds of customizations like styling and alignment of the text as well as the cursor inside the TextField. Adding borders to TextField in Flutter is also a major concern of developers while building an app. Delivering the best user experience to end-users is always the utmost priority of developers as well as enterprises. In order to accomplish that, you need to value several aspects of building a user-friendly app. Adding borders to TextField in Flutter You can add borders to TextField in Flutter to make your UI more interactive. Making each and every field prominent that is present on your screen is the only way to make your app user-friendly. A TextField in any flutter app usually requires a hint text and a label. Let’s move towards the code to add borders to TextField in Flutter. Related Post – How to change text color in flutter? Screenshots of the Output As you can see, we have declared the label as “Name”. And you can see, the text field is showing “Name” as the label. Additionally, we defined the border color as gray and its circular radius as “10”. All the results are displayed accordingly in the code. Furthermore, we declared the hint text as “Enter your name”. We declared its color as black, width as “2” and circular radius as 15. As you can see in the screenshot above, the label moves upwards and the hint text displays. It has a border around it with an increased width and circular radius representing what to write in the field. Moreover, if there exists any error in the TextField flutter, the border will change its color to red. Conclusion Thus, you might become aware of the importance of adding borders to TextFields in Flutter after going through this article. We hope this blog helps you one way or the other. Furthermore, if you have any questions or suggestions, you can leave a comment below. Also, you can hire a flutter developer to discuss your ideas related to flutter app development.

Read More »

How to implement a dropdown list in flutter?

A dropdown button is a widget that helps users to select a value or an option from a set of values. The dropdown list is an important element in an app that increases the ease of the users using the app. In this article, we are going to learn how to implement a dropdown list in Flutter. For example, you have a form with city selection. There are two widgets that you can use to show those city details. One option is using the radio button, which allows for selecting a single value. The other option is to use DropDownButton. In scenarios like this, using a dropdown widget will be the best option. This is because you can add a large list of cities. And when the user selects a city, it will show only that selected city in particular. So, it is much more likely to provide a better user experience to the end-user. Code to Add DropDown Button in Flutter Screenshots of Results

Read More »

How to Store Data in Firebase Cloud Firestore Using Flutter App

In the recent article, we gave you a complete guide on how to integrate firebase with your Android, iOS, and Web flutter apps. Before we move on, you should give it a look. If you know how to do that, let’s move forward to learn how to store data in the cloud firestore for flutter apps. In mobile app development, storing and saving users’ data is the most important part of your app. You can save data in different ways using cloud firestore. You can either save the data locally, which means that you can’t share it with others, or save it permanently. So If you want to share your data, you need to save it in the cloud. One of the easiest solutions to this problem is Google’s Cloud Firestore database. Cloud Firestore is a flexible and scalable NoSQL-style database. It is the best approach for small-sized projects to store and sync data for client and server-side development. Unlike traditional databases that require a lot of work to insert data, Firestore lets you save JSON blobs to collections. This method doesn’t limit you to structure your data and allows you to change it at any time. Creating Firestore Database After that, you’re done creating the project and integrating it with the flutter app, now it’s time to create the Firestore database. For this purpose, click on the Firestore database option appearing in the left navigation menu bar on the firebase homepage. As shown here: The cloud firebase window will appear. Click on the “Create database” button. See here: As you click on the create database, a new popup window will appear asking you to choose production mode or test mode. Now the question is which one to choose? The production mode has increased security which requires a series of steps to consider. You won’t be able to handle the requests or the errors if you’re not ready for them. So we choose test mode which you can alternatively call debug mode. In this mode, you can make changes, remove errors, etc. We are moving on with test mode. As I said earlier, you can choose production mode if you’re ready for it. No enforcement. 😛 When you select a mode, the next step is to state the location where you want to create the database. There are different locations to choose from. By clicking on the Cloud Firestore location dropdown, you’ll be able to choose a multi-regional or regional location. You can choose the location according to your requirements or that is closest to your location and then click ‘enable’. As you click enable, the Firebase will provision your Cloud Firestore database and you will be ready to use the database and perform what we are here for. The database console page is shown in the figure below: Collections and Documents in NoSQL A NoSQL database is made up of collections that contain documents in it. A document basically contains the fields that you plan to store, fields being the information or the parameters. You can add collections using simple steps. Let me give you a quick go-through of it. Click on “start collection” in the Cloud Firebase console. A new “start a collection” popup will appear. Enter a collection ID, which is a set of documents that contain data. Then click next. But It will require a document ID that denotes a particular set of data. And then you have to enter different fields like the name, age, or height of a person. We are going to have a coding approach using the flutter app that we integrated with firebase. Add, Update, Delete or Fetch Documents in Firestore Using Flutter App In contrary to storing data in firestore through the console, you can also store data in firestore using the flutter app.To accomplish this task, firstly, you need to create a model to store the data. But here, we are storing users’ data like name, age, etc. Creating a model To organize the data of users, we need to create a model from which we can access the data of an individual or everyone present in the model. So the code to create a model in the flutter app is given below. class UserModel{   UserModel({     required this.name,     required this.phone,     required this.age,   });     String name;   String phone;   int age;   Map<String, dynamic> toJson() => <String, dynamic>{         ‘name’: name,         ‘phone’: phone,         ‘age’: age,       };     factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(     name: json[‘name’] as String,     phone: json[‘phone’] as String,     age: json[‘age’] as int,   ); } Add a Document So you can add a document in firestore using the flutter app with the code given below. Future<UserModel> insertFirestore(UserModel model) async {   try {     final document = await FirebaseFirestore.instance         .collection(collectionName)         .add(model.toJson());     model.id = document.id;     return model;   } catch (e) {     rethrow;   } } Update the Document You can update an existing document in firestore using the code as follows. Future updateFirestore(UserModel model) async {   try {     await FirebaseFirestore.instance         .collection(collectionName)         .doc(model.id)         .update(model.toJson());   } catch (e) {     rethrow;   } } Delete a Document But If you want to delete any document in firestore, you can use the code given below. Future deleteFirestore(String documentId) async {   try {     await FirebaseFirestore.instance         .collection(collectionName)         .doc(documentId)         .delete();   } catch (e) {     rethrow;   } } Fetch a Document You can also fetch the data stored in a particular document in Firestore using the flutter app. Just use the code given below. Future<UserModel> fetchOneFirestore(String id) async {   try {     return parseModel(await FirebaseFirestore.instance         .collection(collectionName)         .doc(id)         .get());   } catch (_) {     rethrow;   } } Fetch all Documents You can also fetch all the documents stored in Firestore. Future<List<UserModel>> fetchAll() async {   try {     final _data =         await FirebaseFirestore.instance.collection(collectionName).get();     return _data.docs.map((document) => UserModel.fromJson(document.data())).toList();

Read More »

What Is FlutterFlow? A Practical Guide to Design Flutter Apps of the Future

You must be familiar with the flutter framework; an application development platform that has transformed the way of building mobile, web, and desktop apps. Nowadays, many businesses rely on the Flutter framework to build beautiful, scalable, and responsive apps. With the release of FlutterFlow, things have now been easier. Owing to this, designing platforms have also tightened their belts to compete for the best design features. The release of FlutterFlow has surprised the whole community with its amazing and easy-to-use features. There are different platforms available that offer designing UI/UX for your apps. But FlutterFlow overcomes all of them due to its obvious features which we will be discussing shortly. Let’s move towards knowing what is Flutter Flow? Its features, Pricing, Resources, and much more. What is FlutterFlow? FlutterFlow is an online low-code visual builder for native mobile applications. You can create beautiful interfaces, dynamic apps, user-generated content apps, business apps, and much more. FlutterFlow was released back in late 2021, especially for the Flutter framework. It was developed by two former Google engineers as a third-party visual app builder. As discussed earlier, FlutterFlow has a drag & drop feature which allows you to build elegant custom applications within an hour. Let’s move towards some more exciting features of Flutter Flow. Features of FlutterFlow

Read More »

What is Dio in Flutter? Best Practices to Handle Networking in Flutter

During application development, managing network requests could be one of the hectic tasks for you. If you managed the network requests efficiently, your app is likely going to succeed in the market. Responses returned by a network may contain unexpected results, and in order to have a better user experience, you need to take care of such snags in advance. In this article, we are going to get familiar with Dio in Flutter. When you start working on a large application, you need to do something more advanced. Your application will face lots of problems with network handling. In that case, we need some advanced connection library that has extra features like interceptors, logs, cache, etc. that will be helpful in many tasks like adding the token authentication for each request and logging requests. In this article, we’re going to learn about Dio and have a look at the best practices for handling networking in Flutter. you can also hire a flutter developer for this task. What is Dio in Flutter? Dio is a powerful HTTP client for Dart. It supports interceptors, global configuration, FormData, request cancellation, file downloading, and timeout, among others. Flutter offers an HTTP package that’s good for performing basic network tasks but is pretty intimidating to use when handling some advanced features. If we compare the HTTP package with Dio, Dio provides an intuitive API for performing advanced networking tasks with minimal effort. The normal HTTP library can do the things which dio does and we get it in flutter SDK too. But it’s not that easy to learn or understand the http library so dio would be better. Related Topic – How to add Firebase project in Flutter app Get Started with Dio To get started with Dio, we first need to add dependencies. dependencies:dio: ^3.0.8 Then install the package using the command line in your terminal and import it: To install the package:  flutter pub get Or pub get Now use this in your dart code: import ‘package:dio/dio.dart’; GET Request To use methods of the Dio HTTP client, we have to create an instance of the Dio client. After that, we can call all methods of Dio. As you can see in the code below, we have created an instance of Dio to call GET requests. Future<dynamic> getData() async {     try {       Response response;       var dio = Dio();       /// apiUrl is basically the route from where you get data       response = await dio.get(‘$apiUrl/persons’);       debugPrint(response.data.toString());     } catch (_) {       rethrow;     }   } POST Request The instance of Dio provides a POST method by which we can pass param in JSON format. After getting the request using the Dio instance, await for the request you want to post. Future postData() async {     try {       Response response;       var dio = Dio();       /// apiUrl is basically the route from where you get data       response = await dio.post(‘$apiUrl/persons’, data: {         ‘name’: ‘xyz’,         ‘age’: ’22’,         ‘gender’: ‘Male’,       });       debugPrint(response.data.toString());     } catch (_) {       rethrow;     }   } Multiple Concurrent Requests When you need to call different APIs in the same instance of time it tends to get confusing a lot. At that time, we can use dio to get the responses from different APIs. Future multipleConcurrentRequests() async {     var dio = Dio();     try {       List<Response> response = await Future.wait(         [           dio.post(‘$apiUrl/persons’),           dio.get(‘/token’),         ],       );     } catch (_) {       rethrow;     }   } To Download a File from Server To download a file from the server, Dio provides a download method. In this method, we have to pass the complete path of the file. Future downloadingFile() async {     Response response;     var dio = Dio();     try {       response = await dio.download(‘https://www.google.com/’, ‘./xx.html’);       return response.data;     } catch (_) {       rethrow;     }   } Get Response Stream With the help of stream response, we can receive a sequence of events. To get a response stream with the Dio client, we need to set responseType stream. Future responseStream() async {     try {       Response<ResponseBody> responseBody;       responseBody = await Dio().get<ResponseBody>(         /// apiUrl is basically your url         apiUrl,         options: Options(           responseType: ResponseType.stream,         ),       );     } catch (_) {       rethrow;     }   } Get Response with Bytes To get a response in bytes, we have to set responseType to ‘bytes’. As you can see: Future responseBtyes() async {     try {       Response<List<int>> response;       response = await Dio().get<List<int>>(         /// apiUrl is basically your url         apiUrl,         options: Options(responseType: ResponseType.bytes),       );     } catch (_) {       rethrow;     }   } Send FormData To send the FormData, we use the instance FormData from the map and specify where we want to send the data and wait for the post. Future sendingFormData() async {     var dio = Dio();     try {       var formData = FormData.fromMap({         ‘name’: ‘xyz’,         ‘age’: 25,       });       /// apiUrl is basically your url       await dio.post(apiUrl, data: formData);     } catch (_) {       rethrow;     }   } Upload Multiple Files to Server by FormData When you need to upload multiple files to the server by your formData, at that time you can use MultiPartFile. And then awaiting for it step by step and vice versa can reduce your valuable time. Additionally, we can pass the required param with the same request. Future uploadingMultipleFiles(File file) async {     var dio = Dio();     try {       var formData = FormData.fromMap(         {           ‘name’: ‘xyz’,           ‘age’: 25,           ‘file’: await MultipartFile.fromFile(             file.path,             filename: ‘upload.txt’,           ),           ‘files’: [             await MultipartFile.fromFile(‘./text1.txt’, filename: ‘text1.txt’),             await MultipartFile.fromFile(‘./text2.txt’, filename: ‘text2.txt’),           ]         },       );       /// apiUrl is basically your url       var response = await dio.post(apiUrl, data: formData);       return response;     } catch

Read More »

Top 15 Flutter Interview Questions and Answers You Must Know

Flutter interview questions for senior developers and answers have been one of the hot topics in cross-platform application development. As a developer or even a beginner, you need to be aware of certain interview questions that could be asked. Originally developed by Google, Flutter is an open-source framework that offers a fast, productive, and reliable application development experience for all digital platforms. Flutter has gained a lot of popularity in a very short period. Developers love to choose flutter over any other platform because of its independence and simplicity, unlike other platforms. Flutter is the only framework that allows building Android and iOS apps without making any changes to the code. Flutter Interview Questions and Answers (All about Flutter and Dart)

Read More »

How to Contribute to Flutter? Step-by-Step Guide

Flutter is an open-source single codebase framework that offers to build beautiful, fast, and scalable multiplatform apps. It supports Android, iOS, Web, Windows, Linux, and macOS platforms. Flutter always welcomes its users to join their team. If any individual using flutter is having any issue while coding, he can simply pull a request, file an issue on GitHub, and ask for help in their mailing list, in chat channels, or on Stack Overflow to contribute to flutter. Similarly, developers who want to help the one’s filing issues are also encouraged to do so. Improving the developers’ experience has been Flutter’s utmost priority. Interestingly, flutter grants commit access (which includes full rights to the issue database, such as being able to edit labels) to people who gain their trust through a commitment to Flutter. Every developer at some point must have thought of contributing to flutter. You can also contribute to flutter as a flutter developer and even if you have not used flutter in your life. 👉 Flutter roadmap and Strategy Should I be a Pro at Flutter to Contribute to it? It is never the case that you need to be a pro at flutter in order to contribute to it. You don’t have to be a PRO or a 10x developer to land a PR. If you can’t make a code contribution because you have just started, Flutter has a lot of easy-fix issues for you. Which include document changes or adding new samples to the documentation. The flutter team always helps individuals land a PR and they are very generous. Undoubtedly, maintainers are always available to help you out with any issue in one way or the other. How can you contribute to Flutter? You can contribute to flutter in different ways. You can create issues, make code contributions to the flutter framework or engine, improve the existing samples, or land the requested features for the plugins. Here is a quick step-by-step guide on how to contribute to open-source flutter. Step 1 Head over flutter organization on GitHub and select your concerned repository from the repository tab which has 27 repositories as of now. Flutter project on GitHub has several repositories. Some of the important repositories are as following: Step 2 Choose an issue of the type you are most experienced at or find issues labeled as ‘easy fix’, ‘good first contribution’, ‘entertaining new contributor project’, ‘documentation’, ‘d: API docs’. Step 3 If you’re not sure about the solutions to an issue, you can talk to maintainers to solve the issue. You can join Flutter project’s Discord server and consult with the exact concerned person about your issue. Explore different channels there and find the one representing relevant purpose to your issue. As mentioned earlier, flutter team is readily available anytime to help you pave out from any issue you’re facing. Step 4 There is an option in GitHub to fork the repository. You can clone it and do the changes to solve the issue. Keep in mind that all the changes you make will remain in your custody until you pull a request. Moreover, if you have discovered a breaking change, you should design a document presenting the change. You should highlight the root cause, the purpose of change, what problem it caused and how possibly it can be rectified. For further information about submitting a PR to flutter, you can check out the Flutter tree hygiene wiki page here. How to see commits in GitHub? Commits are the changes that you make in a repository that you fork. You can post snapshots of the commits when you pull a request. Step 5 Last but not least, after you have pulled the request, wait for reviews and work on it. Once any of the maintainers find your request solid, you’ll receive an LGTM (looks good to me) comment on your PR. It will be ready to be merged into the repository. Congrats!! It’s your success. Conversely, on the other hand, you don’t need to get demotivated if your PR gets closed. It is totally fine, indeed happens with most of us. Every closed PR has a lesson for you to learn. That’s what we’re here for. It is important to create an issue before sending PR. It’s always beneficial to create an issue so that you can discuss the issue with other maintainers before sending a PR. In addition to the documents, there are many companies that provide flutter app development companies You can also hire flutter app developers to contribute to Flutter from the Flutter YouTube channel, there are many pages on our Wiki, and an article Contributing to Flutter: Getting Started on Medium may be of interest. For a curated list of pages see the sidebar on the wiki’s home page. They are more or less listed in order of importance.

Read More »